Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi, I was solving the 4th Project Euler problem to find the largest palindrome made from the product of two 3-digit numbers, The code :
C++
#include <iostream>

using namespace std;

int reverse(int num)
{
   int num2 = 0;
   while (num > 0)
   {
       num2 *= 10;
       num2 += (num % 10);
       num = ( num - ( num % 10 ) ) / 10;
   }
   return num2;
}

bool is_planidormic(int num)
{
    int rev = reverse(num);
    if (rev == num)
    {
        return true;
    }
    return false;
}

int main()
{
    int num = 0,largest_plan = 0;
    for (int i = 100; i < 1000; i++)
    {
        for (int j = 100; j < 1000; j++)
        {
            num = i*j;
            if (is_planidormic(num))
            {
                largest_plan = num;
            }
        }
    }
    cout << largest_plan << endl;

}

This code reaches 580085 but I googled and found that are larger solution.
Where is the error ?

Thanks, Samuel.
Posted

1 solution

First of all debug your software!
Checking through iterations in the double loop:
C++
for (int i=100; i < 1000; i++)
{
    for (int j=100; j < 1000; j++)
    {
        num = i*j;
        if (is_planidormic(num))
        {
            largest_plan = num;
        }
    }
}

You will see that the product 'num' restarts from low values each time a new inner loop restarts. So happen that on the last iteration you get a new palindrome that is smaller than the 'official' solution, 906609, because you put the palindrome in 'largest_plan' without checking.
Change your code to:
C++
for (int i=100; i < 1000; i++)
{
    for (int j=100; j < 1000; j++)
    {
        num = i*j;
        if (is_planidormic(num))
        {
            if (num > largest_plan)    //Check if actual number is larger that the former
            {
                largest_plan = num;
            }
        }
    }
}

And you'll get the correct answer.

P.S.: I appreciated the downvote, but it would be much better to leave a note about it, so I, and others, could understand where is the wrong...
 
Share this answer
 
v12
Comments
Samuel Shokry 20-Jun-15 17:10pm    
Yeah, Thanks a lot. I forgot it .
Member 14517556 1-Jul-19 11:24am    
I am trying the same question but I am using python. I am attaching my codes here can you please go through it and tell me my mistake.

CODE:
import string
for i in range(100,1000):
for n in range(100,1000):
num1 = i*n
n += 1
while num1 > 0:
r = num1%10
num2 = (10**(len(string(num1))))*r
if num2 == num1 :
print(num1)
else:
continue
i += 1

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900