📌  相关文章
📜  每个数组元素中数组中最接近的质数

📅  最后修改于: 2021-04-21 21:06:41             🧑  作者: Mango

给定一个由N个整数组成的整数数组arr [] ,任务是为数组中的每个元素找到数组中最接近的素数。如果数组不包含任何质数,则打印-1

例子:

方法:
请按照以下步骤解决问题:

  • 在数组中找到最大元素maxm
  • 使用Eratosthenes筛子计算并存储所有质数直到maxm
  • 遍历数组并存储质数的索引。
  • 如果数组中不存在质数,则为所有索引打印-1。
  • curr到由质数组成的第一个索引。
  • 对于直到curr的每个索引,都将arr [primes [curr]]打印为最接近的素数。
  • 对于超过curr的索引,将距离与primes [curr]和primes [curr + 1]进行比较。如果primes [curr]更近,则打印arr [primes [curr]] 。否则,递增curr nad print arr [primes [curr]]
  • 如果curr是数组中的最后一个素数,则从所有索引开始打印arr [primes [curr]]

下面是上述方法的实现:

C++
// C++ program to find nearest
// prime number in the array
// for all array elements
#include 
using namespace std;
  
#define max 10000000
  
// Create a boolean array and set all
// entries it as false. A value in
// prime[i] will be true if i is not a
// prime, else false
bool prime[max] = { false };
  
// Sieve of Eratosthenes function
void SieveOfEratosthenes(int maxm)
{
    prime[0] = prime[1] = true;
    for (int i = 2; i * i <= maxm; 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.
        if (!prime[i]) {
            for (int j = i * i; j <= maxm; j += i) {
                prime[j] = true;
            }
        }
    }
}
// Function to find nearest
// prime number for all elements
void print_nearest_prime(int arr[], int N)
{
    int maxm = *max_element(arr, arr + N);
    // Compute and store all prime
    // numbers up to maxm
    SieveOfEratosthenes(maxm);
  
    vector primes;
    for (int i = 0; i < N; i++) {
        // Store the indices of
        // all primes
        if (!prime[arr[i]])
            primes.push_back(i);
    }
  
    // If no primes are present
    // in the array
    if (primes.size() == 0) {
        for (int i = 0; i < N; i++) {
            cout << -1 << " ";
        }
  
        return;
    }
  
    // Store the current prime
    int curr = 0;
    for (int i = 0; i < N; i++) {
        // If the no further
        // primes exist in the array
        if (curr == primes.size() - 1
            // For all indices less than
            // that of the current prime
            || i <= primes[curr]) {
            cout << arr[primes[curr]] << " ";
            continue;
        }
  
        // If the current prime is
        // nearer
        if (abs(primes[curr] - i)
            < abs(primes[curr + 1] - i)) {
            cout << arr[primes[curr]] << " ";
        }
        // If the next prime is nearer
        else {
            // Make the next prime
            // as the current
            curr++;
            cout << arr[primes[curr]] << " ";
        }
    }
}
// Driver Program
int main()
{
    int N = 6;
    int arr[] = { 8, 7, 12, 15, 3, 11 };
    print_nearest_prime(arr, N);
    return 0;
}


Java
// Java program to find nearest
// prime number in the array
// for all array elements
import java.util.*;
  
class GFG{
  
static final int max = 10000000;
  
// Create a boolean array and set all
// entries it as false. A value in
// prime[i] will be true if i is not a
// prime, else false
static boolean []prime = new boolean[max];
  
// Sieve of Eratosthenes function
static void SieveOfEratosthenes(int maxm)
{
    prime[0] = prime[1] = true;
      
    for(int i = 2; i * i <= maxm; 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.
       if (!prime[i])
       {
           for(int j = i * i; 
                   j <= maxm; j += i)
           {
              prime[j] = true;
           }
       }
    }
}
  
// Function to find nearest
// prime number for all elements
static void print_nearest_prime(int arr[], int N)
{
    int maxm = Arrays.stream(arr).max().getAsInt();
      
    // Compute and store all prime
    // numbers up to maxm
    SieveOfEratosthenes(maxm);
  
    Vector primes = new Vector();
      
    for(int i = 0; i < N; i++)
    {
          
       // Store the indices of
       // all primes
       if (!prime[arr[i]])
           primes.add(i);
    }
  
    // If no primes are present
    // in the array
    if (primes.size() == 0)
    {
        for(int i = 0; i < N; i++) 
        {
           System.out.print(-1 + " ");
        }
        return;
    }
  
    // Store the current prime
    int curr = 0;
    for(int i = 0; i < N; i++)
    {
          
       // If the no further
       // primes exist in the array
       if (curr == primes.size() - 1 ||
         
           // For all indices less than
           // that of the current prime
           i <= primes.get(curr)) 
       {
           System.out.print(
               arr[primes.get(curr)] + " ");
           continue;
       }
         
       // If the current prime is
       // nearer
       if (Math.abs(primes.get(curr) - i) <
           Math.abs(primes.get(curr + 1) - i)) 
       {
           System.out.print(
               arr[primes.get(curr)] + " ");
       }
         
       // If the next prime is nearer
       else
       {
             
           // Make the next prime
           // as the current
           curr++;
           System.out.print(
               arr[primes.get(curr)] + " ");
       }
    }
}
  
// Driver code
public static void main(String[] args)
{
    int N = 6;
    int arr[] = { 8, 7, 12, 15, 3, 11 };
      
    print_nearest_prime(arr, N);
}
}
  
