Suma y producto de los k números primos más pequeños y los k más grandes de la array

Dado un entero k y un arreglo de enteros arr , la tarea es encontrar la suma y el producto de los k números primos más pequeños y los k más grandes en el arreglo. 
Suponga que hay al menos k números primos en la array.
Ejemplos: 
 

Entrada: arr[] = {2, 5, 6, 8, 10, 11}, k = 2 
Salida: La suma de los k números primos mínimos es 7 
La suma de los k números primos máximos es 16 
Producto de los k números primos mínimos es 10 
El producto de k-números primos máximos es 55 
{2, 5, 11} son los únicos números primos de la array. {2, 5} son los 2 más pequeños y {5, 11} son los 2 más grandes entre ellos.
Entrada: arr[] = {4, 2, 12, 13, 5, 19}, k = 3 
Salida: La suma de los k números primos mínimos es 20 
La suma de los k números primos máximos es 37 
Producto de los k números primos mínimos es 130 
Producto de k-números primos máximos es 1235 
 

Acercarse: 
 

  1. El uso de Sieve of Eratosthenes genera un vector booleano hasta el tamaño del elemento máximo de la array que se puede usar para verificar si un número es primo o no.
  2. También establezca 0 y 1 como no primos para que no se cuenten como números primos.
  3. Ahora recorra la array e inserte todos los números que son primos en dos montones , un montón mínimo y un montón máximo.
  4. Ahora, saque los k elementos superiores del montón mínimo y tome la suma y el producto de los k números primos mínimos .
  5. Haga lo mismo con el montón máximo para obtener la suma y el producto de los números primos máximos k .
  6. Finalmente, imprima los resultados.

A continuación se muestra la implementación del enfoque anterior:
 

C++

// C++ program to find the sum
// and product of k smallest and
// k largest prime numbers in an array
#include <bits/stdc++.h>
using namespace std;
 
vector<bool> 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<bool> 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<bool> 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<int> maxHeap;
 
    // Min Heap to store all the prime numbers
    priority_queue<int, vector<int>, greater<int>>
        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<Integer> maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
 
        // Min Heap to store all the prime numbers
        PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
 
        // 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
Producción: 

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

 

Complejidad de tiempo : O(N*log(N) + max_val * log(log(max_val)) ) Donde N es el número total de elementos y max_val es el valor máximo en la array. Espacio Auxiliar : O(N + max_val)  

Publicación traducida automáticamente

Artículo escrito por imdhruvgupta y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *