欢迎光临散文网 会员登陆 & 注册

Java大整数阶乘 不会溢出

2022-10-10 10:49 作者:酸奶公园  | 我要投稿

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("请输入一个数 ");

            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 + ""));

                //将数字转换为字符串,防止溢出

            }

            return result;

        }

    }


Java大整数阶乘 不会溢出的评论 (共 条)

分享到微博请遵守国家法律