📌  相关文章
📜  数组中可被k整除的所有复合数字的总和与乘积

📅  最后修改于: 2021-04-24 22:34:44             🧑  作者: Mango

给定N个正整数的数组arr []。任务是找到在给定数组中可被给定数k整除的所有复合元素的总和。

例子:

Input: arr[] = {1, 3, 4, 5, 7}, k = 2
Output: 4, 4
There is one composite number i.e. 4.
So, sum = 4 and product = 4

Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, k = 2
Output: 10, 24
There is only two composite numbers i.e. 4 and 6.
So, sum = 10 and product = 24

天真的方法:
一个简单的解决方案是遍历数组,并继续检查每个元素是否为合成元素,并且还可以被k整除,然后同时添加和乘积该合成元素。

高效方法:
使用Eratosthenes筛子生成所有素数,直到数组的最大元素,并将它们存储在哈希中。现在遍历该数组,并找到这些元素的总和与乘积,这些元素可以通过筛子被k整除。

下面是有效方法的实现:

C++
// CPP program to find sum and product of 
// composites which are divisible by k in given array.
#include 
using namespace std;
  
// Function to find count of composite
void compositeSumProduct(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
    // 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] = true;
    prime[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;
        }
    }
  
    // Sum all primes in arr[]
    int sum = 0, product = 1;
    for (int i = 0; i < n; i++)
        if (!prime[arr[i]] && arr[i] % k == 0) {
            sum += arr[i];
            product *= arr[i];
        }
  
    cout << "Sum of composite numbers divisible by k is "
         << sum;
    cout << "\nProduct of composite numbers divisible by k is "
         << product;
}
  
// Driver code
int main()
{
  
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    compositeSumProduct(arr, n, k);
  
    return 0;
}


Java
// Java program to find sum and product of 
// composites which are divisible by k in given array. 
import java.util.Vector;
  
public class GFG {
  
    static int max_val(int[] arr) {
        int i;
  
        // Initialize maximum element 
        int max = arr[0];
  
        // Traverse array elements from second and 
        // compare every element with current max   
        for (i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
  
        return max;
    }
  
// Function to find count of composite 
    static void compositeSumProduct(int arr[], int n, int k) {
        // Find maximum value in the array 
        int max_val = max_val(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. 
        Vector prime = new Vector<>();
        // Remaining part of SIEVE 
        for(int i = 0;i


Python3
# Python 3 program to find sum and product 
# of composites which are divisible by k 
# in given array.
from math import sqrt, ceil
  
# Function to find count of composite
def compositeSumProduct(arr, n, k):
      
    # Find maximum value in the array
    max_val = arr[0];
    for i in range(len(arr)):
        if(max_val < arr[i]):
            max_val = arr[i]
          
    # 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.
    prime = [True for i in range(max_val + 1)]
  
    # Remaining part of SIEVE
    k = int(sqrt(max_val))
    for p in range(2, k + 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, p):
                prime[i] = False
  
    # Sum all primes in arr[]
    sum = 0
    product = 1
    for i in range(0, n, 1):
        if (prime[arr[i]] == False and 
                  arr[i] % k == 0):
            sum += arr[i]
            product *= arr[i]
  
    print("Sum of composite numbers", 
          "divisible by k is", sum)
    print("Product of composite numbers", 
          "divisible by k is", product)
  
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6, 7]
    n = len(arr)
    k = 2
    compositeSumProduct(arr, n, k)
  
# This code is contributed by
# Surendra_Gangwar


C#
// C# program to find sum and product of 
// composites which are divisible by k in given array. 
using System; 
using System.Collections.Generic;
public class GFG { 
  
    static int max_val_func(int []arr) { 
        int i; 
  
        // Initialize maximum element 
        int max = arr[0]; 
  
        // Traverse array elements from second and 
        // compare every element with current max 
        for (i = 1; i < arr.Length; i++) { 
            if (arr[i] > max) { 
                max = arr[i]; 
            } 
        } 
  
        return max; 
    } 
  
// Function to find count of composite 
    static void compositeSumProduct(int []arr, int n, int k) { 
        // Find maximum value in the array 
        int max_val = max_val_func(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. 
        List prime = new List();
        // Remaining part of SIEVE 
        for(int i = 0;i


时间复杂度: O(n)其中n是数组中元素的最大值,而不是大小。

输出:
Sum of composite numbers divisible by k is 10
Product of composite numbers divisible by k is 24