You are here

C program to find next prime palindrome

C program to find next prime palindrome: a user will enter a number, and we have to find the least number greater than it which is a palindrome as well as prime. For example, if the input is 7 then the output will be 11 as it's a prime as well as a palindrome, if the input is 21 then the output will be 101. In the program, we check if a number is a palindrome and then check if it's prime as it takes less time as primes occur more frequently than palindromes.

C program

#include <stdio.h>
#include <math.h>

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

  printf("Enter an integer\n");
  scanf("%ld", &n);

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

    // Calculating reverse of the number

    while(t)
    {
      r = r*10;
      r = r + t%10;
      t = t/10;
    }

    // If reverse equals original then it's a 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;
}

Download Next prime palindrome program.

Output of program:
Next prime palindrome C program output