Topic Links:
http://poj.org/problem?id=1423
http://acm.hdu.edu.cn/showproblem.php?pid=1018
Main topic:
Ask n! how many bits there are. 1<=n<=10^7.
Ideas:
N is a large scale. You cannot directly simulate the number of digits to be evaluated. Consider this approach first:
Set a = N! = 1*2*3*4*...*n, then the number of digits is (int) log10 (A) + 1
and (int) log10 (A) = log10 (1*2*3*...*n) = log10 (1) * LOG10 (2) * LOG10 (3) * ... * LOG10 (N)
This adds up to the result. But because N is 10^7 scale, so the accumulation on the HDU can be AC, but
The POJ is still timed out.
It should be done with a sterling formula. Stirling Formula: When N is big enough, n! = (n/e) * N * sqrt (2*pi*n).
log10 (N) + 1 = (int) (LOG10 (2*pi*n)/2 + N*LOG10 (n/e) + 1. the constant e and π are used. To ensure that the fine
degrees, define the constant E = 2.7182818284590452354, define PI = 3.1415926535897932385.
AC Code:
poj1423#include<iostream> #include <algorithm> #include <cstdio> #include <cstring># Include<cmath>using namespace Std;const Double e = 2.7182818284590452354;const double pi = 3.1415926535897932385; Double strling (int N) { return 0.5*log10 (2*pi*n) + n*log10 (n/e);} int main () { int t,n; Cin >> T; while (t--) { cin >> N; cout << (int) strling (N) +1 << Endl; } return 0;}
hdu1018# include<stdio.h># Include<math.h>int Main () { int n,m,i; Double sum; scanf ("%d", &n); while (n--) { scanf ("%d", &m); sum = 0; for (i=1;i<=m;i++) sum + = (log10 (i)); printf ("%d\n", (int) sum+1); } return 0;}
POJ1423 HDU1018 "Sterling formula" "High precision"