Java大整數(shù)階乘 不會溢出
package test1;
import java.util.Random;
import java.math.*;
import java.util.Scanner;
public class ceshi1 {
? ? public static void main(String[] args) {
? ?
? ? ?
? ?
? ? ? ? ? ? Scanner input = new Scanner(System.in);
? ? ? ? ? ? System.out.print("請輸入一個數(shù) ");
? ? ? ? ? ? int num = input.nextShort();
? ? ? ? ? ? System.out.println(num + "! is : " + factorial(num));
? ? ? ? }
? ? ?
? ? ? ? public static BigInteger factorial(long n) {
? ? ? ? ? ? BigInteger result = BigInteger.ONE;
? ? ? ? ? ? for(int i = 1; i <= n; i++) {
? ? ? ? ? ? ? ? result = result.multiply(new BigInteger( i + ""));
? ? ? ? ? ? ? ? //將數(shù)字轉(zhuǎn)換為字符串,防止溢出
? ? ? ? ? ? }
? ? ? ? ? ? return result;
? ? ? ? }
? ? }
標(biāo)簽: