Queries for counts of multiples in an array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an arr[] and Q queries each consisting of a value m. Our task is to create a program to solve the Queries for counts of multiples in an array in C++.

Problem Description

For solving the queries, we need to count all the numbers that are multiples of m. For this we will check for elements divisible by m.

Let’s take an example to understand the problem,

Input:arr[] = {4, 7, 3, 8, 12, 15}

Q = 3 query[] = {2, 3, 5}

Ouput:3 3 1

Explanation

Query 1: m = 2, multiples in the array = 4, 8, 12. Count = 3.

Query 2: m = 3, multiples in the array = 3, 12, 15. Count = 3.

Query 3: m = 5, multiples in the array = 15. Count = 1.

Solution Approach

A simple solution is by traversing the array for each query value and counting the number of elements of the array divisible by m.

Example

 Live Demo

#include <iostream>
using namespace std;
int solveQuery(int arr[], int N, int m){
   int count = 0;
   for(int i = 0; i < N; i++){
      if(arr[i]%m == 0)
         count++;
   }
   return count;
}
int main(){
   int arr[] = {4, 7, 3, 8, 12, 15};
   int N = sizeof(arr)/sizeof(arr[0]);
   int Q = 3;
   int query[] = {2, 3, 5};
   for(int i = 0; i < Q; i++)
      cout<<"The count of multiples in array "<<solveQuery(arr, N,query[i])<<endl;
   return 0;
}

Output

The count of multiples in array 3
The count of multiples in array 3
The count of multiples in array 1

This solution, traverses the array once for every query that makes the time complexity O(Q*n).

A better solution is by using the Sieve of Eratosthenes to find all the multiple

and element counts for the given array. The idea is to pre-calculate the count of multiples of all elements upto the maximum value of the array. And then calling the precalculated array to find the counts of multiples for queries.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int preCalcCount[10001];
void PreCalculateMultiples(int arr[], int N){
   int maxVal = *max_element(arr, arr + N);
   int count[maxVal + 1];
   memset(count, 0, sizeof(count));
   memset(preCalcCount, 0, (maxVal + 1) * sizeof(int));
   for (int i = 0; i < N; ++i)
      ++count[arr[i]];
   for (int i = 1; i <= maxVal; ++i)
      for (int j = i; j <= maxVal; j += i)
         preCalcCount[i] += count[j];

}
int main(){
   int arr[] = {4, 7, 3, 8, 12, 15};
   int N = sizeof(arr)/sizeof(arr[0]);
   int Q = 3;
   int query[Q] = {2, 3, 5};
   PreCalculateMultiples(arr, N);
   for(int i = 0; i < Q; i++)
      cout<<"The count of multiples in array"<<preCalcCount[query[i]]<<endl;
   return 0;
}

Output

The count of multiples in array 3
The count of multiples in array 3
The count of multiples in array 1
raja
Published on 06-Aug-2020 10:45:52
Advertisements