Count divisors of array multiplication in C++

C++Server Side ProgrammingProgramming

We are given an array let’s say, arr[] of integer elements of any given size and the task is to calculate the count of the factors of a number calculated by multiplying all the array elements.

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

For example

Input − int arr[] = {2, 3}
Output − count is 4

Explanation − the multiplication of array is 2 * 3 is 6 and the factors of 6 are 1, 2, 3, 6. So in total there are 4 factors of 6.

Input − int arr[] = {2, 3, 5}
Output − count is 8

Explanation − the multiplication of array is 2 * 3 * 5 is 30 and the factors of 30 are 1, 2, 3, 5, 6, 10, 15, 30. So in total there are 8 factors of 30.

Approach used in the below program is as follows

  • Create an array let’s say, arr[]

  • Calculate the length of an array using the length() function that will return an integer value as per the elements in an array.

  • Declare a temporary variable let’s say, temp set it to 1

  • Start loop for i to 0 and i less than size of array

  • Set temp to temp * = arr[i]

  • Call another function that will return a count.

  • Take a temporary variable that will store the count of elements.

  • Start loop for i to 1 and i less than equals to mul.

  • Inside loop, check if temp % i = 0 then increment the value of count by 1.

  • Return the count

  • Print the result.

Example

 Live Demo

#include <iostream>
using namespace std;
// Function to count number of factors
int divisors(int N){
   // Initialize result with 0
   int result = 0;
   // Increment result for every factor
   // of the given number N.
   for (int i = 1; i <= N; ++i){
      if (N % i == 0){
         result++;
      }
   }
   return result;
}
int countmultiples(int arr_1[], int size){
   // To multiply all elements of
   // the given array.
   int temp = 1;
   for (int i = 0; i < size; ++i){
      temp *= arr_1[i];
   }
   return divisors(temp);
}
// main function
int main(){
   int arr_1[] = { 5, 10, 15 };
   int size = sizeof(arr_1) / sizeof(arr_1[0]);
   cout <<"count is "<<countmultiples(arr_1, size);
   return 0;
}

Output

If we run the above code we will get the following output −

count is 16
raja
Published on 15-May-2020 15:31:54
Advertisements