Skip to content
Related Articles

Related Articles

Improve Article

Find Prime number just less than and just greater each element of given Array

  • Difficulty Level : Easy
  • Last Updated : 12 Jul, 2021

Given an integer array A[] of size N, the task is to find the prime numbers just less and just greater than A[i] (for all 0<=i<N).

Examples:

Input: A={17, 28}, N=2
Output:
13 19
23 29
Explanation:
13 is the prime number just less than 17.
19 is the prime number just greater than 17.
23 is the prime number just less than 28.
29 is the prime number just greater than 28.

Input: A={126, 64, 2896, 156}, N=4
Output:
113 127 
61 67 
2887 2897 
151 157
 

 

Naive Approach: 
Observation: The Maximal Primal Gap for numbers less than 109 is 292.



The Naive Approach would be to check for primality by checking if a number has any factor other than 1 and itself. Follow the steps below to solve the problem:

Traverse the array A, and for each current index i, do the following:

  1. Iterate from A[i]-1 in the descending order, and for each current index j, do the following:
    1. Check if j is prime or not by checking if it has any factor other than 1 and itself.
    2. If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i].
  2. Iterate from A[i]+1 in the ascending order, and for each current index j, do the following:
    1. Check if j is prime or not by checking if it has any factor other than 1 and itself.
    2. If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Utility function to check
// for primality of a number X by
// checking whether X haACCs any
// factors other than 1 and itself.
bool isPrime(int X)
{
    for (int i = 2; i * i <= X; i++)
        if (X % i == 0) // Factor found
            return false;
    return true;
}
// Function to print primes
// just less than and just greater
// than of each element in an array
void printPrimes(int A[], int N)
{
    // Traverse the array
    for (int i = 0; i < N; i++) {
        // Traverse for finding prime
        // just less than A[i]
        for (int j = A[i] - 1;; j--) {
            // Prime just less than A[i] found
            if (isPrime(j)) {
                cout << j << " ";
                break;
            }
        }
        // Traverse for finding prime
        // just greater than A[i]
        for (int j = A[i] + 1;; j++) {
            // Prime just greater than A[i] found
            if (isPrime(j)) {
                cout << j << " ";
                break;
            }
        }
        cout << endl;
    }
}
// Driver code
int main()
{
    // Input
    int A[] = { 17, 28 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function call
    printPrimes(A, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Utility function to check
// for primality of a number X by
// checking whether X has any
// factors other than 1 and itself.
static boolean isPrime(int X)
{
    for(int i = 2; i * i <= X; i++)
     
        // Factor found
        if (X % i == 0)
            return false;
             
    return true;
}
 
// Function to print primes
// just less than and just greater
// than of each element in an array
static void printPrimes(int A[], int N)
{
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Traverse for finding prime
        // just less than A[i]
        for(int j = A[i] - 1;; j--)
        {
             
            // Prime just less than A[i] found
            if (isPrime(j))
            {
                System.out.print(j + " ");
                break;
            }
        }
         
        // Traverse for finding prime
        // just greater than A[i]
        for(int j = A[i] + 1;; j++)
        {
             
            // Prime just greater than A[i] found
            if (isPrime(j))
            {
                System.out.print( j + " ");
                break;
            }
        }
        System.out.println();
    }
}
 
// Driver code
public static void main(String[] args)
{
     
    // Input
    int A[] = { 17, 28 };
    int N = A.length;
     
    // Function call
    printPrimes(A, N);
}
}
 
// This code is contributed by sanjoy_62

Python3




# Python3 program for the above approach
from math import sqrt
 
# Utility function to check
# for primality of a number X by
# checking whether X haACCs any
# factors other than 1 and itself.
def isPrime(X):
     
    for i in range(2, int(sqrt(X)) + 1, 1):
        if (X % i == 0):
             
            # Factor found
            return False
             
    return True
 
# Function to print primes
# just less than and just greater
# than of each element in an array
def printPrimes(A, N):
     
    # Traverse the array
    for i in range(N):
         
        # Traverse for finding prime
        # just less than A[i]
        j = A[i] - 1
         
        while(1):
             
            # Prime just less than A[i] found
            if (isPrime(j)):
                print(j, end = " ")
                break
             
            j -= 1
 
        # Traverse for finding prime
        # just greater than A[i]
        j = A[i] + 1
         
        while (1):
             
            # Prime just greater than A[i] found
            if (isPrime(j)):
                print(j, end = " ")
                break
             
            j += 1
             
        print("\n", end = "")
 
# Driver code
if __name__ == '__main__':
     
    # Input
    A = [ 17, 28 ]
    N = len(A)
 
    # Function call
    printPrimes(A, N)
     
# This code is contributed by SURENDRA_GANGWAR

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Utility function to check
// for primality of a number X by
// checking whether X has any
// factors other than 1 and itself.
static bool isPrime(int X)
{
    for(int i = 2; i * i <= X; i++)
     
        // Factor found
        if (X % i == 0)
            return false;
 
    return true;
}
 
// Function to print primes
// just less than and just greater
// than of each element in an array
static void printPrimes(int[] A, int N)
{
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Traverse for finding prime
        // just less than A[i]
        for(int j = A[i] - 1;; j--)
        {
             
            // Prime just less than A[i] found
            if (isPrime(j))
            {
                Console.Write(j + " ");
                break;
            }
        }
 
        // Traverse for finding prime
        // just greater than A[i]
        for(int j = A[i] + 1;; j++)
        {
             
            // Prime just greater than A[i] found
            if (isPrime(j))
            {
                Console.Write(j + " ");
                break;
            }
        }
        Console.WriteLine();
    }
}
 
// Driver code
public static void Main()
{
     
    // Input
    int []A = { 17, 28 };
    int N = A.Length;
 
    // Function call
    printPrimes(A, N);
}
}
 
// This code is contributed by subhammahato348

Javascript




<script>
// Javascript program for the above approach
 
// Utility function to check
// for primality of a number X by
// checking whether X haACCs any
// factors other than 1 and itself.
function isPrime(X) {
    for (let i = 2; i * i <= X; i++)
        if (X % i == 0) // Factor found
            return false;
    return true;
}
 
// Function to print primes
// just less than and just greater
// than of each element in an array
function printPrimes(A, N)
{
 
    // Traverse the array
    for (let i = 0; i < N; i++)
    {
     
        // Traverse for finding prime
        // just less than A[i]
        for (let j = A[i] - 1; ; j--)
        {
         
            // Prime just less than A[i] found
            if (isPrime(j)) {
                document.write(j + " ");
                break;
            }
        }
         
        // Traverse for finding prime
        // just greater than A[i]
        for (let j = A[i] + 1; ; j++)
        {
         
            // Prime just greater than A[i] found
            if (isPrime(j)) {
                document.write(j + " ");
                break;
            }
        }
        document.write("<br>");
    }
}
 
// Driver code
 
// Input
let A = [17, 28];
let N = A.length;
 
// Function call
printPrimes(A, N);
 
// This code is contributed by _saurabh_jaiswal.
</script>
Output
13 19 
23 29 

Time Complexity: O(N*G*√M), where G is the maximal primal gap and M is the largest element in A.
Auxiliary Space: O(1)

Efficient Approach 1: Instead of checking for individual numbers, all primes numbers can be recalculated using the Sieve of Eratosthenes.

Below is the implementation of the above approach: 

C++




#include <bits/stdc++.h>
using namespace std;
const int M = 1e6;
// Boolean array to store
// if a number is prime or not
bool isPrime[M];
void SieveOfEratosthenes()
{
    // assigh value false
    // to the boolean array isprime
    memset(isPrime, true, sizeof(isPrime));
    for (int i = 2; i * i <= M; i++) {
        // If isPrime[i] is not changed,
        // then it is a prime
        if (isPrime[i]) {
            // Update all multiples of i greater than or
            // equal to the square of it numbers which are
            // multiple of i and are less than i^2 are
            // already been marked.
            for (int j = i * i; j < M; j += i)
                isPrime[j] = false;
        }
    }
}
// Function to print primes
// just less than and just greater
// than of each element in an array
void printPrimes(int A[], int N)
{
    // Precalculating
    SieveOfEratosthenes();
    // Traverse the array
    for (int i = 0; i < N; i++) {
        // Traverse for finding
        // prime just less than A[i]
        for (int j = A[i] - 1;; j--) {
            // Prime just less than A[i] found
            if (isPrime[j]) {
                cout << j << " ";
                break;
            }
        }
        // Traverse for finding
        // prime just greater than A[i]
        for (int j = A[i] + 1;; j++) {
            // Prime just greater than A[i] found
            if (isPrime[j]) {
                cout << j << " ";
                break;
            }
        }
        cout << endl;
    }
}
// Driver code
int main()
{
    // Input
    int A[] = { 17, 28 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function call
    printPrimes(A, N);
 
    return 0;
}

Java




import java.util.*;
  
class GFG{
 
static int M = 1000000;
 
// Boolean array to store
// if a number is prime or not
static boolean isPrime[] = new boolean[M];
 
static void SieveOfEratosthenes()
{
     
    // Assigh value false
    // to the boolean array isprime
    Arrays.fill(isPrime, true);
    for(int i = 2; i * i <= M; i++)
    {
         
        // If isPrime[i] is not changed,
        // then it is a prime
        if (isPrime[i])
        {
             
            // Update all multiples of i greater than or
            // equal to the square of it numbers which are
            // multiple of i and are less than i^2 are
            // already been marked.
            for(int j = i * i; j < M; j += i)
                isPrime[j] = false;
        }
    }
}
 
// Function to print primes
// just less than and just greater
// than of each element in an array
static void printPrimes(int A[], int N)
{
     
    // Precalculating
    SieveOfEratosthenes();
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Traverse for finding
        // prime just less than A[i]
        for(int j = A[i] - 1;; j--)
        {
             
            // Prime just less than A[i] found
            if (isPrime[j])
            {
                System.out.print( j + " ");
                break;
            }
        }
         
        // Traverse for finding
        // prime just greater than A[i]
        for(int j = A[i] + 1;; j++)
        {
             
            // Prime just greater than A[i] found
            if (isPrime[j])
            {
                System.out.print(j + " ");
                break;
            }
        }
        System.out.println();
    }
}
 
// Driver code
public static void main(String[] args)
{
     
    // Input
    int A[] = { 17, 28 };
    int N = A.length;
 
    // Function call
    printPrimes(A, N);
}
}
 
// This code is contributed by sanjoy_62

C#




using System;
 
class GFG {
 
    static int M = 1000000;
 
    // Boolean array to store
    // if a number is prime or not
    static bool[] isPrime = new bool[M];
 
    static void SieveOfEratosthenes()
    {
 
        // Assigh value false
        // to the boolean array isprime
        Array.Fill(isPrime, true);
        for (int i = 2; i * i <= M; i++) {
 
            // If isPrime[i] is not changed,
            // then it is a prime
            if (isPrime[i]) {
 
                // Update all multiples of i greater than or
                // equal to the square of it numbers which
                // are multiple of i and are less than i^2
                // are already been marked.
                for (int j = i * i; j < M; j += i)
                    isPrime[j] = false;
            }
        }
    }
 
    // Function to print primes
    // just less than and just greater
    // than of each element in an array
    static void printPrimes(int[] A, int N)
    {
 
        // Precalculating
        SieveOfEratosthenes();
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Traverse for finding
            // prime just less than A[i]
            for (int j = A[i] - 1;; j--) {
 
                // Prime just less than A[i] found
                if (isPrime[j]) {
                    Console.Write(j + " ");
                    break;
                }
            }
 
            // Traverse for finding
            // prime just greater than A[i]
            for (int j = A[i] + 1;; j++) {
 
                // Prime just greater than A[i] found
                if (isPrime[j]) {
                    Console.Write(j + " ");
                    break;
                }
            }
            Console.WriteLine();
        }
    }
 
    // Driver code
    public static void Main()
    {
 
        // Input
        int[] A = { 17, 28 };
        int N = A.Length;
 
        // Function call
        printPrimes(A, N);
    }
}
 
// This code is contributed by subham348.

Javascript




<script>
 
const M = 1000000;
// Boolean array to store
// if a number is prime or not
let isPrime = new Array(M).fill(true);
function SieveOfEratosthenes()
{
    for (let i = 2; i * i <= M; i++) {
        // If isPrime[i] is not changed,
        // then it is a prime
        if (isPrime[i]) {
            // Update all multiples of i greater than or
            // equal to the square of it numbers which are
            // multiple of i and are less than i^2 are
            // already been marked.
            for (let j = i * i; j < M; j += i)
                isPrime[j] = false;
        }
    }
}
// Function to print primes
// just less than and just greater
// than of each element in an array
function printPrimes(A, N)
{
    // Precalculating
    SieveOfEratosthenes();
    // Traverse the array
    for (let i = 0; i < N; i++) {
        // Traverse for finding
        // prime just less than A[i]
        for (let j = A[i] - 1;; j--) {
            // Prime just less than A[i] found
            if (isPrime[j]) {
                document.write(j + " ");
                break;
            }
        }
        // Traverse for finding
        // prime just greater than A[i]
        for (let j = A[i] + 1;; j++) {
            // Prime just greater than A[i] found
            if (isPrime[j]) {
                document.write(j + " ");
                break;
            }
        }
        document.write("<br>");
    }
}
// Driver code
    // Input
    let A = [ 17, 28 ];
    let N = A.length;
 
    // Function call
    printPrimes(A, N);
 
</script>
Output
13 19 
23 29 

Time Complexity: O(N*G+MLog(Log(M))), where G is the maximal primal gap and M is the largest element in A.
Auxiliary Space: O(M)

Efficient Approach 2: The Millar-Rabin primality test can be used.

C++




#include <bits/stdc++.h>
using namespace std;
// Utility function to do modular exponentiation.
// It returns (x^y) % p
int power(int x, unsigned int y, int p)
{
    int res = 1; // Initialize result
    x = x % p; // Update x if it is more than or
    // equal to p
    while (y > 0) {
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// This function is called for all k trials.
// It returns false if n is composite
// and returns true if n is probably prime.
// d is an odd number such that
// d*2<sup>r</sup> = n-1 for some r >= 1
bool miillerTest(int d, int n)
{
    // Pick a random number in [2..n-2]
    // Corner cases make sure that n > 4
    int a = 2 + rand() % (n - 4);
 
    // Compute a^d % n
    int x = power(a, d, n);
 
    if (x == 1 || x == n - 1)
        return true;
 
    // Keep squaring x while one
    // of the following doesn't happen
    // (i)   d does not reach n-1
    // (ii)  (x^2) % n is not 1
    // (iii) (x^2) % n is not n-1
    while (d != n - 1) {
        x = (x * x) % n;
        d *= 2;
 
        if (x == 1)
            return false;
        if (x == n - 1)
            return true;
    }
 
    // Return composite
    return false;
}
 
// It returns false if n is
// composite and returns true if n
// is probably prime.
// k determines accuracy level. Higher
// value of k indicates more accuracy.
bool isPrime(int n)
{
    // number of iterations
    int k = 4;
    // Corner cases
    if (n <= 1 || n == 4)
        return false;
    if (n <= 3)
        return true;
 
    // Find r such that
    // n = 2^d * r + 1 for some r >= 1
    int d = n - 1;
    while (d % 2 == 0)
        d /= 2;
 
    // Iterate given number of 'k' times
    for (int i = 0; i < k; i++)
        if (!miillerTest(d, n))
            return false;
 
    return true;
}
 
// Function to print primes
// just less than and just greater
// than of each element in an array
void printPrimes(int A[], int N)
{
    // Precalculating
    // Traverse the array
    for (int i = 0; i < N; i++) {
        // Traverse for finding
        // prime just less than A[i]
        for (int j = A[i] - 1;; j--) {
            // Prime just less than A[i] found
            if (isPrime(j)) {
                cout << j << " ";
                break;
            }
        }
        // Traverse for finding
        // prime just greater than A[i]
        for (int j = A[i] + 1;; j++) {
            // Prime just greater than A[i] found
            if (isPrime(j)) {
                cout << j << " ";
                break;
            }
        }
        cout << endl;
    }
}
// Driver code
int main()
{
    // Input
    int A[] = { 17, 28 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function call
    printPrimes(A, N);
 
    return 0;
}
Output
13 19 
23 29 

Time Complexity: O(N*G*KLog3M), where G is the maximal primal gap and M is the largest element in A. Here, K=4
Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :