📜  在数组中找到素数K,使得(A [i]%K)最大

📅  最后修改于: 2021-05-06 07:24:23             🧑  作者: Mango

给定一个n个整数的数组arr [] 。任务是从数组K中找到一个元素,使得

  1. K素数
  2. 并且,在所有可能的K值中,所有有效i的arr [i]%K均为最大值

如果数组中没有素数,则输出-1

例子:

方法:为了最大化arr [i]%K的值K必须是数组中的最大素数,而arr [i]必须是数组中小于K的最大元素。因此,该问题现在简化为从数组中找到最大素数。为了做到这一点,

  1. 首先使用Sieve从数组中找到所有小于或等于最大元素的质数。
  2. 然后,从数组中找到最大素数并打印。如果数组中没有素数,则打印-1。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the required
// prime number from the array
int getPrime(int arr[], int n)
{
    // Find maximum value in the array
    int max_val = *max_element(arr, arr + n);
  
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    vector prime(max_val + 1, true);
  
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (int p = 2; p * p <= max_val; p++) {
  
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
  
            // Update all multiples of p
            for (int i = p * 2; i <= max_val; i += p)
                prime[i] = false;
        }
    }
  
    // To store the maximum prime number
    int maximum = -1;
    for (int i = 0; i < n; i++) {
  
        // If current element is prime
        // then update the maximum prime
        if (prime[arr[i]])
            maximum = max(maximum, arr[i]);
    }
  
    // Return the maximum prime
    // number from the array
    return maximum;
}
  
// Driver code
int main()
{
    int arr[] = { 2, 10, 15, 7, 6, 8, 13 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << getPrime(arr, n);
  
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
  
class GFG
{
  
// Function to return the required
// prime number from the array
static int getPrime(int arr[], int n)
{
    // Find maximum value in the array
    int max_val = Arrays.stream(arr).max().getAsInt();
  
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    Vector prime = new Vector<>(max_val + 1);
    for(int i = 0; i < max_val + 1; i++)
        prime.add(i,Boolean.TRUE);
  
    // Remaining part of SIEVE
    prime.add(1,Boolean.FALSE);
    prime.add(2,Boolean.FALSE);
    for (int p = 2; p * p <= max_val; p++) 
    {
  
        // If prime[p] is not changed, then
        // it is a prime
        if (prime.get(p) == true) 
        {
  
            // Update all multiples of p
            for (int i = p * 2; i <= max_val; i += p)
                prime.add(i,Boolean.FALSE);
        }
    }
  
    // To store the maximum prime number
    int maximum = -1;
    for (int i = 0; i < n; i++) 
    {
  
        // If current element is prime
        // then update the maximum prime
        if (prime.get(arr[i]))
        {
            maximum = Math.max(maximum, arr[i]);
        }
              
    }
  
    // Return the maximum prime
    // number from the array
    return maximum;
}
  
// Driver code
public static void main(String[] args) 
{
    int arr[] = { 2, 10, 15, 7, 6, 8, 13 };
    int n = arr.length;
  
    System.out.println(getPrime(arr, n));
}
}
  
// This code has been contributed by 29AjayKumar


Python3
# Python 3 implementation of the approach
from math import sqrt
  
# Function to return the required
# prime number from the array
def getPrime(arr, n):
      
    # Find maximum value in the array
    max_val = arr[0]
    for i in range(len(arr)):
          
        # USE SIEVE TO FIND ALL PRIME NUMBERS LESS
        # THAN OR EQUAL TO max_val
        # Create a boolean array "prime[0..n]". A
        # value in prime[i] will finally be false
        # if i is Not a prime, else true.
        if(arr[i] > max_val):
            max_val = arr[i]
  
    prime = [True for i in range(max_val + 1)]
   
    # Remaining part of SIEVE
    prime[0] = False
    prime[1] = False
    for p in range(2, int(sqrt(max_val)) + 1, 1):
          
        # If prime[p] is not changed, then
        # it is a prime
        if (prime[p] == True):
              
            # Update all multiples of p
            for i in range(p * 2, max_val + 1, p):
                prime[i] = False
  
    # To store the maximum prime number
    maximum = -1
    for i in range(n):
          
        # If current element is prime
        # then update the maximum prime
        if (prime[arr[i]]):
            maximum = max(maximum, arr[i])
  
    # Return the maximum prime
    # number from the array
    return maximum
  
# Driver code
if __name__ == '__main__':
    arr = [2, 10, 15, 7, 6, 8, 13]
    n = len(arr)
  
    print(getPrime(arr, n))
      
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation of the approach
using System; 
using System.Linq;
using System.Collections.Generic; 
      
class GFG
{
  
// Function to return the required
// prime number from the array
static int getPrime(int []arr, int n)
{
    // Find maximum value in the array
    int max_val = arr.Max();
  
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    List prime = new List(max_val + 1);
    for(int i = 0; i < max_val + 1; i++)
        prime.Insert(i, true);
  
    // Remaining part of SIEVE
    prime.Insert(1, false);
    prime.Insert(2, false);
    for (int p = 2; p * p <= max_val; p++) 
    {
  
        // If prime[p] is not changed, 
        // then it is a prime
        if (prime[p] == true) 
        {
  
            // Update all multiples of p
            for (int i = p * 2; 
                     i <= max_val; i += p)
                prime.Insert(i, false);
        }
    }
  
    // To store the maximum prime number
    int maximum = -1;
    for (int i = 0; i < n; i++) 
    {
  
        // If current element is prime
        // then update the maximum prime
        if (prime[arr[i]])
        {
            maximum = Math.Max(maximum, arr[i]);
        }
              
    }
  
    // Return the maximum prime
    // number from the array
    return maximum;
}
  
// Driver code
public static void Main(String[] args) 
{
    int []arr = { 2, 10, 15, 7, 6, 8, 13 };
    int n = arr.Length;
  
    Console.WriteLine(getPrime(arr, n));
}
}
  
// This code contributed by Rajput-Ji


PHP


输出:
13