Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. in C++


Given an integer num as input. The goal is to find the number of trailing zeroes in the product 11 X 22 X 33 X…X numnum.

For Example

Input

num=5

Output

Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5

Explanation

The number of 2s and 5s in the product will be:
11 * 22* 33* 44* 55=11 * 22* 33* (22)4* 55. So total 10 2s and 5 5s, minimum is 5 so trailing zeroes will be 5.

Input

num=10

Output

Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5

Explanation

The number of 2s and 5s in the product will be:
11 *22*33*44*55*66 *77*88*99*1010 = 11 *22*33*44*55*66 *77*88*99*(2*5)10. So total 20 2s and 15 5s, minimum is 15 so trailing zeroes will be 15.

Approach used in the below program is as follows

In this approach we will count the number of 2s and 5s in prime factorization of each number in the product. As each number is raised to its own power, the minimum of count of 2s or 5s in factorization will give the count of trailing zeroes. As each 2*5 adds one 0 in the product.

  • Take an integer num as input.

  • Function count_trailing(int num) takes num and returns count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.....

  • Take the initial count as 0.

  • Take variables temp_2 = 0, temp_5 = 0 for counts of 2s and 5s.

  • Traverse using for loops from i=1 to i<=num.

  • Take temp as i.

  • While temp is divisible by 2 then reduce it to half and add i to count temp_2 as the number of 2s.

  • While temp is divisible by 5 then divide it by 5 and add i to count temp_5 as the number of 5s.

  • Take count as a minimum of two counts using count = min(temp_2, temp_5).

  • Return count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int count_trailing(int num){
   int count = 0;
   int temp_2 = 0;
   int temp_5 = 0;
   for (int i = 1; i <= num; i++){
      int temp = i;
      while(temp % 2 == 0 && temp > 0){
         temp = temp / 2;
         temp_2 = temp_2 + i;
      }
      while (temp % 5 == 0 && temp > 0){
         temp = temp / 5;
         temp_5 = temp_5+ i;
      }
   }
   count = min(temp_2, temp_5);
   return count;
}
int main(){
   int num = 5;
   cout<<"Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: "<<count_trailing(num);
   return 0;
}

Output

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

Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5

Updated on: 05-Jan-2021

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements