Hi, I am doing Question 4 of the Project Euler puzzles. I wrote some code which is supposed to find the biggest palindrome from the product of 2 numbers. However, this always prints out 900099. I cannot really find any errors in this code, but if you do, please let me know. Any helpful tips on making better code using a different approach is greatly appreciated (my approach was not that great).

#include <iostream>

using namespace std;

bool ispalindrome(int);

int main()
{
	int biggestpal;
    int indicator = 0;

    for (int i = 999; i >= 100 && indicator == 0; i--)
    {
        for (int j = 999; j >= 100; j--)
        {
            biggestpal = i * j;
            if (ispalindrome(biggestpal))
            {
                cout << biggestpal;
                indicator = 1;
                break;
            }
        }
    }

	return 0;
}

bool ispalindrome(int number)
{
	int first,second,third,fourth,fifth,sixth;

	first = number/100000;
	second = number % 100000;
	third = number % 10000;
	fourth = number % 1000;
	fifth = number % 100;
	sixth = number % 10;

	if (first == sixth && second == fifth && third == fourth)
		return true;
	else
		return false;
}

Recommended Answers

All 6 Replies

Hello blee93,
I think there is something wrong with the ispalindrome function.
For example take 101 * 101=10201. 10201 is a palindrome. In you function isplaindrome
first will have zero if 10201 is divided by 100000. Sixth will have 1 (10201 % 10). First is not equal to sixth.
So your function will return false though 10201 is a palindrome.

I think there's a problem with the ispalindrome function. I tried setting number = 123321 and using it as an argument for the ispalindrome function, but it tests false.

That's what i said. The vaiables first and sixth are equal,but the varables second and fifth are not equal if the number is 123321.
second=123321%100000 =23321.
fifth=123321%100=21.

Ohhh thanks Arbus, I fixed it up and now it works. Any other suggestions or different approaches to the problem or is this a good way to approach it?

Yes,there is one method. First you store every digit of the number in an integer array and then you reverse the array and store it into another array. Check if both the arrays are equal. If equal then the number is a palindrome.

Sounds way better actually. Thanks so much for your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.