Next smallest prime palindrome - GeeksforGeeks

10 May, 2021
Given a positive integer N where . The task is to find the smallest prime palindrome greater than or equal to N.Examples:  
Input: 8
Output: 11

Input: 7000000000
Output: 10000500001
Approach:  
The Naive approach is to loop from N + 1 until we found the next smallest prime palindrome greater than or equal to N.Efficient Approach: Let’s say P = R is a the next smallest prime-palindrome greater than or equal to N. Now since R is a palindrome, the first half of the digits of R can be used to determine R up to two possibilities. Let k be the first half of the digits in R. For eg. if k = 123, then R = 12321 or R = 123321.Thus, we iterate through each k upto 105 and create the associated palindrome R, and check whether R is a prime or not. Also, we will handle the odd and even palindromes separately, and break them when we found our result.Below is the implementation of above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; #define ll long long int // Function to check whether// a number is primebool isPrime(ll n){    if (n < 2) return false;         for (ll i = 2; i <= sqrt(n); i++)    {        if (n % i == 0) return false;    }    return true;} // function to generate next// smallest prime palindromell nextPrimePalindrome(ll N){for (ll k = 1; k < 1000000; k++){         // Check for odd-length palindromes    string s = to_string(k);    string z(s.begin(), s.end());    reverse(z.begin(), z.end());     // eg. s = '1234' to x = int('1234321')    ll x = stoll(s + z.substr(1));     if (x >= N and isPrime(x)) return x;     // Check for even-length palindromes    s = to_string(k);    z = string(s.begin(), s.end());    reverse(z.begin(), z.end());     // eg. s = '1234' to x = int('12344321')    x = stoll(s + z);     if (x >= N and isPrime(x)) return x;}} // Driver Codeint main(){    ll N = 7000000000;         // Function call to print answer    cout << nextPrimePalindrome(N) << endl;         return 0;} // This code is contributed by// sanjeev2552
// Java implementation of above approachclass GFG{ // Function to check whether// a number is primestatic boolean isPrime(long n){    if (n < 2) return false;         for (long i = 2; i <= Math.sqrt(n); i++)    {        if (n % i == 0) return false;    }    return true;} // reverse the Stringstatic String reverse(String s){    String s1 = "";    for(int i = s.length() - 1; i >= 0; i--)        s1 += s.charAt(i);         return s1;} // function to generate next// smalongest prime palindromestatic long nextPrimePalindrome(long N){    for (long k = 1; k < 1000000l; k++)    {                 // Check for odd-length palindromes        String s = ""+k;        String z;        z = reverse(s);             // eg. s = '1234' to x = int('1234321')        long x = Long.parseLong(s + z.substring(1, z.length()));             if (x >= N && isPrime(x))            return x;             // Check for even-length palindromes        s = ""+(k);        z = s;        z = reverse(z);             // eg. s = '1234' to x = int('12344321')        x = Long.parseLong(s + z);             if (x >= N && isPrime(x)) return x;    }    return -1;} // Driver Codepublic static void main(String args[]){    long N = 7000000000l;         // Function calong to print answer    System.out.println( nextPrimePalindrome(N) );}} // This code is contributed by Arnab Kundu
# Python3 implementation of above approachimport math # Function to check whether a number is primedef is_prime(n):    return n > 1 and all(n % d for d in range(2, int(math.sqrt(n)) + 1)) # function to generate next smallest prime palindromedef NextprimePalindrome(N):     for k in range(1, 10**6):         # Check for odd-length palindromes        s = str(k)        x = int(s + s[-2::-1])  # eg. s = '1234' to x = int('1234321')         if x >= N and is_prime(x):            return x         # Check for even-length palindromes        s = str(k)        x = int(s + s[-1::-1])  # eg. s = '1234' to x = int('12344321')         if x >= N and is_prime(x):            return x # Driver codeN = 7000000000 # Function call to print answerprint(NextprimePalindrome(N)) # This code is written by# Sanjit_Prasad
// C# implementation of above approachusing System; class GFG{ // Function to check whether// a number is primestatic bool isPrime(long n){    if (n < 2) return false;         for (long i = 2; i <= Math.Sqrt(n); i++)    {        if (n % i == 0) return false;    }    return true;} // reverse the Stringstatic String reverse(String s){    String s1 = "";    for(int i = s.Length - 1; i >= 0; i--)        s1 += s[i];         return s1;} // function to generate next// smalongest prime palindromestatic long nextPrimePalindrome(long N){    for (long k = 1; k < 1000000; k++)    {                 // Check for odd-length palindromes        String s = ""+k;        String z;        z = reverse(s);             // eg. s = '1234' to x = int('1234321')        long x = long.Parse(s + z.Substring(1, z.Length - 1));             if (x >= N && isPrime(x))            return x;             // Check for even-length palindromes        s = ""+(k);        z = s;        z = reverse(z);             // eg. s = '1234' to x = int('12344321')        x = long.Parse(s + z);             if (x >= N && isPrime(x)) return x;    }    return -1;} // Driver Codepublic static void Main(String []args){    long N = 7000000000;         // Function calong to print answer    Console.WriteLine( nextPrimePalindrome(N) );}} // This code is contributed by PrinciRaj1992
<script> // Javascript  implementation of above approach // Function to check whether// a number is primefunction isPrime( n){    if (n < 2) return false;         for (var i = 2; i <= Math.sqrt(n); i++)    {        if (n % i == 0) return false;    }    return true;} // function to generate next// smallest prime palindrome function reverse( s){    var s1 = "";    for(var i = s.length - 1; i >= 0; i--)        s1 += s[i];         return s1;} function nextPrimePalindrome( N){for (var k = 1; k < 1000000; k++){         // Check for odd-length palindromes    var s = ""+k;    var z;    z=reverse(s);     // eg. s = '1234' to x = int('1234321')    var x = Number(s + z.substring(1,z.length));     if (x >= N && isPrime(x)) return x;     // Check for even-length palindromes    s =  ""+k;    z = s;     z=reverse(z);     // eg. s = '1234' to x = int('12344321')    x = Number(s + z);     if (x >= N && isPrime(x)) return x;}} var N = 7000000000;// Function call to find maximum valuedocument.write(nextPrimePalindrome(N) + "<br>"); // This code is contributed by SoumikMondal </script>
10000500001
 
Time Complexity: O(N*sqrt(N)) where N is upper limit and the sqrt(N) term comes from checking if a candidate is prime. 
sanjeev2552
andrew1234
princiraj1992
SoumikMondal
palindrome
Prime Number
Mathematical
Mathematical
Prime Number
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair