Numbers whose factorials end with n zeros | Binary search based CPP program to find numbers with n trailing zeros . ; Function to calculate trailing zeros ; binary search for first number with n trailing zeros ; Print all numbers after low with n trailing zeros . ; Print result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int trailingZeroes ( int n ) { int cnt = 0 ; while ( n > 0 ) { n /= 5 ; cnt += n ; } return cnt ; } void binarySearch ( int n ) { int low = 0 ; while ( low < high ) { int mid = ( low + high ) / 2 ; int count = trailingZeroes ( mid ) ; if ( count < n ) low = mid + 1 ; else high = mid ; } vector < int > result ; while ( trailingZeroes ( low ) == n ) { result . push_back ( low ) ; low ++ ; } for ( int i = 0 ; i < result . size ( ) ; i ++ ) cout << result [ i ] << " ▁ " ; } int main ( ) { int n = 2 ; binarySearch ( n ) ; return 0 ; }