Preimage Size of Factorial Zeroes Function in C++


Suppose we have a function f(x), this will return the number of zeroes at the end of factorial of x. So for f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Now when we have K, we have to find how many non-negative integers x have the property that f(x) = K.

So if the input is like K = 2, then the answer will be 5.

To solve this, we will follow these steps −

  • Define a function ok(), this will take x,
  • ret := 0
  • for initialize i := 5, when i <= x, update i := i * 5, do −
    • ret := ret + x / i
  • return ret
  • From the main method, do the following −
  • if K is same as 0, then −
    • return 5
  • low := 1, high := K * 5
  • while low < high, do −
    • mid := low + (high - low) /2
    • x := ok(mid)
    • if x < K, then −
      • low := mid + 1
    • Otherwise
      • high := mid
  • return (if ok(low) is same as K, then 5, otherwise 0)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   lli ok(lli x){
      int ret = 0;
      for(lli i = 5; i <= x; i *= 5){
         ret += x / i;
      }
      return ret;
   }
   int preimageSizeFZF(int K) {
      if(K == 0) return 5;
      lli low = 1;
      lli high = (lli)K * 5;
      while(low < high){
         lli mid = low + (high - low) / 2;
         lli x = ok(mid);
         if(x < K){
            low = mid + 1;
         }else high = mid;
      }
      return ok(low) == K ? 5 : 0;
   }
};
main(){
   Solution ob;
   cout << (ob.preimageSizeFZF(2));
}

Input

2

Output

5

Updated on: 02-Jun-2020

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements