解题过程:
这个题目一看标题我首先想到的就是使用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);
}
}
}