Java 1000阶乘计算

1000的阶乘使用BigInteger

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

public class Main {
     
	public static void main(String[] args) {
     
		Scanner sc = new Scanner(System.in);
		//获得n
		int num = sc.nextInt();
		
		//初始值
		int preanswer = 1;
		//转为字符串
		String s = String.valueOf(preanswer);
		//转为BigInteger
		BigInteger answer = new BigInteger(s);
		
		//n的范围小于等于1000
		if (num <= 1000) {
     
			//循环求阶乘
			for (int i = 1; i <= num; i++) {
     
				//i转为字符串
				String valuei = String.valueOf(i);
				//i转为BigInteger
				BigInteger value = new BigInteger(valuei);
				
				//同类型相乘
				answer = value.multiply(answer);
			}
			
		}
		System.out.println(answer);
		sc.close();

	}
}

你可能感兴趣的:(Java,字符串,java)