📜  数组中 k 个最小素数和 k 个最大素数的和和积

📅  最后修改于: 2021-10-28 02:00:00             🧑  作者: Mango

给定一个整数k和一个整数数组arr ,任务是找到数组中k 个最小素数和k 个最大素数的和和积。
假设数组中至少有k 个素数。
例子:

方法:

  1. 使用埃拉托色尼筛法生成一个布尔向量,其大小为数组中最大元素的大小,可用于检查数字是否为素数。
  2. 还将01设置为非素数,这样它们就不会被算作素数。
  3. 现在遍历数组并将所有质数插入两个堆中,一个最小堆和一个最大堆。
  4. 现在,从最小堆中弹出前k 个元素,并取最小k 个素数的乘积
  5. 最大堆做同样的事情,得到最大k 个素数的乘积
  6. 最后,打印结果。

下面是上述方法的实现:

C++
// C++ program to find the sum
// and product of k smallest and
// k largest prime numbers in an array
#include 
using namespace std;
 
vector SieveOfEratosthenes(int max_val)
{
    // Create a boolean vector "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);
    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;
        }
    }
    return prime;
}
 
// Function that calculates the sum
// and product of k smallest and k
// largest prime numbers in an array
void primeSumAndProduct(int arr[], int n, int k)
{
    // 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
    vector prime = SieveOfEratosthenes(max_val);
 
    // Set 0 and 1 as non-primes as
    // they don't need to be
    // counted as prime numbers
    prime[0] = false;
    prime[1] = false;
 
    // Max Heap to store all the prime numbers
    priority_queue maxHeap;
 
    // Min Heap to store all the prime numbers
    priority_queue, greater>
        minHeap;
 
    // Push all the prime numbers
    // from the array to the heaps
    for (int i = 0; i < n; i++)
        if (prime[arr[i]]) {
            minHeap.push(arr[i]);
            maxHeap.push(arr[i]);
        }
    long long int minProduct = 1
        , maxProduct = 1
        , minSum = 0
        , maxSum = 0;
    while (k--) {
 
        // Calculate the products
        minProduct *= minHeap.top();
        maxProduct *= maxHeap.top();
 
        // Calculate the sum
        minSum += minHeap.top();
        maxSum += maxHeap.top();
 
        // Pop the current minimum element
        minHeap.pop();
 
        // Pop the current maximum element
        maxHeap.pop();
    }
 
    cout << "Sum of k-minimum prime numbers is "
         << minSum << "\n";
    cout << "Sum of k-maximum prime numbers is "
         << maxSum << "\n";
    cout << "Product of k-minimum prime numbers is "
         << minProduct << "\n";
    cout << "Product of k-maximum prime numbers is "
         << maxProduct;
}
 
// Driver code
int main()
{
 
    int arr[] = { 4, 2, 12, 13, 5, 19 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    int k = 3;
 
    primeSumAndProduct(arr, n, k);
 
    return 0;
}


Java
// Java program to find the sum
// and product of k smallest and
// k largest prime numbers in an array
import java.util.*;
 
class GFG
{
    public static void main(String[] args)
    {
        int arr[] = { 4, 2, 12, 13, 5, 19 };
        int n = arr.length;
        int k = 3;
        primeSumAndProduct(arr, n, k);
    }
 
    static boolean[] SieveOfEratosthenes(int max_val)
    {
        // Create a boolean vector "prime[0..n]". A
        // value in prime[i] will finally be false
        // if i is Not a prime, else true.
        boolean[] prime = new boolean[max_val + 1];
        for(int i = 0;i <= max_val ; i++)
        prime[i] = true;
        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;
            }
        }
        return prime;
    }
 
    // Function that calculates the sum
    // and product of k smallest and k
    // largest prime numbers in an array
    static void primeSumAndProduct(int arr[], int n, int k)
    {
        // Find maximum value in the array
        int max_val = 0;
        for (int i = 0; i < n; i++)
            max_val = Math.max(max_val, arr[i]);
 
        // Use sieve to find all prime numbers
        // less than or equal to max_val
        boolean[] prime = SieveOfEratosthenes(max_val);
 
        // Set 0 and 1 as non-primes as
        // they don't need to be
        // counted as prime numbers
        prime[0] = false;
        prime[1] = false;
 
        // Max Heap to store all the prime numbers
        PriorityQueue maxHeap = new PriorityQueue(Collections.reverseOrder());
 
        // Min Heap to store all the prime numbers
        PriorityQueue minHeap = new PriorityQueue();
 
        // Push all the prime numbers
        // from the array to the heaps
        for (int i = 0; i < n; i++)
            if (prime[arr[i]]) {
                minHeap.add(arr[i]);
                maxHeap.add(arr[i]);
            }
 
        long minProduct = 1, maxProduct = 1, minSum = 0, maxSum = 0;
        while (k > 0)
        {
            k--;
             
            // Calculate the products
            minProduct *= minHeap.peek();
            maxProduct *= maxHeap.peek();
 
            // Calculate the sum
            minSum += minHeap.peek();
            maxSum += maxHeap.peek();
 
            // Pop the current minimum element
            minHeap.remove();
 
            // Pop the current maximum element
            maxHeap.remove();
        }
 
        System.out.println("Sum of k-minimum prime numbers is " + minSum);
        System.out.println("Sum of k-maximum prime numbers is " + maxSum);
        System.out.println("Product of k-minimum prime numbers is " + minProduct);
        System.out.println("Product of k-maximum prime numbers is " + maxProduct);
    }
 
}
 
// This code is contributed by ankush_953


Python3
# Python program to find the sum
# and product of k smallest and
# k largest prime numbers in an array
import heapq
 
def SieveOfEratosthenes(max_val):
    # Create a boolean vector "prime[0..n]". A
    # value in prime[i] will finally be false
    # if i is Not a prime, else true.
    prime = [True for i in range(max_val+1)]
    p = 2
    while p*p <= max_val:
        # If prime[p] is not changed, then
        # it is a prime
        if (prime[p] == True):
 
            # Update all multiples of p
            for j in range(2*p,max_val+1,p):
                prime[j] = False
        p += 1
     
    return prime
 
# Function that calculates the sum
# and product of k smallest and k
# largest prime numbers in an array
def primeSumAndProduct(arr, n, k):
    # Find maximum value in the array
    max_val = max(arr)
 
    # Use sieve to find all prime numbers
    # less than or equal to max_val
    prime = SieveOfEratosthenes(max_val)
 
    # Set 0 and 1 as non-primes as
    # they don't need to be
    # counted as prime numbers
    prime[0] = False
    prime[1] = False
 
    # Heap to store all the prime numbers
    Heap = []
 
    # Push all the prime numbers
    # from the array to the heaps
    for i in range(n):
        if (prime[arr[i]]):
            Heap.append(arr[i])
     
    minProduct = 1
    maxProduct = 1
    minSum = 0
    maxSum = 0
 
    min_k = heapq.nsmallest(k,Heap)
    max_k = heapq.nlargest(k,Heap)
 
    minSum = sum(min_k)
    maxSum = sum(max_k)
     
    for val in min_k:
        minProduct *= val
     
    for val in max_k:
        maxProduct *= val
     
    print("Sum of k-minimum prime numbers is", minSum)
    print("Sum of k-maximum prime numbers is", maxSum)
    print("Product of k-minimum prime numbers is", minProduct)
    print("Product of k-maximum prime numbers is", maxProduct)
 
# Driver code
arr = [ 4, 2, 12, 13, 5, 19 ]
n = len(arr)
k = 3
primeSumAndProduct(arr, n, k)
 
# This code is contributed by ankush_953


输出:
Sum of k-minimum prime numbers is 20
Sum of k-maximum prime numbers is 37
Product of k-minimum prime numbers is 130
Product of k-maximum prime numbers is 1235

时间复杂度:O(N*log(N) + max_val * log(log(max_val)))其中 N 是元素的总数,max_val 是数组中的最大值。  
辅助空间:O(N + max_val)