You are not logged in. Please login at www.codechef.com to post your questions!

×

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);

}

asked 15 Aug '14, 13:52

nibnalin's gravatar image

6★nibnalin
1611515
accept rate: 0%


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.

link

answered 15 Aug '14, 14:33

gdisastery1's gravatar image

4★gdisastery1
1.9k41317
accept rate: 11%

edited 15 Aug '14, 14:33

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • 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
×189
×47
×36

question asked: 15 Aug '14, 13:52

question was seen: 769 times

last updated: 15 Aug '14, 14:33