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 is 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 is prime as it takes less time as primes occur more frequently than palindromes.

C programming code

  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int main()
  5. {
  6.   long n, t, r = 0, c, d;
  7.  
  8.   printf("Enter an integer\n");
  9.   scanf("%ld", &n);
  10.  
  11.   while (1)
  12.   {
  13.     n++;
  14.     t = n;
  15.  
  16.     // Calculating reverse of the number
  17.  
  18.     while(t)
  19.     {
  20.       r = r*10;
  21.       r = r + t%10;
  22.       t = t/10;
  23.     }
  24.  
  25.     // If reverse equals original then it is a palindrome
  26.  
  27.     if (r == n)
  28.     {
  29.       d = (int)sqrt(n);
  30.  
  31.       /* Checking prime */
  32.  
  33.       for (c = 2; c <= d; c++)
  34.       {
  35.         if (n%c == 0)
  36.           break;
  37.       }
  38.       if (c == d+1)
  39.         break;
  40.     }
  41.     r = 0;
  42.   }
  43.  
  44.   printf("%ld\n",n);
  45.  
  46.   return 0;
  47. }

Download Next prime palindrome program.

Output of program:
Next prime palindrome C program output