Tuesday, 24 January 2012

Next Prime Palindrome

C program to find next prime palindrome

C program to find next prime palindrome: In this code user will enter a number(say n) and we have to find a number greater than n which is a palindrome as well as prime. For example if the input is 7 then output will be 11 as it is prime as well as palindrome, if input is 21 then output will be 101. In our code we first check if a number is palindrome and then check if it is prime as it will take less time as primes occur more frequently then palindromes.



#include<stdio.h>
#include<conio.h>
#include<math.h>
#define TRUE 1

void main()
{
    long n, t, b = 0, c, d;
    clrscr();
    printf("Enter an integer\n");
    scanf("%ld",&n);      /* n must be a natural number */
    while(TRUE)
    {
        n++;
        t=n;
        while(t)
        {
            b*=10;   /* Compound assignment operator b*=10 => b=b*10 */
            b+=t%10;
            t/=10;
        }
        if(b==n)
        {
            d=(int)sqrt(n);
            for(c=2; c<=d; c++)
            {
                if(n%c==0)
                break;
            }
            if(c==d+1)
            break;
        }
        b=0;
    }
    printf("%ld\n",n);
    getch();
}

No comments:

Post a Comment