高精度问题——Java大数类~系列2——整数乘法 hdu 1042
高精度问题(2)——整数乘法
题目的意思很简单,就是求N的阶乘。但是N很大,所以要用高精度,直接用Java大数类实现。
hdu 1042 原题如下:
N!
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 44011 Accepted Submission(s): 12392
Problem Description
Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!
Input
One N in one line, process to the end of file.
Output
For each N, output N! in one line.
Sample Input
1
2
3
Sample Output
1
2
6
代码如下(有详细注释):
1 //2.大数乘法 ~java~ hdu 1042 2 import java.math.BigInteger; 3 import java.util.Scanner; 4 import java.io.*; 5 6 public class Main 7 { 8 public static void main(String[] args) 9 { 10 Scanner cin = new Scanner(System.in); 11 BigInteger ans, i, t; //全部定义为大数,统一起见,但是比较繁琐 12 BigInteger one = new BigInteger("1"); 13 while(cin.hasNextBigInteger()) 14 { 15 t=cin.nextBigInteger(); 16 i=new BigInteger("1"); //初始值为1(大数的1) 17 ans=new BigInteger("1"); 18 int cmp=i.compareTo(t); 19 while(cmp<=0) //相当于i<=t 20 { 21 ans=ans.multiply(i); 22 i=i.add(one); //确保数据类型一致 23 cmp=i.compareTo(t); 24 } 25 /*while(i<=t) 26 { 27 ans=ans.multiply(t); 28 i++; 29 }*/ //这样写是错的,i,t均定义为大数,里面不能直接使用<=,要用compareTo 30 System.out.println(ans); 31 } 32 } 33 }
另一种写法(较精炼,但耗时较多):
1 //~java~ hdu 1042 2 //1000ms 3 import java.math.BigInteger; 4 import java.util.*; 5 import java.io.*; 6 7 public class Main 8 { 9 public static void main(String[] args) 10 { 11 Scanner cin = new Scanner(System.in); 12 int t; //临时变量定义为整型,到计算中再转换,代码精炼 13 while(cin.hasNextBigInteger()) 14 { 15 BigInteger ans=BigInteger.ONE; 16 t=cin.nextInt(); 17 for(int i=1;i<=t;i++) 18 ans=ans.multiply(BigInteger.valueOf(i)); 19 System.out.println(ans); 20 } 21 } 22 }
2013-8-11
晴
浙公网安备 33010602011771号