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.

C programming code
#include <stdio.h>
#include <math.h>
#define TRUE 1

int main()
{
  long n, t, r = 0, c, d;

  printf("Enter an integer\n");
  scanf("%ld", &n);    /* n must be a natural number */

  while (TRUE)
  {
    n++;
    t = n;

    /* Calculating reverse of number */

    while(t)
    {
      r *= 10;  /* Compound assignment operator r*=10 => r=r*10 */
      r += t%10;
      t /= 10;
    }

    /* if reverse equals original then it is palindrome */

    if (r == n)
    {
      d = (int)sqrt(n);

      /* Checking prime */

      for (c = 2; c <= d; c++)
      {
        if (n%c == 0)
          break;
      }
      if (c == d+1)
        break;
    }
    r = 0;
  }

  printf("%ld\n",n);

  return 0;
}

Comments

Popular posts from this blog

Difference between asterisk and ampersand operators in c

kbhit in c