📜  计算正好有K个除数的数组元素

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

给定一个由N个整数和整数K组成的数组arr [] ,任务是计算具有正好K个除数的数组元素的数量。

例子:

方法:解决此问题的想法是计算每个数组元素的除数总数,并将它们存储在Map中。然后,遍历数组,对于每个数组元素,检查是否正好有K个除数。打印这些数字的计数。请按照以下步骤解决问题:

  • 查找数组中存在的最大元素。
  • 初始化数组prime []
  • 使用Eratosthenes的Sieve将存在于数组[2,最大元素]中的所有素数存储在数组prime []中。
  • 遍历数组,并使用给定的公式对每个数组元素进行素数分解:

其中a i是素因子,而p i是它们的整数幂。

  • 使用以下公式计算每个数组元素的除数总数:

  • 初始化一个Map,以存储每个数组元素的除数总数。
  • 遍历数组并初始化一个变量,例如count ,以计算除数的总数正好为K的元素数。
  • 打印除数正好为K的元素数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Stores prime numbers
// using Sieve of Eratosthenes
bool prime[100000];
 
// Function to find the maximum element
int maximumElement(int arr[], int N)
{
  // Stores the maximum element
  // of the array
  int max = arr[0];
 
  // Traverse the array
  for (int i = 0; i < N; i++) {
 
    // If current element
    // is maximum so far
    if (max < arr[i]) {
 
      // Update maximum
      max = arr[i];
    }
  }
 
  // Return maximum element
  return max;
}
 
// Function to find the prime numbers
// using sieve of eratosthenes algorithm
void sieveOfEratosthenes(int max)
{
  // Calculate primes using Sieve
  memset(prime, true, max+1);
 
  for (int p = 2; p * p < max; p++)
 
    // If current element is prime
    if (prime[p] == true)
 
      // Make all multiples non-prime
      for (int i = p * 2; i < max; i += p)
        prime[i] = false;
}
 
// Function to count divisors of n
int divCount(int n)
{
 
  // Traversing through
  // all prime numbers
  int total = 1;
  for (int p = 2; p <= n; p++) {
 
    // If it is a prime number
    if (prime[p]) {
 
      // Calculate number of divisors
      // with the formula
      // number of diviors = (p1 + 1) * (p2 + 1)
      // *.....* (pn + 1)
      // n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)
      // ai: prime divisor of n
      // pi: power in factorization
      int count = 0;
 
      if (n % p == 0) {
 
        while (n % p == 0) {
          n = n / p;
          count++;
        }
        total = total * (count + 1);
      }
    }
  }
 
  // Return the total number of divisors
  return total;
}
 
// Function to count array elements
// having exactly K diviors
int countElements(int arr[], int N, int K)
{
 
  // Initialize a map to store
  // count of divisors of array elements
  map map;
 
  // Traverse the array
  for (int i = 0; i < N; i++) {
 
    // If element is not already present in
    // the Map, then insert it into the Map
    if (map.find(arr[i]) == map.end()) {
      // Function call to count the total
      // number of divisors
      map.insert({arr[i], divCount(arr[i])});
    }
  }
 
  // Stores the number of
  // elements with divisor K
  int count = 0;
 
  // Traverse the array
  for (int i = 0; i < N; i++) {
 
    // If current element
    // has exactly K divisors
    if (map.at(arr[i]) == K) {
      count++;
    }
  }
 
  // Return the number of
  // elements having K divisors
  return count;
}
 
// Driver Code
int main()
{
 
  int arr[] = { 3, 6, 2, 9, 4 };
  int N = sizeof(arr) / sizeof(arr[0]);
  int K = 2;
 
  // Find the maximum element
  int max = maximumElement(arr, N);
 
  // Generate all prime numbers
  sieveOfEratosthenes(max);
 
  cout << countElements(arr, N, K);
 
  return 0;
}
 
// This code is contributed by Dharanendra L V


Java
// Java program for the above approach
import java.util.*;
class GFG {
 
    // Stores prime numbers
    // using Sieve of Eratosthenes
    public static boolean prime[];
 
    // Function to find the maximum element
    public static int maximumElement(
        int arr[], int N)
    {
        // Stores the maximum element
        // of the array
        int max = arr[0];
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // If current element
            // is maximum so far
            if (max < arr[i]) {
 
                // Update maximum
                max = arr[i];
            }
        }
 
        // Return maximum element
        return max;
    }
 
    // Function to find the prime numbers
    // using sieve of eratosthenes algorithm
    public static void sieveOfEratosthenes(int max)
    {
        // Initialize primes having
        // size of maximum element + 1
        prime = new boolean[max + 1];
 
        // Calculate primes using Sieve
        Arrays.fill(prime, true);
 
        for (int p = 2; p * p < max; p++)
 
            // If current element is prime
            if (prime[p] == true)
 
                // Make all multiples non-prime
                for (int i = p * 2; i < max; i += p)
                    prime[i] = false;
    }
 
    // Function to count divisors of n
    public static int divCount(int n)
    {
 
        // Traversing through
        // all prime numbers
        int total = 1;
        for (int p = 2; p <= n; p++) {
 
            // If it is a prime number
            if (prime[p]) {
 
                // Calculate number of divisors
                // with the formula
                // number of diviors = (p1 + 1) * (p2 + 1)
                // *.....* (pn + 1)
                // n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)
                // ai: prime divisor of n
                // pi: power in factorization
                int count = 0;
 
                if (n % p == 0) {
 
                    while (n % p == 0) {
                        n = n / p;
                        count++;
                    }
                    total = total * (count + 1);
                }
            }
        }
 
        // Return the total number of divisors
        return total;
    }
 
    // Function to count array elements
    // having exactly K diviors
    public static int countElements(
        int arr[], int N, int K)
    {
 
        // Initialize a map to store
        // count of divisors of array elements
        Map map
            = new HashMap();
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // If element is not already present in
            // the Map, then insert it into the Map
            if (!map.containsKey(arr[i])) {
                // Function call to count the total
                // number of divisors
                map.put(arr[i], divCount(arr[i]));
            }
        }
 
        // Stores the number of
        // elements with divisor K
        int count = 0;
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // If current element
            // has exactly K divisors
            if (map.get(arr[i]) == K) {
                count++;
            }
        }
 
        // Return the number of
        // elements having K divisors
        return count;
    }
 
    // Driver Code
    public static void main(
        String[] args)
    {
        int arr[] = { 3, 6, 2, 9, 4 };
        int N = arr.length;
        int K= 2;
 
        // Find the maximum element
        int max = maximumElement(arr, N);
 
        // Generate all prime numbers
        sieveOfEratosthenes(max);
 
        System.out.println(countElements(arr, N, K));
    }
}


Python3
# Python3 program for the above approach
 
# Stores prime numbers
# using Sieve of Eratosthenes
 
# Function to find the maximum element
def maximumElement(arr, N):
   
    # Stores the maximum element
    # of the array
    max = arr[0]
 
    # Traverse the array
    for i in range(N):
 
        # If current element
        # is maximum so far
        if (max < arr[i]):
 
            # Update maximum
            max = arr[i]
 
    # Return maximum element
    return max
 
# Function to find the prime numbers
# using sieve of eratosthenes algorithm
def sieveOfEratosthenes(max):
    global prime
    for p in range(2, max + 1):
        if p * p > max:
            break
 
        # If current element is prime
        if (prime[p] == True):
 
            # Make all multiples non-prime
            for i in range(2 * p, max, p):
                prime[i] = False
    return prime
 
# Function to count divisors of n
def divCount(n):
 
    # Traversing through
    # all prime numbers
    total = 1
    for p in range(2, n + 1):
 
        # If it is a prime number
        if (prime[p]):
 
            # Calculate number of divisors
            # with the formula
            # number of diviors = (p1 + 1) * (p2 + 1)
            # *.....* (pn + 1)
            # n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)
            # ai: prime divisor of n
            # pi: power in factorization
            count = 0
 
            if (n % p == 0):
                while (n % p == 0):
                    n = n // p
                    count += 1
                total = total * (count + 1)
 
    # Return the total number of divisors
    return total
 
