📜  数组乘法的除数计数

📅  最后修改于: 2021-04-27 17:28:12             🧑  作者: Mango

给定一个具有N个元素的数组,任务是找到所有数组元素的乘积X的因数。

例子:

Input : 5 5
Output : 3
5 * 5 = 25, the factors of 25 are 1, 5, 25
whose count is 3
 
Input : 3 5 7
Output : 8
3 * 5 * 7 = 105, the factors of 105 are 1,
3, 5, 7, 15, 21, 35, 105 whose count is 8

方法1(简单,但会导致溢出)
1.乘以数组的所有元素。
2.计算除数后的除数。

C++
// A simple C++ program to count divisors
// in array multiplication.
#include 
using namespace std;
 
// To count number of factors in a number
int counDivisors(int X)
{
    // Initialize count with 0
    int count = 0;
    // Increment count for every factor
    // of the given number X.
    for (int i = 1; i <= X; ++i) {
        if (X % i == 0) {
            count++;
        }
    }
 
    // Return number of factors
    return count;
}
 
// Returns number of divisors in array
// multiplication
int countDivisorsMult(int arr[], int n)
{
    // Multipliying all elements of
    // the given array.
    int mul = 1;
    for (int i = 0; i < n; ++i)
        mul *= arr[i];
     
    // Calling function which count number of factors
    // of the number
    return counDivisors(mul);
}
 
// Driver code
int main()
{
    int arr[] = { 2, 4, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countDivisorsMult(arr, n) << endl;
    return 0;
}


Java
// A simple Java program to count divisors
// in array multiplication.
 
class GFG
{
    // To count number of factors in a number
    static int counDivisors(int X)
    {
        // Initialize count with 0
        int count = 0;
         
        // Increment count for every factor
        // of the given number X.
        for (int i = 1; i <= X; ++i)
        {
            if (X % i == 0) {
                count++;
            }
        }
     
        // Return number of factors
        return count;
    }
     
    // Returns number of divisors in array
    // multiplication
    static int countDivisorsMult(int arr[], int n)
    {
        // Multipliying all elements of
        // the given array.
        int mul = 1;
        for (int i = 0; i < n; ++i)
            mul *= arr[i];
         
        // Calling function which count
        // number of factors of the number
        return counDivisors(mul);
    }
     
     
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = { 2, 4, 6 };
        int n = arr.length;
        System.out.println(countDivisorsMult(arr, n));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# A simple Python program
# to count divisors
# in array multiplication.
 
# To count number of
# factors in a number
def counDivisors(X):
 
    # Initialize count with 0
    count = 0
    # Increment count for
    # every factor
    # of the given number X.
    for i in range(1, X + 1):
        if (X % i == 0):
            count += 1
  
    # Return number of factors
    return count
  
# Returns number of
# divisors in array
# multiplication
def countDivisorsMult(arr, n):
 
    # Multipliying all elements of
    # the given array.
    mul = 1
    for i in range(n):
        mul *= arr[i]
      
    # Calling function which
    # count number of factors
    # of the number
    return counDivisors(mul)
 
# Driver code
 
arr = [ 2, 4, 6 ]
n =len(arr)
 
print(countDivisorsMult(arr, n))
 
# This code is contributed
# by Anant Agarwal.


C#
// C# program to count divisors
// in array multiplication.
using System;
 
class GFG {
     
    // To count number of factors
    // in a number
    static int counDivisors(int X)
    {
         
        // Initialize count with 0
        int count = 0;
         
        // Increment count for every
        // factor of the given
        // number X.
        for (int i = 1; i <= X; ++i)
        {
            if (X % i == 0) {
                count++;
            }
        }
     
        // Return number of factors
        return count;
    }
     
    // Returns number of divisors in
    // array multiplication
    static int countDivisorsMult(
                    int []arr, int n)
    {
         
        // Multipliying all elements
        // of the given array.
        int mul = 1;
         
        for (int i = 0; i < n; ++i)
            mul *= arr[i];
         
        // Calling function which
        // count number of factors
        // of the number
        return counDivisors(mul);
    }
     
    // Driver code
    public static void Main ()
    {
         
        int []arr = { 2, 4, 6 };
        int n = arr.Length;
         
        Console.Write(
         countDivisorsMult(arr, n));
    }
}
 
// This code is contributed by
// nitin mittal.


PHP


C++
// C++ program to count divisors in array multiplication.
#include 
using namespace std;
 
void SieveOfEratosthenes(int largest, vector &prime)
{
   
    // Create a boolean array "isPrime[0..n]" and initialize
    // all entries it as true. A value in isPrime[i] will
    // finally be false if i is Not a isPrime, else true.
    bool isPrime[largest+1];
    memset(isPrime, true, sizeof(isPrime));
 
    for (int p = 2; p * p <= largest; p++)
    {
       
        // If isPrime[p] is not changed, then it is a isPrime
        if (isPrime[p] == true)
        {
           
            // Update all multiples of p
            for (int i = p * 2; i <= largest; i += p)
                isPrime[i] = false;
        }
    }
 
    // Print all isPrime numbers
    for (int p = 2; p <= largest; p++)
        if (isPrime[p])
            prime.push_back(p);
}
 
// Returns number of divisors in array
// multiplication
int countDivisorsMult(int arr[], int n)
{
   
    // Find all prime numbers smaller than
    // the largest element.
    int largest = *max_element(arr, arr+n);
    vector prime;
    SieveOfEratosthenes(largest, prime);
 
    // Find counts of occurrences of each prime
    // factor
    unordered_map mp;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < prime.size(); j++)
        {
            while(arr[i] > 1 && arr[i]%prime[j] == 0)
            {
                arr[i] /= prime[j];
                mp[prime[j]]++;
            }
        }
        if (arr[i] != 1)
            mp[arr[i]]++;
    }
 
    // Compute count of all divisors using counts
    // prime factors.
    long long int res = 1;
    for (auto it : mp)
       res *= (it.second + 1L);
    return res;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 4, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countDivisorsMult(arr, n) << endl;
    return 0;
}


