现在的位置: 首页 > 综合 > 正文

NYOJ 69 数的长度

2016年09月29日 ⁄ 综合 ⁄ 共 1034字 ⁄ 字号 评论关闭

原题链接

直接用log10函数。注意结果要保存到double中。

附ac代码:

 
#include <stdio.h>
#include <math.h>

int main(){
	int n, t;
	double count;
	scanf("%d", &t);
	while(t-- && scanf("%d", &n)){
		count = 1;
		while(n)
			count += log10(n--);
		printf("%d\n", (int)count);
	}
	return 0;
}        

再附上NYOJ上的标程:(感谢原作者feihu

 
 
/*	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;
}                

抱歉!评论已关闭.