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 ofj. The only instruction the for-loop ofjis 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
wthe reverse of the number to test for palindrome is reset his value to0in every execution ofwhile (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 = 2andi = 70,j = 65in this casei*jwould be in first solution= 196in the second= 4550and when you found the first you could not stop the search. In your code using thebreakdon’t do what I think you are waiting for (stop the search), only stop the search with the actualivalue.
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 == 98andj == 99andi == 99andj == 98), you could restrictjto be always less or equal toi. - Using
max_productto 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]