Queries for the smallest and the largest prime number of given digit | C ++ implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to return the smallest prime number with d digits ; check if prime ; Function to return the largest prime number with d digits ; check if prime ; Driver code ; Perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  100000 NEW_LINE bool prime [ MAX + 1 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= MAX ; i += p ) prime [ i ] = false ; } } } int smallestPrime ( int d ) { int l = pow ( 10 , d - 1 ) ; int r = pow ( 10 , d ) - 1 ; for ( int i = l ; i <= r ; i ++ ) { if ( prime [ i ] ) { return i ; } } return -1 ; } int largestPrime ( int d ) { int l = pow ( 10 , d - 1 ) ; int r = pow ( 10 , d ) - 1 ; for ( int i = r ; i >= l ; i -- ) { if ( prime [ i ] ) { return i ; } } return -1 ; } int main ( ) { SieveOfEratosthenes ( ) ; int queries [ ] = { 2 , 5 } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) { cout << smallestPrime ( queries [ i ] ) << " ▁ " << largestPrime ( queries [ i ] ) << endl ; } return 0 ; }