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

Hi everyone. I am new to C++ and am trying to solve problem #4 on project Euler.
The problem asks to find the largest palindrome made from the product of two 3-digit numbers. If someone could look at my code and tell me what I am doing wrong I would really appreciate it. I think I am on the right track but my program will only return 0. Thanks!


// Project Euler Problem 4
#include <iostream>
using namespace std;

bool isValid(int);

int main()
{
int pal, final;


// Finds largest product
for (int a = 999; a >= 100; a--)
{
for (int b = 999; b >= 100; b--)
{
pal = a * b;
if (isValid(pal))
final = a * b;
}
}


cout << final << endl;
return 0;
}


bool isValid(int num)
{
bool status = true;
int digit, rev;

// Tests for palindrome
while (num)
{
digit = num % 10;
num /= 10;
rev = rev * 10 + digit;
}

if (rev == num)
status = true;
else
status = false;
return status;
}

@Jame116

Your main problem, was you are decreasing the variable num, and checking rev against it. That why you get a 0. After fixing that, the result was only one number. But you needed the largest, which is not necessarily the first. Anyway, I made a small correction to your program, and it prints ALL the palindromes. I'll leave it to you to be able to add the code to show just the highest one. If you still run into a problem, repost with your solution, and we'll help from there.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Project Euler Problem 4
#include <iostream>

using namespace std;

bool isValid(int);

int main()
{
	int pal, final;
	// Finds largest product
	for (int a = 999; a >= 100; a--)
	{
		for (int b = 999; b >= 100; b--)
		{
			pal = a * b;
			if (isValid(pal))
				cout << pal << endl;
		}
	}
	return 0;
}


bool isValid(int num)
{
	bool status = true;
	int digit, rev=0, ck_num; // Added new variable
	ck_num = num; // Assigned it to variable num
	
	// Tests for palindrome
	while (num)
	{
		digit = num % 10;
		num /= 10;
		rev = rev * 10 + digit;
	}

	if (rev == ck_num) // Checked it against unchanged variable
		status = true;
	else
		status = false;
	return status;
}
Thanks so much for the help! I was able to get my program to produce the correct answer.
@James116

And what number did you come up with, may I ask?
I got 906609.
@James116

Excellent. Same as I got. I even print out the a and b variable, that made up the palindrome result.
Topic archived. No new replies allowed.