×

# Whats wrong with my code for Prime Palindromes ?

 0 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 #include 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); }  asked 15 Aug '14, 13:52 6★nibnalin 161●1●5●15 accept rate: 0%

 1 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. answered 15 Aug '14, 14:33 1.9k●4●13●17 accept rate: 11%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×194
×188
×47
×36

question asked: 15 Aug '14, 13:52

question was seen: 763 times

last updated: 15 Aug '14, 14:33