hdu1018 big number

强大的数学

题目要求很简单求n的阶乘的位数

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1018

首先是暴力求解 时间951ms差点没过。。

求数字n的位数 log10(n);

用的数学公式N!的位数=log10(N!)=log10(1)+log10(2)+...+log(N);

代码如下

#include <stdio.h>
#include <math.h>
int fun(int n) { double sum=0; //log10求出了小数所以用double
 for(int i=1;i<=n;i++) {
        sum+=log10(i); } return (int)sum+1; } int main() { int t; int n;
    scanf("%d",&t); while(t--) {
        scanf("%d",&n);
        printf("%d\n",fun(n)); } }
但是差点超时

然后还有一位伟大的数学家发明的公式斯特林数

log10(n!)=1.0/2*log10(2*pi*n)+n*log10(n/e)

代码如下

#include <stdio.h>
#include <math.h>
#define e 2.71828182
#define pi 3.1415926
int main() { int t; int n; double stl;//斯特林数
    scanf("%d",&t); while(t--) {
        scanf("%d",&n);
        stl=(1.0/2*log10(2*pi*n)+n*log10(n/e));
        printf("%d\n",(int)stl+1); } }

你可能感兴趣的:(HDU,数学题,ACMbegin)