6.21.2010

Problem 4 - Project Euler Problems - Palindromes

This problem requires you to find the largest product of three digit numbers that is a palindrome.

There are 2470 of such palindromes; the highest being 993 * 913 [906609] and the lowest being 101 * 101 [10201]

The code I used to get this is as below. Feel free to loo through it, modify and comment! You can view the output file here.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main (int argc, char * const argv[]) {

  int num1;
  int num2;
  string resultString;
 
  for (num1 = 999; num1 > 99; --num1) {
    for (num2 = 999; num2 > 99; --num2) {
      int result = num1 * num2;
      stringstream resultStream;
      resultStream << result;
      resultString = resultStream.str();
   
      {
        /* CHECK FOR PALINDROME */
        int stringSize = resultString.size();
        int midpoint = stringSize / 2;
        bool fault = false;
    
        for (int i = 0; i <= midpoint; ++i) {
          if (resultString[i] != resultString[stringSize - i - 1]) {
            fault = true;
            break;
          }
        }
    
        if (!fault) {
          cout << "Palindrome found!   "
               << num1 << " * " << num2
               << " = " << resultString 
               << " which is a palidrome." 
               << endl;
        }
      }
    }
  }
 
  cout << "Done" << endl;
 
  return 0;
}

No comments: