Blog Archives

Project Euler Problem #4 C++ solution:

/** (From:http://projecteuler.net/index.php?section=problems&id=3)

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Solution: (Brute force)

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void check(int);

int main ()
{
int result = 0;

for (int i = 999; i >= 101; i–)
{
for (int j = i; j >= 101; j–)
{
result = (j *i);
check (result);
}
}
}

void check (int a)
{
string str = static_cast<std::ostringstream*>( &(std::ostringstream() << a) )->str();
string syl_1;
string syl_2;
string syl_3;
static string j ;
int len = (str.length()/2);
syl_1 = str.substr(0, len);
syl_2 = str.substr(len);

for (int i = syl_2.length(); i >=0; i –)
{
if (syl_2[i] != NULL)
syl_3 += syl_2[i];
}
if ((syl_1.compare(syl_3))==0)
{
if (j < str)
j = str;
if (str == j)
cout << j << endl;
}
}