hdu 1018 big number (求N!的位数)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1018


Big Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25856    Accepted Submission(s): 11743

Problem Description
In many applications very large integers numbers are required. Some of these applications are using keys for secure transmission of data, encryption, etc. In this problem you are given a number, you have to determine the number of digits in the factorial of the number.
 
Input
Input consists of several lines of integer numbers. The first line contains an integer n, which is the number of cases to be tested, followed by n lines, one integer 1 ≤ n ≤ 10 7 on each line.
 
Output
The output contains the number of digits in the factorial of the integers appearing in the input.
 
Sample Input
      
      
2 10 20
 
Sample Output
      
      
7 19
 


求n!的位数,转化成求log10(n!)的问题;

1,直接求解,log10(n!)=log10(1)+log10(2)+...+log10(n)

2,利用斯特林公式 : log10(n!)=1.0/2*log10(2*pi*n)+n*log10(n/e)

3,打表


不用公式的 :900ms+;

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

int main()
{
    int n;
    scanf("%d",&n);
    while(n--)
    {
        int a;
        scanf("%d",&a);
        double sum = 0 ;
        int i;
        for(i=1;i<=a;i++)
            sum += log10(i);
        printf("%d\n",(int)(sum+1));
    }
    return 0;
}

用公式求的:0ms;

#include <stdio.h>
#include <math.h>
#define E 2.71828182845904523536028747135266250
#define PI 3.141592654

int main()
{

    int n;
    scanf("%d",&n);
    while(n--)
    {
        int a;
        scanf("%d",&a);
        double sum =(double) 0.5*log10(2*PI*a)+a*log10(a*1.0/E);
        printf("%d\n",(int)(sum+1));
    }
    return 0;
}


打表:

#include<stdio.h>
int main()
{
	int n,m,i,bit=1;
	double num=0;
	scanf("%d",&n);
	while(n--)
	{
		bit=1,num=1;
		scanf("%d",&m);
		for(i=2;i<=m;i++)
		{//num只是转化为整数部分有1位,其余的都在小数部分,防止方法溢出
			num*=i;
			if(num<10){continue;}
			if(num<100){num/=10;bit+=1;continue;}
			if(num<1000){num/=100;bit+=2;continue;}
			if(num<10000){num/=1000;bit+=3;continue;}
			if(num<100000){num/=10000;bit+=4;continue;}
			if(num<1000000){num/=100000;bit+=5;continue;}
			if(num<10000000){num/=1000000;bit+=6;continue;}
			if(num<100000000){num/=10000000;bit+=7;continue;}
		}
		printf("%d\n",bit);
	}
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值