Java
// Java program to count divisors in array multiplication.
import java.io.*;
import java.util.*;
class GFG
{
 
  static void SieveOfEratosthenes(int largest, ArrayList prime)
  {
 
    // Create a boolean array "isPrime[0..n]" and initialize
    // all entries it as true. A value in isPrime[i] will
    // finally be false if i is Not a isPrime, else true.
    boolean[] isPrime = new boolean[largest + 1];
    Arrays.fill(isPrime, true);
 
    for (int p = 2; p * p <= largest; p++)
    {
 
      // If isPrime[p] is not changed, then it is a isPrime
      if (isPrime[p] == true)
      {
 
        // Update all multiples of p
        for (int i = p * 2; i <= largest; i += p)
          isPrime[i] = false;
      }
    }
 
    // Print all isPrime numbers
    for (int p = 2; p <= largest; p++)
      if (isPrime[p])
        prime.add(p);
  }
 
  // Returns number of divisors in array
  // multiplication
  static long countDivisorsMult(int[] arr, int n)
  {
 
    // Find all prime numbers smaller than
    // the largest element.
    int largest = 0;
    for(int a : arr )
    {
      largest=Math.max(largest, a);
    }
 
    ArrayList prime = new ArrayList();
    SieveOfEratosthenes(largest, prime);
 
    // Find counts of occurrences of each prime
    // factor
    Map mp = new HashMap<>();
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < prime.size(); j++)
      {
        while(arr[i] > 1 && arr[i]%prime.get(j) == 0)
        {
          arr[i] /= prime.get(j);
          if(mp.containsKey(prime.get(j)))
          {
            mp.put(prime.get(j), mp.get(prime.get(j)) + 1);
          }
          else
          {
            mp.put(prime.get(j), 1);
          }
        }
      }
      if (arr[i] != 1)
      {
        if(mp.containsKey(arr[i]))
        {
          mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
          mp.put(arr[i], 1);
        }
      }
    }
 
    // Compute count of all divisors using counts
    // prime factors.
    long res = 1;
    for (int it : mp.keySet())
      res *= (mp.get(it) + 1L);
    return res;
  }
 
  // Driver code
  public static void main (String[] args) {
    int arr[] = { 2, 4, 6 };
    int n = arr.length;
    System.out.println(countDivisorsMult(arr, n));
  }
}
 
// This code is contributed by avanitrachhadiya2155


