Count number of trailing zeros in product of array in C++


We are given an array Arr[] of positive integers of size N. The goal is to count the number of trailing zeroes present in the product of all elements of the array.

We will do this by counting the factors of each number. We will count 2 and 5 as factors of each number as the product of 2 and 5 is 10 which gives 1 trailing 0. In the end whichever count is smaller gives the count of trailing zeroes in the product. If we have 4 2’s and 6 5’s then there will be 4 trailing zeroes in the product − 2*2*2*2*5*5*5*5*5*5= 250000

Let’s understand with examples.

Input 

Arr[] = { 2, 5, 10, 15, 20, 25, 100 }

Output 

Number of trailing zeroes : 6

Explanation 

Factors 2 and 5 of each element of Arr[]:
Arr[0] = 2 : 2 twos=1, fives=0
Arr[1] = 5 : 5 twos=1, fives=1
Arr[2] = 10 : 2*5 twos=2, fives=2
Arr[3] = 15 : 3*5 twos=2, fives=3
Arr[4] = 20 : 2*2*5 twos=4, fives=4
Arr[5] = 25 : 5*5 twos=4, fives=6
Arr[6] = 100 : 2*2*5*5 twos=6, fives=8
Count of 2 is less so trailing zeroes will be 6.

Input 

Arr[] = { 10,10,10,10,10 }

Output 

Number of trailing zeroes : 5

Explanation 

Factors 2 and 5 of each element of Arr[]:
Arr[0] = 10 : 2*5 twos=1, fives=1
Arr[1] = 10 : 2*5 twos=2, fives=2
Arr[2] = 10 : 2*5 twos=3, fives=3
Arr[3] = 10 : 3*5 twos=4, fives=4
Arr[4] = 10 : 2*5 twos=5, fives=5
Count of 2 and 5 is equal so trailing zeroes will be 5.

Approach used in the below program is as follows

  • We take an array of positive integers of length N..

  • Function trailZeros(int arr[],int n) takes array and n as input and returns the number of trailing zeroes in the product of all elements.

  • Take the initial variable count as 0 for the number zeroes.

  • Take two variables twos and fives as count of 2’s and 5’s as factors.

  • Traverse array using for loop.

  • For each element if it is divisible by 2 or 5 then increment twos and fives and reduce it by 2 or 5.

  • At the end of for loop check value of twos and fives whichever is smaller.

  • Initialize count with lower of the two.

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h<
using namespace std;
int trailZeros(int arr[],int n){
   int count = 0;
   int twos = 0;
   int fives = 0;
   for (int i = 0; i < n; i++){
      while(arr[i]%2==0 || arr[i]%5==0){
         if(arr[i]%2==0){
            arr[i]=arr[i]/2;
            twos++;
         }
         if(arr[i]%5==0){
            arr[i]=arr[i]/5;
            fives++;
         }
      }
   }
   count=twos<fives?twos:fives;
   return count;
}
int main(){
   int Arr[]={ 12, 5 , 15, 8, 100, 40 };
   int Length= sizeof(Arr)/sizeof(Arr[0]);
   cout <<endl<< "Number of trailing zeroes : "<<trailZeros(Arr,Length);
   return 0;
}

Output

If we run the above code it will generate the following output −

Number of trailing zeroes : 5

Updated on: 31-Oct-2020

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements