scosant
12/17/2012 - 11:33 AM

## projecteuler004 - largest palindrome product

projecteuler004 - largest palindrome product

``````/**
*
* projecteuler004 - largest palindrome product
*
* A palindromic number reads the same both ways. The largest
* palindrome made from the product of two 2-digit numbers
* is 9009 = 91 x 99.
* Find the largest palindrome made from the product of two
* 3-digit numbers.
*/

#include <iostream>
#include <sstream>

bool IsPalindrome(int num);

int main(int argc, char *argv[])
{
std::cout << "Largest palindrome made from "
<< "the product of two 3-digit numbers is: ";
int largest_palindrome = 0;
for (int x = 100; x < 1000; x++) {
for (int y = 100; y < 1000; y++) {
if (IsPalindrome(x * y)) {
if (x * y > largest_palindrome) {
largest_palindrome = x * y;
}
}
}
}
std::cout << largest_palindrome << std::endl;
return 0;
}

bool IsPalindrome(int num) {
// Convert number to string.
std::string num_string;
std::stringstream out;
out << num;
num_string = out.str();

int size = num_string.size() - 1;
for (int i = 0; i < num_string.size() / 2; i++) {
// Check opposite indexes of the string.
if (num_string[i] != num_string[size--]) {
return false;
}
}
return true;
}
``````