HODJ Big Number(java 阶乘)

来源:互联网 发布:获取百度指数的源数据 编辑:程序博客网 时间:2024/06/06 03:08

Big Number

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


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 ≤ 107 on each line.
 

Output
The output contains the number of digits in the factorial of the integers appearing in the input.
 

Sample Input
21020
 

Sample Output
719
超时代码:以为用大数可以解决,结果发现求千万数量级的阶乘内存也无法受得了
import java.math.BigInteger;import java.util.Scanner;public class Main {            public static void main(String[] args) {                Scanner in = new Scanner(System.in);        int n = in.nextInt();        while(n-->0){            String str = in.next();            BigInteger number = new BigInteger(str);            BigInteger sum = BigInteger.ONE;            while(number.intValue()>0){                                sum = sum.multiply(number);                number = number.subtract(BigInteger.ONE);                            }                        System.out.println(sum.toString().length());                    }            }}

AC代码1:利用数学中对数公式可以求解出,lg(N!)=lg(1)+lg(2)+…+lg(N)
import java.util.Scanner;public class Main {        public static void main(String[] args) {                Scanner in = new Scanner(System.in);        int n = in.nextInt();        while(n-->0){            double d = in.nextDouble();            double sum = 0;            for(int i=1; i<=d; i++){                    sum += Math.log10(i);            }                System.out.println((int)sum+1);                    }            }}

AC代码2:采用斯特林公式计算能够在时间上快速解决
链接:http://baike.baidu.com/view/4113061.htm?fr=aladdin
import java.util.Scanner;public class Main {        public static void main(String[] args) {                Scanner in = new Scanner(System.in);        int n = in.nextInt();        while(n-->0){            int number = in.nextInt();            double sum1 = Math.log10(Math.sqrt(2*Math.PI*number));            double sum2 = number*Math.log10(number/Math.E);            System.out.println((int)(sum1+sum2+1));                    }            }}






0 0
原创粉丝点击