B - tcaF Editorial by en_translator
The maximum \(X\) with \(2 \leq X \leq 3 \times 10^{18}\) such that there exists \(N\) with \(N! = X\) is \(2432902008176640000 (=20!)\). Also, we have \(2 \leq N\) because \(2 \leq X\).
Thus, the answer can be found with a for statement in the following way:
- For \(i=2,\ldots,20\) in order, do the following.
- Prepare a variable \(f\) to evaluate \(i!\). \(f\) is initialized with \(1\).
- For \(j=1,\ldots i\) in order, do the following.
- Multiply \(f\) by \(j\).
- If \(f\) equals \(X\), print \(i\).
The time complexity is \(O(N^2)\), where \(N\) denotes the maximum possible answer. This time, \(N = 20\), so it is fast enough. On implementing, beware that using 32-bit integers causes overflows.
One can also calculate \(i!\) for each \(i\) sequentially, the problem can be solved in \(O(N)\) time too.
Sample code (C++):
#include <bits/stdc++.h>
using namespace std;
int main() {
long long x;
cin >> x;
for (int i = 2; i <= 20; ++i) {
long long f = 1;
for (int j = 1; j <= i; ++j) {
f *= j;
}
if (f == x) {
cout << i << endl;
}
}
}
posted:
last update: