📜  查询数组中倍数的计数

📅  最后修改于: 2021-04-26 07:02:30             🧑  作者: Mango

给定正整数数组和许多除数查询。在每个查询中,我们都得到一个整数k(> 0),我们需要计算数组中所有可以被’k’完全整除的元素。

例子:

Input:
2 4 9 15 21 20
k = 2
k = 3
k = 5

Output:
3
3
2

Explanation:
Multiples of '2' in array are:- {2, 4, 20}
Multiples of '3' in array are:- {9, 15, 21}
Multiples of '5' in array are:- {15, 20}

简单方法是遍历整个数组中的每个’k’值,并通过检查数组中每个元素的模数来计算总倍数,即对于i(0

高效的方法是使用Eratosthenes筛网的概念。让我们定义array []中的最大值为’Max’。由于array []中所有数字的倍数始终小于Max,因此我们仅迭代到“ Max”。
现在对于每个值(例如’q’)迭代q,2q,3q,… tk (tk <= MAX),因为所有这些数字都是’ q ‘的倍数。 1,2,…MAX)在ans []数组中。之后,我们可以在O(1)时间内回答每个查询。

C++
// C++ program to calculate all multiples
// of integer 'k' in array[]
#include 
using namespace std;
  
// ans is global pointer so that both countSieve()
// and countMultiples() can access it.
int* ans = NULL;
  
// Function to pre-calculate all multiples of
// array elements
void countSieve(int arr[], int n)
{
    int MAX = *max_element(arr, arr + n);
  
    int cnt[MAX + 1];
  
    // ans is global pointer so that query function
    // can access it.
    ans = new int[MAX + 1];
  
    // Initialize both arrays as 0.
    memset(cnt, 0, sizeof(cnt));
    memset(ans, 0, (MAX + 1) * sizeof(int));
  
    // Store the arr[] elements as index
    // in cnt[] array
    for (int i = 0; i < n; ++i)
        ++cnt[arr[i]];
  
    // Iterate over all multiples as 'i'
    // and keep the count of array[] ( In
    // cnt[] array) elements in ans[] array
    for (int i = 1; i <= MAX; ++i)
        for (int j = i; j <= MAX; j += i)
            ans[i] += cnt[j];
    return;
}
  
int countMultiples(int k)
{
    // return pre-calculated result
    return ans[k];
}
  
// Driver code
int main()
{
    int arr[] = { 2, 4, 9, 15, 21, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // pre-calculate all multiples
    countSieve(arr, n);
  
    int k = 2;
    cout << countMultiples(k) << "\n";
  
    k = 3;
    cout << countMultiples(k) << "\n";
  
    k = 5;
    cout << countMultiples(k) << "\n";
    return 0;
}


Java
// Java program to calculate all multiples
// of integer 'k' in array[]
class CountMultiples {
    // ans is global array so that both
    // countSieve() and countMultiples()
    // can access it.
    static int ans[];
  
    // Function to pre-calculate all
    // multiples of array elements
    static void countSieve(int arr[], int n)
    {
        int MAX = arr[0];
        for (int i = 1; i < n; i++)
            MAX = Math.max(arr[i], MAX);
  
        int cnt[] = new int[MAX + 1];
  
        // ans is global array so that
        // query function can access it.
        ans = new int[MAX + 1];
  
        // Store the arr[] elements as
        // index in cnt[] array
        for (int i = 0; i < n; ++i)
            ++cnt[arr[i]];
  
        // Iterate over all multiples as 'i'
        // and keep the count of array[]
        // (In cnt[] array) elements in ans[]
        // array
        for (int i = 1; i <= MAX; ++i)
            for (int j = i; j <= MAX; j += i)
                ans[i] += cnt[j];
        return;
    }
  
    static int countMultiples(int k)
    {
        // return pre-calculated result
        return ans[k];
    }
  
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 2, 4, 9, 15, 21, 20 };
        int n = 6;
  
        // pre-calculate all multiples
        countSieve(arr, n);
  
        int k = 2;
        System.out.println(countMultiples(k));
  
        k = 3;
        System.out.println(countMultiples(k));
  
        k = 5;
        System.out.println(countMultiples(k));
    }
}
  
/*This code is contributed by Danish Kaleem */


Python3
# Python3 program to calculate all multiples
# of integer 'k' in array[]
  
# ans is global array so that both countSieve()
# and countMultiples() can access it.
ans = []
  
# Function to pre-calculate all multiples
# of array elements 
# Here, the arguments are as follows
# a: given array
# n: length of given array
def countSieve(arr, n):
      
    MAX=max(arr)
  
# Accessing the global array in the function
    global ans
  
# Initializing "ans" array with zeros
    ans = [0]*(MAX + 1)
  
# Initializing "cnt" array with zeros
    cnt = [0]*(MAX + 1)
  
#Store the arr[] elements as index in cnt[] array
    for i in range(n):
        cnt[arr[i]] += 1
  
# Iterate over all multiples as 'i' 
# and keep the count of array[] ( In 
# cnt[] array) elements in ans[] array 
    for i in range(1, MAX+1):
        for j in range(i, MAX+1, i):
            ans[i] += cnt[j]
  
def countMultiples(k):
# Return pre-calculated result
    return(ans[k])
  
# Driver code
if __name__ == "__main__":
    arr = [2, 4, 9 ,15, 21, 20]
    n=len(arr)
# Pre-calculate all multiples
    countSieve(arr, n)
    k=2
    print(countMultiples(2))
    k=3
    print(countMultiples(3))
    k=5
    print(countMultiples(5))
  
  
  
# This code is contributed by Pratik Somwanshi


C#
// C# program to calculate all multiples
// of integer 'k' in array[]
using System;
  
class GFG {
      
    // ans is global array so that both
    // countSieve() and countMultiples()
    // can access it.
    static int[] ans;
  
    // Function to pre-calculate all
    // multiples of array elements
    static void countSieve(int[] arr, int n)
    {
          
        int MAX = arr[0];
        for (int i = 1; i < n; i++)
            MAX = Math.Max(arr[i], MAX);
  
        int[] cnt = new int[MAX + 1];
  
        // ans is global array so that
        // query function can access it.
        ans = new int[MAX + 1];
  
        // Store the arr[] elements as
        // index in cnt[] array
        for (int i = 0; i < n; ++i)
            ++cnt[arr[i]];
  
        // Iterate over all multiples as 
        // 'i' and keep the count of 
        // array[] (In cnt[] array) 
        // elements in ans[] array
        for (int i = 1; i <= MAX; ++i)
            for (int j = i; j <= MAX; j += i)
                ans[i] += cnt[j];
                  
        return;
    }
  
    static int countMultiples(int k)
    {
          
        // return pre-calculated result
        return ans[k];
    }
  
    // Driver code
    public static void Main()
    {
        int[] arr = { 2, 4, 9, 15, 21, 20 };
        int n = 6;
  
        // pre-calculate all multiples
        countSieve(arr, n);
  
        int k = 2;
        Console.WriteLine(countMultiples(k));
  
        k = 3;
        Console.WriteLine(countMultiples(k));
  
        k = 5;
        Console.WriteLine(countMultiples(k));
    }
}
  
// This code is contributed by nitin mittal


PHP


输出:

3
3
2

时间复杂度: O(M * log(M)),其中M是数组元素中的最大值。
辅助空间: O(MAX)