# Function to count array elements
# having exactly K diviors
def countElements(arr, N, K):
 
    # Initialize a map to store
    # count of divisors of array elements
    mp = {}
 
    # Traverse the array
    for i in range(N):
 
        # If element is not already present in
        # the Map, then insert it into the Map
        if (arr[i] not in mp):
             
            # Function call to count the total
            # number of divisors
            mp[arr[i]] = divCount(arr[i])
 
    # Stores the number of
    # elements with divisor K
    count = 0
 
    # Traverse the array
    for i in range(N):
 
        # If current element
        # has exactly K divisors
        if (mp[arr[i]] == K):
            count += 1
 
    # Return the number of
    # elements having K divisors
    return count
 
# Driver Code
if __name__ == '__main__':
    prime = [True for i in range(10**6)]
    arr = [3, 6, 2, 9, 4]
    N = len(arr)
    K= 2
 
    # Find the maximum element
    max = maximumElement(arr, N)
 
    # Generate all prime numbers
    prime = sieveOfEratosthenes(max)
    print(countElements(arr, N, K))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
    // Stores prime numbers
    // using Sieve of Eratosthenes
    public static bool []prime;
 
    // Function to find the maximum element
    public static int maximumElement(
        int []arr, int N)
    {
       
        // Stores the maximum element
        // of the array
        int max = arr[0];
 
        // Traverse the array
        for (int i = 0; i < N; i++)
        {
 
            // If current element
            // is maximum so far
            if (max < arr[i])
            {
 
                // Update maximum
                max = arr[i];
            }
        }
 
        // Return maximum element
        return max;
    }
 
    // Function to find the prime numbers
    // using sieve of eratosthenes algorithm
    public static void sieveOfEratosthenes(int max)
    {
       
        // Initialize primes having
        // size of maximum element + 1
        prime = new bool[max + 1];
 
        // Calculate primes using Sieve
        for (int i = 0; i < prime.Length; i++)
        prime[i] = true;
        for (int p = 2; p * p < max; p++)
 
            // If current element is prime
            if (prime[p] == true)
 
                // Make all multiples non-prime
                for (int i = p * 2; i < max; i += p)
                    prime[i] = false;
    }
 
    // Function to count divisors of n
    public static int divCount(int n)
    {
 
        // Traversing through
        // all prime numbers
        int total = 1;
        for (int p = 2; p <= n; p++)
        {
 
            // If it is a prime number
            if (prime[p])
            {
 
                // Calculate number of divisors
                // with the formula
                // number of diviors = (p1 + 1) * (p2 + 1)
                // *.....* (pn + 1)
                // n = (a1 ^ p1) * (a2 ^ p2) .... *(an ^ pn)
                // ai: prime divisor of n
                // pi: power in factorization
                int count = 0;
                if (n % p == 0)
                {
                    while (n % p == 0)
                    {
                        n = n / p;
                        count++;
                    }
                    total = total * (count + 1);
                }
            }
        }
 
        // Return the total number of divisors
        return total;
    }
 
    // Function to count array elements
    // having exactly K diviors
    public static int countElements(int []arr,
                                    int N, int K)
    {
 
        // Initialize a map to store
        // count of divisors of array elements
        Dictionary map
            = new Dictionary();
 
        // Traverse the array
        for (int i = 0; i < N; i++)
        {
 
            // If element is not already present in
            // the Map, then insert it into the Map
            if (!map.ContainsKey(arr[i]))
            {
               
                // Function call to count the total
                // number of divisors
                map.Add(arr[i], divCount(arr[i]));
            }
        }
 
        // Stores the number of
        // elements with divisor K
        int count = 0;
 
        // Traverse the array
        for (int i = 0; i < N; i++)
        {
 
            // If current element
            // has exactly K divisors
            if (map[arr[i]] == K)
            {
                count++;
            }
        }
 
        // Return the number of
        // elements having K divisors
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int []arr = {3, 6, 2, 9, 4};
        int N = arr.Length;
        int K= 2;
 
        // Find the maximum element
        int max = maximumElement(arr, N);
 
        // Generate all prime numbers
        sieveOfEratosthenes(max);
        Console.WriteLine(countElements(arr, N, K));
    }
}
 
// This code is contributed by 29AjayKumar


输出:
2

时间复杂度: O(N + maxlog(log(max)+ log(max)),其中max是最大数组元素。
辅助空间: O(max),其中max是最大数组元素。