
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Smallest Number X with 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
Advertisements