📜  数组中每个第K个素数的总和

📅  最后修改于: 2021-06-26 09:36:30             🧑  作者: Mango

给定一个整数k和一个整数arr (小于10 ^ 6)的数组,任务是找到数组中第k个素数的和。

例子:

简单方法:遍历数组,找到数组中的每个第K个质数,然后计算运行总和。这样,我们将必须检查数组的每个元素是否为质数,随着数组大小的增加,这将花费更多时间。

高效方法:创建一个筛子,该筛子将存储数字是否为质数。然后,它可以用于检查O(1)时间中是否有素数。这样,我们只需要跟踪每个第K个素数并保持运行总和即可。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
#define MAX 1000000
bool prime[MAX + 1];
void SieveOfEratosthenes()
{
    // Create a boolean array "prime[0..n]"
    // and initialize all the entries as true.
    // A value in prime[i] will finally be false
    // if i is Not a prime, else true.
    memset(prime, true, sizeof(prime));
  
    // 0 and 1 are not prime numbers
    prime[1] = false;
    prime[0] = false;
  
    for (int p = 2; p * p <= MAX; 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; i += p)
                prime[i] = false;
        }
    }
}
  
// compute the answer
void SumOfKthPrimes(int arr[], int n, int k)
{
    // count of primes
    int c = 0;
  
    // sum of the primes
    long long int sum = 0;
  
    // traverse the array
    for (int i = 0; i < n; i++) {
  
        // if the number is a prime
        if (prime[arr[i]]) {
  
            // increase the count
            c++;
  
            // if it is the K'th prime
            if (c % k == 0) {
                sum += arr[i];
                c = 0;
            }
        }
    }
    cout << sum << endl;
}
  
// Driver code
int main()
{
    // create the sieve
    SieveOfEratosthenes();
  
    int arr[] = { 2, 3, 5, 7, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
  
    SumOfKthPrimes(arr, n, k);
  
    return 0;
}


Java
// Java implementation of the approach 
  
public class GFG {
  
    static int MAX = 1000000;
    static boolean prime[] = new boolean[MAX + 1];
  
    static void SieveOfEratosthenes() {
        // Create a boolean array "prime[0..n]" 
        // and initialize all the entries as true. 
        // A value in prime[i] will finally be false 
        // if i is Not a prime, else true. 
        for (int i = 0; i < prime.length; i++) {
            prime[i] = true;
        }
  
        // 0 and 1 are not prime numbers 
        prime[1] = false;
        prime[0] = false;
  
        for (int p = 2; p * p <= MAX; 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; i += p) {
                    prime[i] = false;
                }
            }
        }
    }
  
// compute the answer 
    static void SumOfKthPrimes(int arr[], int n, int k) {
        // count of primes 
        int c = 0;
  
        // sum of the primes 
        long sum = 0;
  
        // traverse the array 
        for (int i = 0; i < n; i++) {
  
            // if the number is a prime 
            if (prime[arr[i]]) {
  
                // increase the count 
                c++;
  
                // if it is the K'th prime 
                if (c % k == 0) {
                    sum += arr[i];
                    c = 0;
                }
            }
        }
        System.out.println(sum);
    }
  
// Driver code 
    public static void main(String[] args) {
        // create the sieve 
        SieveOfEratosthenes();
        int arr[] = {2, 3, 5, 7, 11};
        int n = arr.length;
        int k = 2;
        SumOfKthPrimes(arr, n, k);
    }
}


Python3
# Python3 implementation of the approach
MAX = 100000;
prime = [True] * (MAX + 1);
  
def SieveOfEratosthenes():
  
    # Create a boolean array "prime[0..n]"
    # and initialize all the entries 
    # as true. A value in prime[i] will 
    # finally be false if i is Not a prime,
    # else true.
      
    # 0 and 1 are not prime numbers
    prime[1] = False;
    prime[0] = False;
  
    p = 2;
    while(p * p <= MAX):
  
        # If prime[p] is not changed,
        # then it is a prime
        if (prime[p]): 
  
            # Update all multiples of p
            i = p * 2;
            while(i <= MAX):
                prime[i] = False;
                i += p;
        p += 1;
  
# compute the answer
def SumOfKthPrimes(arr, n, k):
      
    # count of primes
    c = 0;
  
    # sum of the primes
    sum = 0;
  
    # traverse the array
    for i in range(n):
  
        # if the number is a prime
        if (prime[arr[i]]):
              
            # increase the count
            c+=1;
  
            # if it is the K'th prime
            if (c % k == 0): 
                sum += arr[i];
                c = 0;
      
    print(sum);
  
# Driver code
  
# create the sieve
SieveOfEratosthenes();
  
arr = [ 2, 3, 5, 7, 11 ];
n = len(arr);
k = 2;
  
SumOfKthPrimes(arr, n, k);
  
# This code is contributed by mits


C#
// C# implementation of the approach
class GFG
{
static int MAX = 1000000;
static bool[] prime = new bool[MAX + 1];
static void SieveOfEratosthenes()
{
    // Create a boolean array "prime[0..n]"
    // and initialize all the entries as true.
    // A value in prime[i] will finally be 
    // false if i is Not a prime, else true.
  
    // 0 and 1 are not prime numbers
    prime[1] = false;
    prime[0] = false;
  
    for (int p = 2; p * p <= MAX; p++) 
    {
  
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == false)
        {
  
            // Update all multiples of p
            for (int i = p * 2; 
                     i <= MAX; i += p)
                prime[i] = true;
        }
    }
}
  
// compute the answer
static void SumOfKthPrimes(int[] arr,
                           int n, int k)
{
    // count of primes
    int c = 0;
  
    // sum of the primes
    long sum = 0;
  
    // traverse the array
    for (int i = 0; i < n; i++)
    {
  
        // if the number is a prime
        if (!prime[arr[i]]) 
        {
  
            // increase the count
            c++;
  
            // if it is the K'th prime
            if (c % k == 0) 
            {
                sum += arr[i];
                c = 0;
            }
        }
    }
    System.Console.WriteLine(sum);
}
  
// Driver code
static void Main()
{
    // create the sieve
    SieveOfEratosthenes();
  
    int[] arr = new int[] { 2, 3, 5, 7, 11 };
    int n = arr.Length;
    int k = 2;
  
    SumOfKthPrimes(arr, n, k);
}
}
  
// This code is contributed by mits


PHP


输出:
10