Find the smallest number X such that X! contains at least Y trailing zeros in C++


We have to take a number Y, we will find smallest number X, such that X! contains at least Y number of training zeros. For example, if Y = 2, then the value of X = 10. As X! = 3228800. It has Y number of zeros.

We can solve this using binary search. The number of trailing zeros in N! is given by the count of the factors 5 in N!. X can be found using binary search in range [0, 5*Y]

Example

#include<iostream>
using namespace std;
int factorCount(int n, int X) {
   if (X < n)
      return 0;
   return (X / n + factorCount(n, X / n));
}
int findX(int Y) {
   int left = 0, right = 5 * Y;
   int N = 0;
   while (left <= right) {
      int mid = (right + left) / 2;
   if (factorCount(5, mid) < Y) {
      left = mid + 1;
   }else {
      N = mid;
      right = mid - 1;
      }
   }
   return N;
}
int main() {
   int Y = 4;
   cout << "Smallest value of X: " << findX(Y);
}

Output

Smallest value of X: 20

Updated on: 04-Nov-2019

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements