题目36:数的长度

来源:互联网 发布:python毕业设计项目 编辑:程序博客网 时间:2024/05/21 08:02

题目链接:

http://acm.nyist.net/JudgeOnline/problem.php?cid=330&cpid=36

描述

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

输入

首行输入n,表示有多少组测试数据(n<10)
随后n行每行输入一组测试数据 N( 0 < N < 1000000 )

输出

对于每个数N,输出N!的(十进制)位数。

样例输入

3
1
3
32000

样例输出

1
1
130271

算法思想:

这道题只是需要求出X = N!数有多少位数,可以对两边对数log(X) = log(N!) = log(1) + log(2) + log(3) + …… + log(N),此时注意,如果取对数以10为底,其最右边表达式的和向上取整即为N!的位数。

源代码

#include <iostream>#include <cmath>#include <iomanip>using namespace std;int main(){    int n, N;    double ans;    cin >> n;    while (n--)    {        cin >> N;        ans = 0;        if (N == 1)        {            cout << "1" << endl;            continue;        }        for (int i = 2; i <= N; i++)        {            ans += log10(i);        }        cout <<fixed<<setprecision(0)<< ceil(ans) << endl;    }    return 0;}

最优源代码

/*  NYOJ69 阶乘数位长度  *  方法一: *  可设想n!的结果是不大于10的M次幂的数,即n!<=10^M(10的M次方),则不小于M的最小整数就是 n!的位数,对 *  该式两边取对数,有 M =log10^n! 即:M = log10^1+log10^2+log10^3...+log10^n 循环求和,就能算得M值, *  该M是n!的精确位数。当n比较大的时候,这种方法方法需要花费很多的时间。 *   *  方法二: *  利用斯特林(Stirling)公式的进行求解。下面是推导得到的公式: *  res=(long)( (log10(sqrt(4.0*acos(0.0)*n)) + n*(log10(n)-log10(exp(1.0)))) + 1 ); *  当n=1的时候,上面的公式不适用,所以要单独处理n=1的情况! *  有关斯特林(Stirling)公式及其相关推导,这里就不进行详细描述,有兴趣的话可看这里。 *  这种方法速度很快就可以得到结果。详细证明如下: *  http://episte.math.ntu.edu.tw/articles/mm/mm_17_2_05/index.html*/#include<iostream>#include <cmath>using namespace std;int normal(double n){    double x=0;    while(n)    {        x +=log10(n);        n--;    }    return (int)x+1;}long stirling(double n){    long x=0;    if( n ==1 )        x = 1;    else    {        x = (long)( (log10(sqrt(4.0*acos(0.0)*n)) + n*(log10(n)-log10(exp(1.0)))) + 1 );    }     return x;}int main(){    int n;    cin>>n;    while(n--)    {        int x;        cin>>x;        cout<<stirling(x)<<endl;    }    return 0;}                
原创粉丝点击