HDU 1018 Big Number(求n!的位数)
2013-10-18 17:14
405 查看
转载请注明出处:忆梦http://blog.csdn.net/yimeng2013/article/details/12856081
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1018题意:计算n!结果的位数(1<= n <= 10^7)
题解:
①我们先来讨论任意一个数a如何求解其位数,
设a的位数为x,既有:10^(x-1) <= a < 10^x
取对数有:log10(10^(x-1)) <= log10(a) < log10(10^x)
即:x-1 <= log10(a) < x;
则:(int)log10(a) = x-1;
所以: x =
(int)log10(a)+1;
②n! = 1*2*3……*n
所以[b]n! 的位数 = (int)log10(1*2*3……*n)+1 = (int)(log10(1)+log10(2)+……+log10(n))
+ 1;[/b]
超内存的代码:
#include<cstdio> #include<cmath> #include<cstring> #define N 10000000 int ans[N+5]; int main () { double s = 0; for(int i = 1; i <= N; i++) { s += log10(i); ans[i] = (int)s + 1; } int T; scanf("%d", &T); while(T--) { int n; scanf("%d", &n); printf("%d\n", ans ); } return 0; }
AC:968MS
#include<cstdio> #include<cmath> int main () { int T; scanf("%d", &T); while(T--) { int n; scanf("%d", &n); double s = 0; for(int i = 1; i <= n; i++) s += log10(i); printf("%d\n", int(s)+1); } return 0; }
网上0MS的程序
《计算机程序设计艺术》中给出了另一个公式
n! = sqrt(2*π*n) * ((n/e)^n) * (1 + 1/(12*n) + 1/(288*n*n) + O(1/n^3))
π = acos(-1)
e = exp(1)
两边对10取对数
忽略log10(1 + 1/(12*n) + 1/(288*n*n) + O(1/n^3)) ≈ log10(1) = 0
得到公式
log10(n!) = log10(sqrt(2 * pi * n)) + n * log10(n / e)
#include<iostream> #include<cmath> using namespace std; int main() { double Pi = acos(-1.0); double E = exp(1.0); int n,m; cin >> m; while(m--) { cin >> n; double len = (log10(sqrt(2 * Pi * n)) + n * log10(n/E) ); cout <<(int) len +1 << endl; } return 0; }
相关文章推荐
- HDU--1018--Big number!(计算阶乘结果的位数)
- HDU 1018 Big Number (log函数求数的位数)
- HDU 1018 Big Number【阶乘位数】
- Hdu 1018 Big Number 求N!的位数
- HDU 1018 Big Number N!的位数
- hdu 1018 Big Number (求一个数的阶乘的位数,公式!!!)
- HDU 1018 Big Number(求n!的位数)
- hdu 1018 Big Number (求一个数的阶乘的位数,公式!!!)
- HDU1018 Big Number(求阶乘位数)
- HDU 1018 Big Number (log函数求数的位数)
- 【HDU 1018】Big Number —— n!的位数
- hdu 1018 Big Number(求阶乘的位数)
- hdu 1018 Big Number(n!求位数)
- HDU 1018 Big Number(阶乘位数计算)
- hdu 1018 Big Number_Stirling数求N!的位数
- HDU1018 Big Number n!的位数
- hdu 1018 -Big Number(求n的阶乘的位数)
- HDU 1018 Big Number 计算N!的位数
- 求位数 hdu 1018 Big Number
- hdu 1018 big number (求N!的位数)