📌  相关文章
📜  找到小于和大于给定数组的每个元素的素数

📅  最后修改于: 2022-05-13 01:56:06.098000             🧑  作者: Mango

找到小于和大于给定数组的每个元素的素数

给定一个大小为N的整数数组A[] ,任务是找到刚好小于和大于A[i]的素数(对于所有0<=i )。

例子:

天真的方法:
观察:小于 10 9的数字的最大原始差距是 292。

朴素的方法是通过检查一个数字是否具有除 1 和它本身之外的任何因子来检查素数。请按照以下步骤解决问题:

遍历数组A ,对于每个当前索引i ,执行以下操作:

  1. A[i]-1以降序迭代,对于每个当前索引j ,执行以下操作:
    1. 通过检查 j 是否具有除 1 和自身之外的任何因子来检查j是否为素数。
    2. 如果j是素数,则打印 j 并终止内部循环。这给出的素数刚好小于A[i]
  2. A[i]+1以升序迭代,对于每个当前索引j ,执行以下操作:
    1. 通过检查 j 是否具有除 1 和自身之外的任何因子来检查j是否为素数。
    2. 如果j是素数,则打印j并终止内部循环。这给出了小于A[i] 的素数,

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
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


C++
#include 
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


C++
#include 
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*2r = 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*2r = 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


输出
13 19 
23 29 

时间复杂度: O(N*G*√M),其中 G 是最大原始间隙,M 是 A 中的最大元素。
辅助空间: O(1)

有效方法 1:可以使用埃拉托色尼筛法重新计算所有素数,而不是检查单个数字。

下面是上述方法的实现:

C++

#include 
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


输出
13 19 
23 29 

时间复杂度: O(N*G+MLog(Log(M))),其中 G 是最大原始间隙,M 是 A 中的最大元素。
辅助空间: O(M)

有效方法 2:可以使用 Millar-Rabin 素性检验。

C++

#include 
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*2r = 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*2r = 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
输出
13 19 
23 29 

时间复杂度: O(N*G*KLog 3 M),其中G是最大原始间隙,M是A中最大的元素。这里,K=4
辅助空间: O(1)