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

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 << '';
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 09:36:11