Reputation: 3
I tried to solve Problem 4 of Project Euler with C language but get wrong answers all the time.
// Project Euler - Problem 5
// 09/01/2014
#include <stdio.h>
int a,b,c,digits[14],e,y,z,biggestNum;
void isPalindrome (int x)
{
a = -1;
c = 0;
b = x;
while (b != 0)
{
digits[c] = (b % 10);
b=b/10;
c++;
}
while (c>=a)
{
if(digits[++a]!=digits[--c])
{
break;
}
if(a==c) { biggestNum=x; }
else if(a==c-1) { biggestNum=x; }
}
}
int main (void)
{
for(y=10; y<1000; y++)
{
for(z=10; z<1000; z++)
{
isPalindrome(y*z);
}
}
printf ("%d",biggestNum);
return 0;
}
Can someone tell me what is wrong in my code? Maybe in checking if the num is Palindrome function? thanks The Problem
Upvotes: 0
Views: 894
Reputation: 86691
Your code doesn't find the biggest Palindrome, it finds the last Palindrome if you run through the numbers
10* 10, 10 * 11, 10 * 12, .... 10 * 999
...
999 * 10, 999 * 11, .... 999 * 999
If the largest palindrome happens to be (say) 750 * 750, but also 999 * 11 is a Palindrome, the 999 * 11 will overwrite the correct answer.
You need to test each time that your answer is bigger than the previous biggest answer you had.
Upvotes: 1
Reputation: 40155
change
while (c>=a)
{
if(digits[++a]!=digits[--c])
{
break;
}
if(a==c) { biggestNum=x; }
else if(a==c-1) { biggestNum=x; }
}
to
while (c > a){
if(digits[++a]!=digits[--c])
return ;
}
if(x>biggestNum)//bigger than old value
biggestNum=x;
Upvotes: 0
Reputation: 6642
for(y = 999; y >= 100 ; --y) { for(z = y; z >= 100; --z) { if (isPalindrome(y*z)) { return y*z; // TODO: use temp var } } }
for (i = 0; i < n/2; i++) { if (str[i] != str(n-i)) { return false; } } return true
Upvotes: 1