Reputation: 241
The task is to find the largest palindrome number made from the product of two 3-digit numbers but I can't understand where i made a mistake.
I made a loop where I get all the possible products of two 3-digit numbers; then I transform the product in an array so that I can verify that is a palindrome number and finally if it is bigger than the last palindrome number, I save it to the variable max_palindrome
This is the code:
#include <iostream>
int number_of_digits(int num){
int digit = 0;
while(num > 0){
digit++;
num /= 10;
}
return digit;
}
int main() {
int max_palindrome = 0;
for(int a = 100; a < 1000; a++){
for(int b = 100; b < 1000; b++){
int product = a * b;
int digits = number_of_digits(product);
// transform number in a vector
int vector_product[digits];
int temporary_num = product;
for(int c = digits-1; c >= 0; c--){
vector_product[c] = temporary_num % 10;
temporary_num /= 10;
}
// verifying that the number is a palindrome
int d = digits-1;
bool palindrome = true;
for(int e = 0; e < digits; e++){
if(vector_product[e] != vector_product[d]){
palindrome = false;
break;
}
d--;
}
if(palindrome && max_palindrome < a){
std::cout<<max_palindrome<<std::endl;
max_palindrome = product;
}
}
}
std::cout<<"The biggest palindrome number from a product of two 3- digits numbers is "<<max_palindrome<<std::endl;
return 0;
}
Upvotes: 1
Views: 75
Reputation: 44258
Your condition is wrong:
if(palindrome && max_palindrome < a){
should be instead:
if(palindrome && max_palindrome < product){
your program may be much simpler if you just convert number to string (could be slightly slower, but you already waste CPU time by doing loop over number twice).
Upvotes: 2