Zachary Stence

Problem 4: 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 × 99.

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

I first solved this problem October 1st, 2014 in my AP Computer Science class in highschool. I do not have the original code I wrote, but I have solved the problem again and included the code below.

I solved this problem by first writing a function to check whether or not a positive integer is a palindrome. The function first converts the integer to a string, then uses C++11 iterators to check to make sure each number starting at the front and back is equal. Then in main, I iterate through all possible products (starting at 999 * 999 to find the max sooner), and store the maximum palindrome.

#include <iostream>

/**
 * Returns true if x is a palindrome, false otherwise
 * @param x: A positive integer
 */
bool isPalindrome(int x) {
  // Convert x to a string for easier processing
  std::string num = std::to_string(x);
  // Set iterators at first and last characters of string
  auto front = num.begin();
  auto back = num.end() - 1;
  // While iterators haven't passed each other
  while (front < back) {
    // If characters in the string aren't equal, isn't a palindrome
    if (*front != *back) return false;
    // Increment iterators
    ++front, --back;
  }
  return true;
}

int main() {
  int max = 0;
  // Loop through possible products and save maximum
  for (int num1 = 999; num1 >= 111; num1--) {
    for (int num2 = num1; num2 >= 111; num2--) {
      int product = num1 * num2;
      if (product > max && isPalindrome(product)) max = product;
    }
  }
  std::cout << max << std::endl;
}

Answer: 906609