Python3
# Python 3 program to count divisors in array multiplication.
from collections import defaultdict
def SieveOfEratosthenes(largest, prime):
 
    # Create a boolean array "isPrime[0..n]" and initialize
    # all entries it as true. A value in isPrime[i] will
    # finally be false if i is Not a isPrime, else true.
    isPrime = [True] * (largest + 1)
 
    p = 2
    while p * p <= largest:
 
        # If isPrime[p] is not changed, then it is a isPrime
        if (isPrime[p] == True):
 
            # Update all multiples of p
            for i in range(p * 2, largest + 1, p):
                isPrime[i] = False
        p += 1
 
    # Print all isPrime numbers
    for p in range(2, largest + 1):
        if (isPrime[p]):
            prime.append(p)
 
# Returns number of divisors in array
# multiplication
def countDivisorsMult(arr, n):
 
    # Find all prime numbers smaller than
    # the largest element.
    largest = max(arr)
    prime = []
    SieveOfEratosthenes(largest, prime)
 
    # Find counts of occurrences of each prime
    # factor
    mp = defaultdict(int)
    for i in range(n):
        for j in range(len(prime)):
            while(arr[i] > 1 and arr[i] % prime[j] == 0):
                arr[i] //= prime[j]
                mp[prime[j]] += 1
        if (arr[i] != 1):
            mp[arr[i]] += 1
 
    # Compute count of all divisors using counts
    # prime factors.
    res = 1
    for it in mp.values():
        res *= (it + 1)
    return res
 
# Driver code
if __name__ == "__main__":
 
    arr = [2, 4, 6]
    n = len(arr)
    print(countDivisorsMult(arr, n))
 
    # This code is contributed by chitranayal.


C#
// C# program to count divisors in array multiplication.
using System;
using System.Collections.Generic;
 
class GFG{
     
static void SieveOfEratosthenes(int largest,
                                List prime)
{
 
    // Create a boolean array "isPrime[0..n]" and initialize
    // all entries it as true. A value in isPrime[i] will
    // finally be false if i is Not a isPrime, else true.
    bool[] isPrime = new bool[largest + 1];
    Array.Fill(isPrime, true);
     
    for(int p = 2; p * p <= largest; p++)
    {
     
        // If isPrime[p] is not changed, then it is a isPrime
        if (isPrime[p] == true)
        {
         
            // Update all multiples of p
            for (int i = p * 2; i <= largest; i += p)
                isPrime[i] = false;
        }
    }
     
    // Print all isPrime numbers
    for(int p = 2; p <= largest; p++)
        if (isPrime[p])
            prime.Add(p);
}
 
// Returns number of divisors in array
// multiplication
static long countDivisorsMult(int[] arr, int n)
{
     
    // Find all prime numbers smaller than
    // the largest element.
    int largest = 0;
    foreach(int a in arr )
    {
        largest = Math.Max(largest, a);
    }
     
    List prime = new List();
    SieveOfEratosthenes(largest, prime);
     
    // Find counts of occurrences of each prime
    // factor
    Dictionary mp = new Dictionary();
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < prime.Count; j++)
        {
            while(arr[i] > 1 && arr[i] % prime[j] == 0)
            {
                arr[i] /= prime[j];
                if (mp.ContainsKey(prime[j]))
                {
                    mp[prime[j]]++;
                }
                else
                {
                    mp.Add(prime[j], 1);
                }
            }
        }
        if (arr[i] != 1)
        {
            if(mp.ContainsKey(arr[i]))
            {
                mp[arr[i]]++;
            }
            else
            {
                mp.Add(arr[i], 1);
            }
        }
    }
 
    // Compute count of all divisors using counts
    // prime factors.
    long res = 1;
    foreach(KeyValuePair it in mp)
        res *= (it.Value + 1L);
         
    return res;
}
 
// Driver code
static public void Main()
{
    int[] arr = { 2, 4, 6 };
    int n = arr.Length;
     
    Console.WriteLine(countDivisorsMult(arr, n));
}
}
 
// This code is contributed by rag2127


输出:

10

方法2(避免溢出)
1.查找数组中的最大元素
1.查找小于最大元素的质数
3.通过遍历所有数组元素并找到它们的主要因子,找到整个数组中每个主要因子的总出现次数。我们使用散列来计算出现次数。
4.设素因子的出现次数为a1,a2,…aK,如果我们有K个不同的素因子,则答案为:(a1 + 1)(a2 + 1)(…)*(aK + 1) )。

C++

// C++ program to count divisors in array multiplication.
#include 
using namespace std;
 
void SieveOfEratosthenes(int largest, vector &prime)
{
   
    // Create a boolean array "isPrime[0..n]" and initialize
    // all entries it as true. A value in isPrime[i] will
    // finally be false if i is Not a isPrime, else true.
    bool isPrime[largest+1];
    memset(isPrime, true, sizeof(isPrime));
 
    for (int p = 2; p * p <= largest; p++)
    {
       
        // If isPrime[p] is not changed, then it is a isPrime
        if (isPrime[p] == true)
        {
           
            // Update all multiples of p
            for (int i = p * 2; i <= largest; i += p)
                isPrime[i] = false;
        }
    }
 
    // Print all isPrime numbers
    for (int p = 2; p <= largest; p++)
        if (isPrime[p])
            prime.push_back(p);
}
 
// Returns number of divisors in array
// multiplication
int countDivisorsMult(int arr[], int n)
{
   
    // Find all prime numbers smaller than
    // the largest element.
    int largest = *max_element(arr, arr+n);
    vector prime;
    SieveOfEratosthenes(largest, prime);
 
    // Find counts of occurrences of each prime
    // factor
    unordered_map mp;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < prime.size(); j++)
        {
            while(arr[i] > 1 && arr[i]%prime[j] == 0)
            {
                arr[i] /= prime[j];
                mp[prime[j]]++;
            }
        }
        if (arr[i] != 1)
            mp[arr[i]]++;
    }
 
    // Compute count of all divisors using counts
    // prime factors.
    long long int res = 1;
    for (auto it : mp)
       res *= (it.second + 1L);
    return res;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 4, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countDivisorsMult(arr, n) << endl;
    return 0;
}

Java

// Java program to count divisors in array multiplication.
import java.io.*;
import java.util.*;
class GFG
{
 
  static void SieveOfEratosthenes(int largest, ArrayList prime)
  {
 
    // Create a boolean array "isPrime[0..n]" and initialize
    // all entries it as true. A value in isPrime[i] will
    // finally be false if i is Not a isPrime, else true.
    boolean[] isPrime = new boolean[largest + 1];
    Arrays.fill(isPrime, true);
 
    for (int p = 2; p * p <= largest; p++)
    {
 
      // If isPrime[p] is not changed, then it is a isPrime
      if (isPrime[p] == true)
      {
 
        // Update all multiples of p
        for (int i = p * 2; i <= largest; i += p)
          isPrime[i] = false;
      }
    }
 
    // Print all isPrime numbers
    for (int p = 2; p <= largest; p++)
      if (isPrime[p])
        prime.add(p);
  }
 
  // Returns number of divisors in array
  // multiplication
  static long countDivisorsMult(int[] arr, int n)
  {
 
    // Find all prime numbers smaller than
    // the largest element.
    int largest = 0;
    for(int a : arr )
    {
      largest=Math.max(largest, a);
    }
 
    ArrayList prime = new ArrayList();
    SieveOfEratosthenes(largest, prime);
 
    // Find counts of occurrences of each prime
    // factor
    Map mp = new HashMap<>();
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < prime.size(); j++)
      {
        while(arr[i] > 1 && arr[i]%prime.get(j) == 0)
        {
          arr[i] /= prime.get(j);
          if(mp.containsKey(prime.get(j)))
          {
            mp.put(prime.get(j), mp.get(prime.get(j)) + 1);
          }
          else
          {
            mp.put(prime.get(j), 1);
          }
        }
      }
      if (arr[i] != 1)
      {
        if(mp.containsKey(arr[i]))
        {
          mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
          mp.put(arr[i], 1);
        }
      }
    }
 
    // Compute count of all divisors using counts
    // prime factors.
    long res = 1;
    for (int it : mp.keySet())
      res *= (mp.get(it) + 1L);
    return res;
  }
 
  // Driver code
  public static void main (String[] args) {
    int arr[] = { 2, 4, 6 };
    int n = arr.length;
    System.out.println(countDivisorsMult(arr, n));
  }
}
 
// This code is contributed by avanitrachhadiya2155

Python3

# Python 3 program to count divisors in array multiplication.
from collections import defaultdict
def SieveOfEratosthenes(largest, prime):
 
    # Create a boolean array "isPrime[0..n]" and initialize
    # all entries it as true. A value in isPrime[i] will
    # finally be false if i is Not a isPrime, else true.
    isPrime = [True] * (largest + 1)
 
    p = 2
    while p * p <= largest:
 
        # If isPrime[p] is not changed, then it is a isPrime
        if (isPrime[p] == True):
 
            # Update all multiples of p
            for i in range(p * 2, largest + 1, p):
                isPrime[i] = False
        p += 1
 
    # Print all isPrime numbers
    for p in range(2, largest + 1):
        if (isPrime[p]):
            prime.append(p)
 
# Returns number of divisors in array
# multiplication
def countDivisorsMult(arr, n):
 
    # Find all prime numbers smaller than
    # the largest element.
    largest = max(arr)
    prime = []
    SieveOfEratosthenes(largest, prime)
 
    # Find counts of occurrences of each prime
    # factor
    mp = defaultdict(int)
    for i in range(n):
        for j in range(len(prime)):
            while(arr[i] > 1 and arr[i] % prime[j] == 0):
                arr[i] //= prime[j]
                mp[prime[j]] += 1
        if (arr[i] != 1):
            mp[arr[i]] += 1
 
    # Compute count of all divisors using counts
    # prime factors.
    res = 1
    for it in mp.values():
        res *= (it + 1)
    return res
 
# Driver code
if __name__ == "__main__":
 
    arr = [2, 4, 6]
    n = len(arr)
    print(countDivisorsMult(arr, n))
 
    # This code is contributed by chitranayal.

C#

// C# program to count divisors in array multiplication.
using System;
using System.Collections.Generic;
 
class GFG{
     
static void SieveOfEratosthenes(int largest,
                                List prime)
{
 
    // Create a boolean array "isPrime[0..n]" and initialize
    // all entries it as true. A value in isPrime[i] will
    // finally be false if i is Not a isPrime, else true.
    bool[] isPrime = new bool[largest + 1];
    Array.Fill(isPrime, true);
     
    for(int p = 2; p * p <= largest; p++)
    {
     
        // If isPrime[p] is not changed, then it is a isPrime
        if (isPrime[p] == true)
        {
         
            // Update all multiples of p
            for (int i = p * 2; i <= largest; i += p)
                isPrime[i] = false;
        }
    }
     
    // Print all isPrime numbers
    for(int p = 2; p <= largest; p++)
        if (isPrime[p])
            prime.Add(p);
}
 
// Returns number of divisors in array
// multiplication
static long countDivisorsMult(int[] arr, int n)
{
     
    // Find all prime numbers smaller than
    // the largest element.
    int largest = 0;
    foreach(int a in arr )
    {
        largest = Math.Max(largest, a);
    }
     
    List prime = new List();
    SieveOfEratosthenes(largest, prime);
     
    // Find counts of occurrences of each prime
    // factor
    Dictionary mp = new Dictionary();
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < prime.Count; j++)
        {
            while(arr[i] > 1 && arr[i] % prime[j] == 0)
            {
                arr[i] /= prime[j];
                if (mp.ContainsKey(prime[j]))
                {
                    mp[prime[j]]++;
                }
                else
                {
                    mp.Add(prime[j], 1);
                }
            }
        }
        if (arr[i] != 1)
        {
            if(mp.ContainsKey(arr[i]))
            {
                mp[arr[i]]++;
            }
            else
            {
                mp.Add(arr[i], 1);
            }
        }
    }
 
    // Compute count of all divisors using counts
    // prime factors.
    long res = 1;
    foreach(KeyValuePair it in mp)
        res *= (it.Value + 1L);
         
    return res;
}
 
// Driver code
static public void Main()
{
    int[] arr = { 2, 4, 6 };
    int n = arr.Length;
     
    Console.WriteLine(countDivisorsMult(arr, n));
}
}
 
// This code is contributed by rag2127

输出:

10