Prime Palindrome in C++


Suppose we have to find the smallest prime palindrome that is greater than or equal to N. So if the N is 13, then the smallest palindrome will be 101.

To solve this, we will follow these steps −

  • If N is in range 8 to 11, then return 11

  • for i in range 1 to 99999

    • s := i as a string

    • r := s

    • reverse r

    • num := concatenate s and substring of r from index 1, then convert to number

    • if num >= N and num is prime, then return num

  • return 0

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool isPrime(int n){
      if(n % 2 == 0 && n > 2) return false;
      for(int i = 3; i * i <= n; i++){
         if(n % i == 0) return false;
      }
      return n != 1 && n != 0;
   }
   int primePalindrome(int N) {
      if(8 <= N && N <= 11) return 11;
      for(int i = 1; i < 100000; i++){
         string s = to_string(i);
         string r = s;
         reverse(r.begin(), r.end());
         int num = stoi(s + r.substr(1));
         if(num >= N && isPrime(num)) return num;
      }
      return 0;
   }
};
main(){
   Solution ob;
   cout << (ob.primePalindrome(105));
}

Input

105

Output

131

Updated on: 30-Apr-2020

715 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements