Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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


Python3




# Python code for the above approach
M = 1000000
 
# Boolean array to store if
# a number is prime or not
isPrime = [True]*M
 
def SieveOfEratosthenes():
    i = 2
    while(1):
        if((i*i) > M):
            break
             
        # 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.
            j = i*i
            while(j < M):
                isPrime[j] = False
                j += i
        i += 1
 
 
# Function to print primes just less than
# and just greater than of each element in
# an array
def printPrimes(A, N):
   
    # Precalculating
    SieveOfEratosthenes()
 
    # 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="\n")
                break
            j += 1
 
 
A = [17, 28]
N = len(A)
 
# Function call
printPrimes(A, N)
 
# This code is contributed by lokeshmvs21.


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;
}


Java




import java.util.*;
 
class GFG
{
   
// Utility function to do modular exponentiation.
// It returns (x^y) % p
static int power(int x,  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 %2==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
static boolean miillerTest(int d, int n)
{
   
    // Pick a random number in [2..n-2]
    // Corner cases make sure that n > 4
    int a = 2 + (int)(Math.random()*100000) % (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.
static boolean 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
static 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)) {
                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 gauravrajput1


Python3




import random, math
 
# Utility function to do modular exponentiation.
# It returns (x^y) % p
def power(x, y, p):
    res = 1  # Initialize result
    x = x % # Update x if it is more than or
    # equal to p
    y = int(y)
    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^r = n-1 for some r >= 1
def miiller_test(d, n):
   
    # Pick a random number in [2..n-2]
    # Corner cases make sure that n > 4
    a = 2 + math.floor(random.randint(0, 1000) % (n - 4))
 
    # Compute a^d % n
    x = power(a, d, n)
 
    if x == 1 or 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.
def is_prime(n):
    # number of iterations
    k = 4
    # Corner cases
    if n <= 1 or n == 4:
        return False
    if n <= 3:
        return True
 
    # Find r such that
    # n = 2^d * r + 1 for some r >= 1
    d = n - 1
    while d % 2 == 0:
        d /= 2
 
    # Iterate given number of 'k' times
    for i in range(k):
        if miiller_test(d, n) == False:
            return False
    return True
 
# Function to print primes
# just less than and just greater
# than of each element in an array
def print_primes(A, N):
    # Precalculating
    # Traverse the array
    for i in range(N):
        # Traverse for finding
        # prime just less than A[i]
        ans = []
        j = A[i] - 1
        while True:
            if is_prime(j) != 0:
                ans.append(j)
                break
            j -= 1
             
        # Traverse for finding
        # prime just greater than A[i]
        j = A[i] + 1
        while True:
            if is_prime(j) != 0:
                ans.append(j)
                break
            j += 1
         
        print(ans)
 
 
# Driver code
 
# Input
A = [17, 28]
N = len(A)
 
# Function call
print_primes(A, N)
 
# This code is contributed by phasing17.


C#




// C# program for the above approach
using System;
 
class GFG
{
 
// Utility function to do modular exponentiation.
// It returns (x^y) % p
static int power(int x, 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 %2==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
static bool miillerTest(int d, int n)
{
 
    // Pick a random number in [2..n-2]
    // Corner cases make sure that n > 4
    Random rnd = new Random();
    int a = 2 + (int)(rnd.NextDouble()*100000) % (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.
static 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
static 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)) {
                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 Pushpesh Raj.


Javascript




// Utility function to do modular exponentiation.
// It returns (x^y) % p
function power(x,  y,  p)
{
    let 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
function miillerTest( d,  n)
{
    // Pick a random number in [2..n-2]
    // Corner cases make sure that n > 4
    let a = 2 + Math.floor(Math.random() * 10000 + 1)% (n - 4);
 
    // Compute a^d % n
    let 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.
function isPrime(n)
{
    // number of iterations
    let 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
    let d = n - 1;
    while (d % 2 == 0)
        d /= 2;
 
    // Iterate given number of 'k' times
    for (let i = 0; i < k; i++)
        if (miillerTest(d, n) == false)
            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)
{
    // Precalculating
    // Traverse the array
    for (let i = 0; i < N; i++)
    {
     
        // Traverse for finding
        // prime just less than A[i]
        let ans=[];
        for (let j = A[i] - 1;; j--)
        {
         
            // Prime just less than A[i] found
            if (isPrime(j) != 0) {
                ans.push(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) != 0)
            {
                ans.push(j);
                break;
            }
        }
       console.log(ans);
    }
}
// Driver code
 
    // Input
    let A = [ 17, 28 ];
    let N =A.length;
 
    // Function call
    printPrimes(A, N);
 
// This code is contributed by garg28harsh.


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)

 



Last Updated : 01 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads