📌  相关文章
📜  数组中复合元素的计数和总和

📅  最后修改于: 2022-05-13 01:57:05.721000             🧑  作者: Mango

数组中复合元素的计数和总和

给定一个正整数数组“arr”,任务是计算数组中合数的个数。
注意: 1 既不是Prime也不是Composite
例子:

朴素方法:一个简单的解决方案是遍历数组并对每个元素进行素数测试。
有效的方法:使用埃拉托色尼筛法生成一个布尔向量,其大小可达数组中最大元素的大小,可用于检查一个数字是否为素数。还要添加 0 和 1 作为素数,这样它们就不会被算作合数。现在遍历数组并找到使用生成的布尔向量合成的那些元素的计数。
下面是上述方法的实现:

C++
// C++ program to count the
// number of composite numbers
// in the given array
#include 
using namespace std;
 
// Function that returns the
// the count of composite numbers
int compositeCount(int arr[], int n, int* sum)
{
    // 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);
 
    // Set 0 and 1 as primes as
    // they don't need to be
    // counted as composite numbers
    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;
        }
    }
 
    // Count all composite
    // numbers in the arr[]
    int count = 0;
    for (int i = 0; i < n; i++)
        if (!prime[arr[i]]) {
            count++;
            *sum = *sum + arr[i];
        }
 
    return count;
}
 
// Driver code
int main()
{
 
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = 0;
 
    cout << "Count of Composite Numbers = "
          << compositeCount(arr, n, &sum);
 
    cout << "\nSum of Composite Numbers = " << sum;
 
    return 0;
}


Java
import java.util.*;
 
// Java program to count the
// number of composite numbers
// in the given array
 
class GFG
{
 
    static int sum = 0;
     
    // Function that returns the
    // the count of composite numbers
    static int compositeCount(int arr[], int n)
    {
        // Find maximum value in the array
        int max_val = Arrays.stream(arr).max().getAsInt();
 
        // 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(max_val + 1);
        for (int i = 0; i < max_val + 1; i++)
        {
            prime.add(i, Boolean.TRUE);
        }
        // Set 0 and 1 as primes as
        // they don't need to be
        // counted as composite numbers
        prime.add(0, Boolean.TRUE);
        prime.add(1, Boolean.TRUE);
        for (int p = 2; p * p <= max_val; p++)
        {
 
            // If prime[p] is not changed, then
            // it is a prime
            if (prime.get(p) == true)
            {
 
                // Update all multiples of p
                for (int i = p * 2; i <= max_val; i += p)
                {
                    prime.add(i, Boolean.FALSE);
                }
            }
        }
 
        // Count all composite
        // numbers in the arr[]
        int count = 0;
        for (int i = 0; i < n; i++)
        {
            if (!prime.get(arr[i]))
            {
                count++;
                sum = sum + arr[i];
            }
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {1, 2, 3, 4, 5, 6, 7};
        int n = arr.length;
 
        System.out.print("Count of Composite Numbers = "
                + compositeCount(arr, n));
 
        System.out.print("\nSum of Composite Numbers = " + sum);
    }
}
 
// This code has been contributed by 29AjayKumar


Python3
# Python3 program to count the
# number of composite numbers
# in the given array
 
# Function that returns the
# the count of composite numbers
def compositeCount(arr, n):
    Sum = 0
 
    # Find maximum value in the array
    max_val = max(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.
    prime = [True for i in range(max_val + 1)]
 
    # Set 0 and 1 as primes as
    # they don't need to be
    # counted as composite numbers
    prime[0] = True
    prime[1] = True
    for p in range(2, max_val + 1):
 
        if p * p > max_val:
            break
             
        # 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 + 1, p):
                prime[i] = False
         
    # Count all composite numbers
    # in the arr[]
    count = 0
    for i in range(n):
        if (prime[arr[i]] == False):
            count += 1
            Sum = Sum + arr[i]
     
    return count, Sum
 
# Driver code
arr = [1, 2, 3, 4, 5, 6, 7 ]
n = len(arr)
count, Sum = compositeCount(arr, n)
 
print("Count of Composite Numbers = ", count)
 
print("Sum of Composite Numbers = ", Sum)
 
// This code is contributed by Mohit Kumar


C#
// C# program to count the
// number of composite numbers
// in the given array
using System;
using System.Linq;
using System.Collections;
 
class GFG
{
     
static int sum1=0;
 
// Function that returns the
// the count of composite numbers
static int compositeCount(int []arr, int n, int sum)
{
    // Find maximum value in the array
    int max_val = arr.Max();
 
    // 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.
    bool[] prime=new bool[max_val + 1];
 
    // Set 0 and 1 as primes as
    // they don't need to be
    // counted as composite numbers
    prime[0] = false;
    prime[1] = false;
    for (int p = 2; p * p <= max_val; 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_val; i += p)
                prime[i] = true;
        }
    }
 
    // Count all composite
    // numbers in the arr[]
    int count = 0;
    for (int i = 0; i < n; i++)
        if (prime[arr[i]])
        {
            count++;
            sum = sum + arr[i];
        }
    sum1 = sum;
    return count;
}
 
// Driver code
static void Main()
{
 
    int []arr = { 1, 2, 3, 4, 5, 6, 7 };
    int n = arr.Length;
    int sum = 0;
 
    Console.Write("Count of Composite Numbers = "+
                    compositeCount(arr, n, sum));
 
    Console.Write("\nSum of Composite Numbers = "+sum1);
}
}
 
// This code is contributed by mits


PHP


Javascript


输出:
Count of Composite Numbers = 2
Sum of Composite Numbers = 10

时间复杂度: O(n)