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 ofj
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 to0
in 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 = 2
andi = 70
,j = 65
in this casei*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 thebreak
don’t do what I think you are waiting for (stop the search), only stop the search with the actuali
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
andj == 99
andi == 99
andj == 98
), you could restrictj
to be always less or equal toi
. - 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]