Queries for the smallest and the largest prime number of given digit

Given Q queries where every query consists of an integer D, the task is to find the smallest and the largest prime number with D digits. If no such prime number exists then print -1.
Examples:Â
Â
Input: Q[] = {2, 5}Â
Output:Â
11 97Â
10007 99991
Input: Q[] = {4, 3, 1}Â
Output:Â
1009 9973Â
101 997Â
1 7Â
Â
Approach:Â
Â
- D digit numbers start from 10(D – 1) and end at 10D – 1.
- Now, the task is to find the smallest and the largest prime number from this range.
- To answer a number of queries for prime numbers, Sieve of Eratosthenes can be used to answer whether a number is prime or not.
Below is the implementation of the above approach:Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
#define MAX 100000Â
bool prime[MAX + 1];Â
void SieveOfEratosthenes(){Â
    // 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.    memset(prime, true, sizeof(prime));Â
    for (int p = 2; p * p <= MAX; p++) {Â
        // If prime[p] is not changed, then it is a prime        if (prime[p] == true) {Â
            // 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.            for (int i = p * p; i <= MAX; i += p)                prime[i] = false;        }    }}Â
// Function to return the smallest prime// number with d digitsint smallestPrime(int d){Â Â Â Â int l = pow(10, d - 1);Â Â Â Â int r = pow(10, d) - 1;Â Â Â Â for (int i = l; i <= r; i++) {Â
        // check if prime        if (prime[i]) {            return i;        }    }    return -1;}Â
// Function to return the largest prime// number with d digitsint largestPrime(int d){Â Â Â Â int l = pow(10, d - 1);Â Â Â Â int r = pow(10, d) - 1;Â Â Â Â for (int i = r; i >= l; i--) {Â
        // check if prime        if (prime[i]) {            return i;        }    }    return -1;}Â
// Driver codeint main(){Â Â Â Â SieveOfEratosthenes();Â
    int queries[] = { 2, 5 };    int q = sizeof(queries) / sizeof(queries[0]);Â
    // Perform queries    for (int i = 0; i < q; i++) {        cout << smallestPrime(queries[i]) << " "             << largestPrime(queries[i]) << endl;    }Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.*;Â
class GFG {static int MAX = 100000;Â
static boolean []prime = new boolean[MAX + 1];Â
static void SieveOfEratosthenes(){Â
    // 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.    for (int i = 0; i < MAX + 1; i++)    {        prime[i] = true;    }    for (int p = 2; p * p <= MAX; p++)     {Â
        // If prime[p] is not changed,        // then it is a prime        if (prime[p] == true)         {Â
            // 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.            for (int i = p * p; i <= MAX; i += p)                prime[i] = false;        }    }}Â
// Function to return the smallest prime// number with d digitsstatic int smallestPrime(int d){Â Â Â Â int l = (int) Math.pow(10, d - 1);Â Â Â Â int r = (int) Math.pow(10, d) - 1;Â Â Â Â for (int i = l; i <= r; i++)Â Â Â Â {Â
        // check if prime        if (prime[i])        {            return i;        }    }    return -1;}Â
// Function to return the largest prime// number with d digitsstatic int largestPrime(int d){Â Â Â Â int l = (int) Math.pow(10, d - 1);Â Â Â Â int r = (int) Math.pow(10, d) - 1;Â Â Â Â for (int i = r; i >= l; i--) Â Â Â Â {Â
        // check if prime        if (prime[i])        {            return i;        }    }    return -1;}Â
// Driver codepublic static void main(String[] args) {Â Â Â Â SieveOfEratosthenes();Â
    int queries[] = { 2, 5 };    int q = queries.length;Â
    // Perform queries    for (int i = 0; i < q; i++)    {        System.out.println(smallestPrime(queries[i]) + " " +                            largestPrime(queries[i]));    }}} Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 implementation of the approach from math import sqrtÂ
MAX = 100000Â
# 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. prime = [True] * (MAX + 1)Â
def SieveOfEratosthenes() : Â
    for p in range(2, int(sqrt(MAX)) + 1) : Â
        # If prime[p] is not changed,        # then it is a prime         if (prime[p] == True) :Â
            # 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.             for i in range(p * p, MAX + 1, p) :                prime[i] = False; Â
# Function to return the smallest prime # number with d digits def smallestPrime(d) : Â
    l = 10 ** (d - 1);     r = (10 ** d) - 1;     for i in range(l, r + 1) : Â
        # check if prime         if (prime[i]) :            return i; Â
    return -1; Â
# Function to return the largest prime # number with d digits def largestPrime(d) : Â
    l = 10 ** (d - 1);     r = (10 ** d) - 1;     for i in range(r, l , -1) :Â
        # check if prime         if (prime[i]) :            return i;                  return -1; Â
# Driver code if __name__ == "__main__" : Â
    SieveOfEratosthenes(); Â
    queries = [ 2, 5 ];     q = len(queries); Â
    # Perform queries     for i in range(q) :        print(smallestPrime(queries[i]), " ",              largestPrime(queries[i])); Â
# This code is contributed by AnkitRai01 |
C#
// C# implementation of the approachusing System;Â Â Â Â Â class GFG {static int MAX = 100000;Â
static bool []prime = new bool[MAX + 1];Â
static void SieveOfEratosthenes(){Â
    // 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.    for (int i = 0; i < MAX + 1; i++)    {        prime[i] = true;    }    for (int p = 2; p * p <= MAX; p++)     {Â
        // If prime[p] is not changed,        // then it is a prime        if (prime[p] == true)         {Â
            // 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.            for (int i = p * p; i <= MAX; i += p)                prime[i] = false;        }    }}Â
// Function to return the smallest prime// number with d digitsstatic int smallestPrime(int d){Â Â Â Â int l = (int) Math.Pow(10, d - 1);Â Â Â Â int r = (int) Math.Pow(10, d) - 1;Â Â Â Â for (int i = l; i <= r; i++)Â Â Â Â {Â
        // check if prime        if (prime[i])        {            return i;        }    }    return -1;}Â
// Function to return the largest prime// number with d digitsstatic int largestPrime(int d){Â Â Â Â int l = (int) Math.Pow(10, d - 1);Â Â Â Â int r = (int) Math.Pow(10, d) - 1;Â Â Â Â for (int i = r; i >= l; i--) Â Â Â Â {Â
        // check if prime        if (prime[i])        {            return i;        }    }    return -1;}Â
// Driver codepublic static void Main(String[] args) {Â Â Â Â SieveOfEratosthenes();Â
    int []queries = { 2, 5 };    int q = queries.Length;Â
    // Perform queries    for (int i = 0; i < q; i++)    {        Console.WriteLine(smallestPrime(queries[i]) + " " +                            largestPrime(queries[i]));    }}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Javascript implementation of the approachÂ
const MAX = 100000;Â
// 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.let prime = new Array(MAX + 1).fill(true);Â
function SieveOfEratosthenes(){Â
    for (let p = 2; p * p <= MAX; p++)     {Â
        // If prime[p] is not changed,         // then it is a prime        if (prime[p] == true) {Â
            // 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.            for (let i = p * p; i <= MAX; i += p)                prime[i] = false;        }    }}Â
// Function to return the smallest prime// number with d digitsfunction smallestPrime(d){Â Â Â Â let l = Math.pow(10, d - 1);Â Â Â Â let r = Math.pow(10, d) - 1;Â Â Â Â for (let i = l; i <= r; i++) {Â
        // check if prime        if (prime[i]) {            return i;        }    }    return -1;}Â
// Function to return the largest prime// number with d digitsfunction largestPrime(d){Â Â Â Â let l = Math.pow(10, d - 1);Â Â Â Â let r = Math.pow(10, d) - 1;Â Â Â Â for (let i = r; i >= l; i--) {Â
        // check if prime        if (prime[i]) {            return i;        }    }    return -1;}Â
// Driver code    SieveOfEratosthenes();Â
    let queries = [ 2, 5 ];    let q = queries.length;Â
    // Perform queries    for (let i = 0; i < q; i++) {        document.write(smallestPrime(queries[i]) + " "             + largestPrime(queries[i]) + "<br>");    }Â
</script> |
Output:Â
11 97 10007 99991
Â
Time Complexity: O(MAX*log(log(MAX)) + q*(r – l))
Auxiliary Space: O(MAX)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



