数的长度【南阳 oj 题目69】

来源:互联网 发布:js 禁用input select 编辑:程序博客网 时间:2024/05/02 06:09

点击打开链接


描述

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

输入
首行输入n,表示有多少组测试数据(n<10)
随后n行每行输入一组测试数据 N( 0 < N < 1000000 )
输出
对于每个数N,输出N!的(十进制)位数。
样例输入
31332000
样例输出
11130271

题解一:直接利用斯特林公式

s=(long)( (log10(sqrt(4.0*acos(0.0)*n)) + n*(log10(n)-log10(exp(1.0)))) + 1 );(n>1)

#include <iostream>#include <cstdio>#include <cmath>#include <algorithm>using namespace std;int main(){int t,n,s;cin>>t;while(t--){cin>>n;if(n==1)cout<<"1"<<endl;else    {s=(long)( (log10(sqrt(4.0*acos(0.0)*n)) + n*(log10(n)-log10(exp(1.0)))) + 1 );    cout<<s<<endl;}}return 0;}


题解二:设n!<=10^m,两边同时取对数可得m = log10^1+log10^2+log10^3...+log10^n,
然后利用for循环求m的值(n值过大可能会超时)

#include <iostream>#include <cstdio>#include <cmath>#include <algorithm>using namespace std;int main() {     int n;     cin>>n;     while(n--)     {              int m,s;              double t=1;              cin>>m;              for(int i=1;i<=m;i++)                    t=t+log10(i);              s=(int)t;            cout<<s<<endl;}     return 0;}