Given a positive integer N where . The task is to find the smallest prime palindrome greater than or equal to N.
Input: 8 Output: 11 Input: 7000000000 Output: 10000500001
The Naive approach is to loop from N + 1 until we found next smallest prime palindrome greater than or equal to N.
Lets 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 when we fount our result.
Below is the implementation of above approach:
Time Complexity: O(N*sqrt(N)) where N is upper limit and the sqrt(N) term comes from checking if a candidate is prime.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Given a number, find the next smallest palindrome
- Find next palindrome prime
- Quick ways to check for Prime and find next Prime in Java
- Next word that does not contain a palindrome and has characters from first k
- Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
- Count all palindrome which is square of a palindrome
- Program to find the next prime number
- Construct lexicographically smallest palindrome
- Make a lexicographically smallest palindrome with minimal changes
- Smallest and Largest Palindrome with N Digits
- Make lexicographically smallest palindrome by substituting missing characters
- Check if the first and last digit of the smallest number forms a prime
- Smallest prime divisor of a number
- Sum and product of k smallest and k largest prime numbers in the array
- Smallest prime number missing in an array
- Smallest Special Prime which is greater than or equal to a given number
- Queries for the smallest and the largest prime number of given digit
- Smallest N digit number divisible by all possible prime digits
- Smallest composite number not divisible by first N prime numbers
- Find coordinates of a prime number in a Prime Spiral