Find the largest palindrome made from the product of two 3-digit numbers.

I am new to c++ and not getting the proper output for a question i found in project euler please help me find where i am going wrong. I am getting the answer as 1220045305.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 #include<iostream>
using namespace std;
int main()
{
	long x,y,digit;
	long rev=0;
	  	for(int i=999;i>100;i--)
	{
		for(int j=999;j>100;j--)
		{
			x=i*j;
			y=x;
			 do
           {
               digit = x % 10;
               rev = (rev * 10) + digit;
               x = x / 10;
           }while (x != 0);
           if(y==rev)
           {cout<<rev;
           break;
		   }
		}
	}
  cout<<rev; 
  return 0;
}
Last edited on
Main mistakes:
- you need to set rev=0 EACH time before you start building a new reversed number; otherwise it will just keep getting bigger and bigger; set rev=0 between lines 12 and 13.
- you aren't actually keeping track of the maximum - just outputting every palindrome; you need a separate variable revmax, initialised to 0 and updated if necessary when you find a new palindrome (after current line 20);
- your output comes out as a long chain of digits; add a newline to each cout statement.


Other things to think about:
- you test a lot of unnecessary numbers; for example, since a*b=b*a you calculate each product twice; you could enforce, for example, that j<=i and so reduce the number of checks;
- you don't need to test for the largest palindrome once your product i*j is less than the current maximum, revmax;
- there are more optimal search orders - leave you to think about that;
- I would have a separate function
bool isPalindrome( int n );
so that you can separate this test from the looping strategy;
- your inconsistent indentation makes your code extremely difficult to read; please address this; my personal view (which won't be shared by everyone, I know) is that you would be better indenting with the spacebar, since (i) indenting 8 characters with a typical tab setting runs far too far to the right; (ii) tab settings are different in every editor, and mixing tabs and spaces causes havoc.
Topic archived. No new replies allowed.