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;
}
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.
// Project Euler Problem 4
#include <iostream>
usingnamespace 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;
}