Find Largest Special Prime which is less than or equal to a given number in C++


Suppose we have a number n. We have to find the largest special prime which is less than or equal to N. The special prime is a number, which can be created by placing digits one after another, so all the resultant numbers are prime.

Here we will use Sieve Of Eratosthenes. We will create the sieve array up to the number n. Then start iteratively back from the number N, by checking if the number is prime. When this is prime, check whether this is special prime or not.

Example

 Live Demo

#include<iostream>
using namespace std;
bool isSpecialPrime(bool sieve[], int num) {
   while (num) {
      if (!sieve[num]) {
         return false;
      }
      num /= 10;
   }
   return true;
}
void findSpecialPrime(int N) {
   bool sieve[N + 10];
   for(int i = 0; i<N+10; i++){
      sieve[i] = true;
   }
   sieve[0] = sieve[1] = false;
   for (long long i = 2; i <= N; i++) {
      if (sieve[i]) {
         for (long long j = i * i; j <= N; j += i) {
            sieve[j] = false;
         }
      }
   }
   while (true) {
      if (isSpecialPrime(sieve, N)) {
         cout << N << '\n';
         break;
      }
      else
         N--;
   }
}
int main() {
   cout << "Special prime in range (2 -> 400): ";
   findSpecialPrime(400);
   cout << "Special prime in range (2 -> 100): ";
   findSpecialPrime(100);
}

Output

Special prime in range (2 -> 400): 379
Special prime in range (2 -> 100): 79

Updated on: 18-Dec-2019

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements