[Solved] C++ program to find the largest palindrome which is product of two two digit numbers [closed]


Some modified version of your code:

#include <iostream>
using namespace std;
int main() {
    int max_product = 0;
    for (int i = 99; i > 9; i--) {
        for (int j = i; j > 9; j--) {
            int product = i * j;
            if (product < max_product)
                break;
            int number = product;
            int reverse = 0;
            while (number != 0) {
                reverse = reverse * 10 + number % 10;
                number /= 10;
            }
            if (product == reverse && product > max_product) {
                max_product = product;
            }
        }
    }
    cout << "Solution: " << max_product << endl;
    return 0;
}

You have various problems:

  • Need one more pair of {, }. After the for-loop of j. The only instruction the for-loop of j is executing is: n = i * j; with the braces the rest of the instruction (testing if it’s a palindrome) are out of the loop.
  • the variable w the reverse of the number to test for palindrome is reset his value to 0 in every execution of while (n != 0) loop resulting in incorrect reverse value (and never find the palindrome).
  • The max palindrome product of 2 two digits number don’t have to be the first one found with this 2 for-loop, eg: suppose that there is 2 valid solutions i = 98, j = 2 and i = 70, j = 65 in this case i*j would be in first solution = 196 in the second = 4550 and when you found the first you could not stop the search. In your code using the break don’t do what I think you are waiting for (stop the search), only stop the search with the actual i value.

Some notes about the modified code:

  • The two for-loop don’t need to be from 99..9, in this case you are testing a lot of product two times (eg: 98*99, are testing when i == 98 and j == 99 and i == 99 and j == 98), you could restrict j to be always less or equal to i.
  • Using max_product to maintain the maximum palindrome product found. And use that info in the inner loop (if (product < max_product)) for early exit when no better solution could be found.

0

solved C++ program to find the largest palindrome which is product of two two digit numbers [closed]