// This code is contributed by PrinciRaj1992


Python3
# Python3 program to find nearest
# prime number in the array
# for all array elements
maxi = 10000000
  
# Create a boolean array and set all
# entries it as false. A value in
# prime[i] will be true if i is not a
# prime, else false
prime = [False] * (maxi)
  
# Sieve of Eratosthenes function
def SieveOfEratosthenes(maxm):
      
    prime[0] = prime[1] = True
    for i in range(2, maxm + 1):
        if i * i > maxm:
            break
              
        # 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.
        if (not prime[i]):
            for j in range(i * i, maxm + 1, i):
                prime[j] = True
  
# Function to find nearest
# prime number for all elements
def print_nearest_prime(arr, N):
  
    maxm = max(arr)
      
    # Compute and store all prime
    # numbers up to maxm
    SieveOfEratosthenes(maxm)
  
    primes = []
    for i in range(N):
          
        # Store the indices of
        # all primes
        if (not prime[arr[i]]):
            primes.append(i)
  
    # If no primes are present
    # in the array
    if len(primes) == 0:
        for i in range(N):
            print(-1, end = " ")
        return
          
    # Store the current prime
    curr = 0
    for i in range(N):
          
        # If the no further primes 
        # exist in the array
        if (curr == len(primes) - 1 or 
          
            # For all indices less than
            # that of the current prime
            i <= primes[curr]):
            print(arr[primes[curr]], end = " ")
            continue
  
        # If the current prime is
        # nearer
        if (abs(primes[curr] - i) < 
            abs(primes[curr + 1] - i)):
            print(arr[primes[curr]], end = " ")
              
        # If the next prime is nearer
        else:
              
            # Make the next prime
            # as the current
            curr += 1
            print(arr[primes[curr]], end = " ")
              
# Driver code
if __name__ == '__main__':
      
    N = 6
    arr = [ 8, 7, 12, 15, 3, 11 ]
      
    print_nearest_prime(arr, N)
  
# This code is contributed by mohit kumar 29


C#
// C# program to find nearest
// prime number in the array
// for all array elements
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG{
  
static readonly int max = 10000000;
  
// Create a bool array and set all
// entries it as false. A value in
// prime[i] will be true if i is not a
// prime, else false
static bool []prime = new bool[max];
  
// Sieve of Eratosthenes function
static void SieveOfEratosthenes(int maxm)
{
    prime[0] = prime[1] = true;
      
    for(int i = 2; i * i <= maxm; 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.
        if (!prime[i])
        {
            for(int j = i * i; 
                    j <= maxm; j += i)
            {
                prime[j] = true;
            }
        }
    }
}
  
// Function to find nearest
// prime number for all elements
static void print_nearest_prime(int []arr, 
                                int N)
{
    int maxm = arr.Max();
      
    // Compute and store all prime
    // numbers up to maxm
    SieveOfEratosthenes(maxm);
  
    List primes = new List();
      
    for(int i = 0; i < N; i++)
    {
          
        // Store the indices of
        // all primes
        if (!prime[arr[i]])
            primes.Add(i);
    }
      
    // If no primes are present
    // in the array
    if (primes.Count == 0)
    {
        for(int i = 0; i < N; i++) 
        {
            Console.Write(-1 + " ");
        }
        return;
    }
  
    // Store the current prime
    int curr = 0;
    for(int i = 0; i < N; i++)
    {
          
        // If the no further
        // primes exist in the array
        if (curr == primes.Count - 1 ||
              
            // For all indices less than
            // that of the current prime
            i <= primes[curr]) 
        {
            Console.Write(
                arr[primes[curr]] + " ");
            continue;
        }
              
        // If the current prime is
        // nearer
        if (Math.Abs(primes[curr] - i) <
            Math.Abs(primes[curr + 1] - i)) 
        {
            Console.Write(
                arr[primes[curr]] + " ");
        }
              
        // If the next prime is nearer
        else
        {
              
            // Make the next prime
            // as the current
            curr++;
            Console.Write(
                arr[primes[curr]] + " ");
        }
    }
}
  
// Driver code
public static void Main(String[] args)
{
    int N = 6;
    int []arr = { 8, 7, 12, 15, 3, 11 };
      
    print_nearest_prime(arr, N);
}
}
  
// This code is contributed by PrinciRaj1992


输出:
7 7 7 3 3 11

时间复杂度: O(maxm *(log(log(log(maxm)))+ N)
辅助空间: O(N)