【ACM】杭电1141:Factstone Benchmark

我觉得这道题 值得一写,是因为它用到了取对数的方法来处理数值过大的阶乘问题。这种方法应该熟练掌握。

分析:

问题实际上可以转化成一个不等式: n ! < 2 ^ n 

即求使上述不等式成立的最大的整数n.

如果直接枚举的话,势必溢出。所以应该用取对数的方法来避免处理过大的数。

首先对不等式两边都取自然对数,得:

ln(n!) < n * ln(2)

这时候数据就被大大缩小了。

代码 :

#include <stdio.h>
#include <math.h>
int Pow(int bottom,int bit) /* 用来求bottom的bit次方 */
{
	int i,res = 1;
	for(i = 1 ; i <= bit ; ++i)
		res *= bottom;
	return res;
}

int main(int argc, char *argv[])
{
	int yy;
	while(scanf("%d",&yy) != EOF && yy != 0)
	{
		int bit = Pow(2,((yy - 1960) / 10 + 2)); /* 计算当年的位数 */
		double max = bit * log(2); /* 对这几位所能表示的最大的数取自然对数 */
		double sum = 0;
		int i = 1;
		while(sum <= max)
		{
			sum += log(i);
			++i;
		}
		printf("%d\n",i - 2);
	}
	
	return 0;
}


你可能感兴趣的:(【ACM】杭电1141:Factstone Benchmark)