📜  具有素数和的大小为K的子数组

📅  最后修改于: 2021-05-17 19:11:21             🧑  作者: Mango

给定一个大小为N的数组arr []和一个整数K ,任务是打印一个大小为K的子数组,其元素之和是素数。如果存在多个这样的子数组,则打印其中任何一个。

例子:

方法:要解决此问题,我们的想法是使用“滑动窗口”技术找到大小为K的所有子阵列的总和,并检查其是否为素数。请按照以下步骤解决问题。

  1. 使用Eratosthenes筛子生成[1,1000000]范围内的所有质数,以检查数字是否为质数。
  2. 初始化一个变量,例如currSum,以存储大小为K的子数组的元素之和。
  3. 查找数组的前K个元素的总和,并将其存储在currSum中
  4. 依次迭代其余数组元素,并通过添加第i元素并从数组中删除第(i – K)元素来更新currSum 。现在,检查currSum是否为素数。
  5. 如果发现currSum为质数,则打印当前子数组的所有元素。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Generate all prime numbers
// in the range [1, 1000000]
void sieve(bool prime[])
{
    // Set all numbers as
    // prime initially
    for (int i = 0; i < 1000000;
         i++) {
        prime[i] = true;
    }
 
    // Mark 0 and 1 as non-prime
    prime[0] = prime[1] = false;
 
    for (int i = 2; i * i <= 1000000; i++) {
 
        // If current element is prime
        if (prime[i]) {
 
            // Mark all its multiples
            // as non-prime
            for (int j = i * i; j <= 1000000;
                 j += i) {
 
                prime[j] = false;
            }
        }
    }
}
 
// Function to print the subarray
// whose sum of elements is prime
void subPrimeSum(int N, int K,
                 int arr[],
                 bool prime[])
{
    // Store the current subarray
    // of size K
    int currSum = 0;
 
    // Calculate the sum of
    // first K elements
    for (int i = 0; i < K; i++) {
 
        currSum += arr[i];
    }
 
    // Check if currSum is prime
    if (prime[currSum]) {
        for (int i = 0; i < K; i++) {
 
            cout << arr[i] << " ";
        }
        return;
    }
 
    // Store the start and last
    // index of subarray of size K
    int st = 1, en = K;
 
    // Iterate over remaining array
    while (en < N) {
 
        currSum += arr[en] - arr[st - 1];
 
        // Check if currSum
        if (prime[currSum]) {
 
            for (int i = st; i <= en; i++) {
                cout << arr[i] << " ";
            }
            return;
        }
 
        en++;
        st++;
    }
}
// Driver Code
int main()
{
    int arr[] = { 20, 7, 5, 4, 3, 11,
                  99, 87, 23, 45 };
    int K = 4;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    bool prime[1000000];
 
    sieve(prime);
 
    subPrimeSum(N, K, arr, prime);
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Generate all prime numbers
// in the range [1, 1000000]
static void sieve(boolean prime[])
{
  // Set all numbers as
  // prime initially
  for (int i = 0; i < 1000000; i++)
  {
    prime[i] = true;
  }
 
  // Mark 0 and 1 as non-prime
  prime[0] = prime[1] = false;
 
  for (int i = 2; i * i <= 1000000; i++)
  {
    // If current element is prime
    if (prime[i])
    {
      // Mark all its multiples
      // as non-prime
      for (int j = i * i; j < 1000000; j += i)
      {
        prime[j] = false;
      }
    }
  }
}
 
// Function to print the subarray
// whose sum of elements is prime
static void subPrimeSum(int N, int K,
                        int arr[],
                        boolean prime[])
{
  // Store the current subarray
  // of size K
  int currSum = 0;
 
  // Calculate the sum of
  // first K elements
  for (int i = 0; i < K; i++)
  {
    currSum += arr[i];
  }
 
  // Check if currSum is prime
  if (prime[currSum])
  {
    for (int i = 0; i < K; i++)
    {
      System.out.print(arr[i] + " ");
    }
    return;
  }
 
  // Store the start and last
  // index of subarray of size K
  int st = 1, en = K;
 
  // Iterate over remaining array
  while (en < N)
  {
    currSum += arr[en] - arr[st - 1];
 
    // Check if currSum
    if (prime[currSum])
    {
      for (int i = st; i <= en; i++)
      {
        System.out.print(arr[i] + " ");
      }
      return;
    }
    en++;
    st++;
  }
}
   
// Driver Code
public static void main(String[] args)
{
  int arr[] = {20, 7, 5, 4, 3, 11,
               99, 87, 23, 45};
  int K = 4;
  int N = arr.length;
  boolean []prime = new boolean[1000000];
  sieve(prime);
  subPrimeSum(N, K, arr, prime);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program to implement
# the above approach
 
# Generate all prime numbers
# in the range [1, 1000000]
def sieve(prime):
     
    # Set all numbers as
    # prime initially
    for i in range(1000000):
        prime[i] = True
 
    # Mark 0 and 1 as non-prime
    prime[0] = prime[1] = False
 
    for i in range(2, 1000 + 1):
         
        # If current element is prime
        if (prime[i]):
             
            # Mark all its multiples
            # as non-prime
            for j in range(i * i, 1000000, i):
                prime[j] = False
                 
    return prime
 
# Function to prthe subarray
# whose sum of elements is prime
def subPrimeSum(N, K, arr, prime):
     
    # Store the current subarray
    # of size K
    currSum = 0
 
    # Calculate the sum of
    # first K elements
    for i in range(0, K):
        currSum += arr[i]
 
    # Check if currSum is prime
    if (prime[currSum]):
        for i in range(K):
            print(arr[i], end = " ")
 
        return
 
    # Store the start and last
    # index of subarray of size K
    st = 1
    en = K
 
    # Iterate over remaining array
    while (en < N):
        currSum += arr[en] - arr[st - 1]
 
        # Check if currSum
        if (prime[currSum]):
            for i in range(st, en + 1):
                print(arr[i], end = " ")
 
            return
 
        en += 1
        st += 1
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 20, 7, 5, 4, 3,
            11, 99, 87, 23, 45 ]
    K = 4
    N = len(arr)
    prime = [False] * 1000000
    prime = sieve(prime)
     
    subPrimeSum(N, K, arr, prime)
 
# This code is contributed by Amit Katiyar


C#
// C# program to implement
// the above approach
using System;
class GFG{
 
// Generate all prime numbers
// in the range [1, 1000000]
static void sieve(bool []prime)
{
  // Set all numbers as
  // prime initially
  for (int i = 0; i < 1000000; i++)
  {
    prime[i] = true;
  }
 
  // Mark 0 and 1 as non-prime
  prime[0] = prime[1] = false;
 
  for (int i = 2; i * i <= 1000000; i++)
  {
    // If current element is prime
    if (prime[i])
    {
      // Mark all its multiples
      // as non-prime
      for (int j = i * i; j < 1000000; j += i)
      {
        prime[j] = false;
      }
    }
  }
}
 
// Function to print the subarray
// whose sum of elements is prime
static void subPrimeSum(int N, int K,
                        int []arr,
                        bool []prime)
{
  // Store the current subarray
  // of size K
  int currSum = 0;
 
  // Calculate the sum of
  // first K elements
  for (int i = 0; i < K; i++)
  {
    currSum += arr[i];
  }
 
  // Check if currSum is prime
  if (prime[currSum])
  {
    for (int i = 0; i < K; i++)
    {
      Console.Write(arr[i] + " ");
    }
    return;
  }
 
  // Store the start and last
  // index of subarray of size K
  int st = 1, en = K;
 
  // Iterate over remaining array
  while (en < N)
  {
    currSum += arr[en] - arr[st - 1];
 
    // Check if currSum
    if (prime[currSum])
    {
      for (int i = st; i <= en; i++)
      {
        Console.Write(arr[i] + " ");
      }
      return;
    }
    en++;
    st++;
  }
}
   
// Driver Code
public static void Main(String[] args)
{
  int []arr = {20, 7, 5, 4, 3, 11,
               99, 87, 23, 45};
  int K = 4;
  int N = arr.Length;
  bool []prime = new bool[1000000];
  sieve(prime);
  subPrimeSum(N, K, arr, prime);
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:
7 5 4 3

时间复杂度: O(N)
辅助空间: O(1)