PROBLEM LINK:
Author: Hanzala Sohrab
DIFFICULTY:
EASY-MEDIUM
PREREQUISITES:
Factorial, Math, Number Theory
PROBLEM:
Given a non-negative integer N, find the position of the last non-zero digit (from the left) in N!.
EXPLANATION:
Method - I :
Compute N! and then find the position of the last non-zero digit. But this is not a good solution for this problem.
Method - II :
Total number of digits in a positive integer M = \lfloor log_{10}(M)\rfloor + 1
Let D be the total number of digits in N!.
Let M = N!
As M = N! = 1*2*3* ... * (N - 1) * N.
\implies log_{10}(M) = log_{10}(N!) = log_{10}(1) + log_{10}(2) + log_{10}(3) + ... + log_{10}(N-1) + log_{10}(N).
\therefore D = \lfloor log_{10}(M)\rfloor + 1
Let Z be the total number of trailing zeroes in N!.
Suppose N < 5^k
\therefore Z = \Big\lfloor \frac{N}{5}\Big\rfloor + \Big\lfloor \frac{N}{5^2}\Big\rfloor + ... + \Big\lfloor \frac{N}{5^{k - 1}}\Big\rfloor
Let P be the position of the last non-zero digit in N!.
Then, P = (Total number of digits in N!) - (Total number of trailing zeroes).
\therefore P = D - Z
However, this approach won’t help you much. There’s still a better approach.
Method - III :
Dmitry Kamenetsky proposed a formula which works well for integers up to 10^9.
In fact, 6561101970383 is the first integer for which the formula gives a slightly incorrect answer.
Kamenetsky’s formula is given as :
D = \bigg\lfloor N * log_{10}\big(\frac{N}{e}) + \frac{log_{10}(2 * N * \pi)}{2}\bigg\rfloor + 1
where D is the total number of digits in N!.
REFERENCES:
Count number of digits in N! using Kamenetsky’s formula - GeeksforGeeks
SOLUTIONS:
Setter's Solution
#include<bits/stdc++.h>
using namespace std;
int main() {
cin.sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
while (T--)
{
long long N, i, d = 0, z = 0;
double dig = 0;
cin >> N;
if (N == 0 or N == 1)
{
cout << "1\n";
continue;
}
// SIMPLE SOLUTION USING LOOP
// for (i = 1; i <= N; ++i)
// dig += log10(i);
// SLIGHTLY COMPLEX SOLUTION
dig = ((N * log10(N / M_E) +
log10(2 * M_PI * N) /
2.0));
d = floor(dig) + 1;
for (i = 5; N / i >= 1; i *= 5)
z += N / i;
cout << d - z << '\n';
}
return 0;
}