 # Whats wrong with my code for Prime Palindromes ?

I have worked up a solution for Prime Palindromes, and after a lot of debugging, the code started being successful with the sample input and I thought i should submit this, but doing so, it gives me wrong answer!

Can anyone help me figure out my mistakes ?

``````

#include <stdio.h>
#include <stdlib.h>

int isPalindrome(int x) {
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int l = x / div;
int r = x % 10;
if (l != r)
return 1;
x = (x % div) / 10;
div /= 100;
}
return 0;
}

int main(void)
{
int n;
scanf ("%d\n", &n);
int i,j, sum = 0;
int from = n;
int to = 1000000;
int *sieve=(int *)calloc(to+1,sizeof(int));
for(i=2;i<=to;i++)
{
if(sieve[i]==0)
{
if(i>=from)
{
if (isPalindrome(i) == 0)
{
printf ("%d\n", i);
return 0;
}
}
if(i*i<=to)
{
for(j=i;j<=to;j+=i)
{
sieve[j]=1;
}
}
}
}
free(sieve);
}

``````

Hi,
your isPalindrome function looks faulty. In the second while loop you check if the left digit matches with the corresponding right digit, but after they mismatch, you return, that the given number is a Palindrome. Another gotcha, might be the if condition in the main function.

``````if(i*i<=to) // gotcha!
``````

i can be up to 10^6 and thus i*i up to 10^12, which doesn’t fit into the 32bit integer. One might use long long instead.

1 Like
//