BigInteger

BigInteger超大整数运算

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

public class Test1JieCheng {
    public static void main(String[] args) {
        //66 ->0    21 ->-4249290049419214848
        System.out.print("输入整数求阶乘:");
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        //n传递到f()方法求n的阶乘,得到方法的返回值存到变量r
        String r=f(n);
        System.out.println("阶乘结果为"+r);
        sc.close();
    }

    private static String f(int n) {
        /**
         * 假设n是5
         * r=5
         * i=4 r=r*i
         * i=3 r=r*i
         * i=2 r=r*i
         * i=1 r=r*i
         */
        BigInteger r=BigInteger.valueOf(n);
        for(int i=n-1;i>=1;i--)
        {
             r=r.multiply(BigInteger.valueOf(i)); 
        }
        return r.toString();
    }
}

运行结果

输入整数求阶乘:60
阶乘结果为832098711274139014427634118322336438075417260636124595244927769640960000000
0000000

你可能感兴趣的:(BigInteger)