HDOJ 1018 Big Number

解题过程:

这个题目一看标题我首先想到的就是使用java的大数类解题,可是超时了

然后通过查阅资料知道了一个斯特林公式:res=(long)( (log10(sqrt(4.0*acos(0.0)*n)) + n*(log10(n)-log10(exp(1.0)))) + 1 );

也就是说一个正整数的位数,等于 (int)log10(a)+1        

*了解斯特林公式详细内容:点击打开链接


题目链接:点击打开链接


先跟大家分享一下我的垃圾超时代码:

import java.math.BigInteger;
import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        while(n-->0){
            BigInteger a=sc.nextBigInteger();
            BigInteger b=BigInteger.ONE;
            while(!a.equals(BigInteger.ZERO)){
                b=b.multiply(a);
                a=a.subtract(BigInteger.ONE);
            }
            int sum=0;
            while(!b.equals(BigInteger.ZERO)){
                sum++;
                b=b.divide(BigInteger.TEN);
            }
            System.out.println(sum);
        }
    }
}

下面是利用斯特林公式解决的代码:

import java.util.Scanner;

//正整数a的位数等于(int)log10(a) + 1,
public class P1018 {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		while(n-->0){
			double sum=0;//sum必须声明为double型
			int m=sc.nextInt();
			for(int i=1;i<=m;i++){
				sum+=Math.log10(i);
			}
			System.out.println((int)sum+1);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值