数的长度 69 (数学+log的使用)

来源:互联网 发布:手机淘宝退货流程 编辑:程序博客网 时间:2024/05/16 17:28

数的长度

时间限制:3000 ms  |           内存限制:65535 KB
难度:1
描述

    N!阶乘是一个非常大的数,大家都知道计算公式是N!=N*(N-1)······*2*1.现在你的任务是计算出N!的位数有多少(十进制)?

输入
首行输入n,表示有多少组测试数据(n<10)
随后n行每行输入一组测试数据 N( 0 < N < 1000000 )
输出
对于每个数N,输出N!的(十进制)位数。
样例输入
31332000
样例输出
11130271
//对log的使用//1*2*3*4*5*.....*n的位数是(int)(log10(1)+log10(2)+log10(3)+log10(4)+log10(5) +......+log10(n))+1//因为log的值为浮点型。 #include<stdio.h>#include<math.h>int main(){int t;int n,i;double sum;scanf("%d",&t);while(t--){sum=0;scanf("%d",&n);for(i=1;i<=n;i++)sum+=log10(i);printf("%d\n",(int)sum+1);}return 0;}
 
关于斯特林公式的推导看http://episte.math.ntu.edu.tw/articles/mm/mm_17_2_05/page4.html
//用斯特林公式解,更省时。 //即:res=(long)( (log10(sqrt(4.0*acos(0.0)*n)) + n*(log10(n)-log10(exp(1.0)))) + 1 ); //当n=1的时候,上面的公式不适用,所以要单独处理n=1的情况!
 
#include<stdio.h>#include<math.h>int stirling(double n){long long m;if(n==1)m=1;elsem=(long)((log10(sqrt(4.0*acos(0.0)*n))+n*(log10(n)-log10(exp(1.0))))+1);return m;}int main(){int t;int n;scanf("%d",&t);while(t--){scanf("%d",&n);printf("%d\n",stirling(n));}return 0;} 

0 0