Java高精度学习第二弹——求N!

  继续学习Java高精度,今天写的是求N!。

 

  首先附上源代码:

 

  

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

public class Main 
{
    public static void main(String []args)
    {
        Scanner cin = new Scanner(System.in);
        BigInteger a,n,i;
        while(cin.hasNext())
        {
            a = cin.nextBigInteger();
            n = BigInteger.ONE;
            for(i=BigInteger.ONE; i.compareTo(a)<=0;i=i.add(BigInteger.ONE))
                n = n.multiply(i);
            System.out.println(n);
        }
    }
}
    

 

  有几个需要注意的地方:

 

  1.BigInteger.ONE 这个是用来获取BigInteger的1值的,同样的还有,BigInteger.TEN(获取10),BigInteger.ZERO(获取0)。

 

  2.compareTo。这个函数可以很简单的去理解。例如上面的 i.compareTo(a) 既是返回 i - a 的值(如果是字符串的话就类似C里面的strcmp了)。

posted @ 2014-09-01 20:25  猫御龙  阅读(234)  评论(0编辑  收藏  举报