阶乘法不能很好地运作!

use*_*221 6 java math factorial

嗨这是一个阶乘方法,但它在控制台打印0请帮助我谢谢

public class Demo {

    public static void main(String[] args) {
        Demo obj = new Demo();
        System.out.println(obj.factorial(500));
    }

    public int factorial(int n) {
        int fact = 1;

        for (int i = 2; i <= n; i++) {
            fact= fact*i;
        }
        return fact;
    }
Run Code Online (Sandbox Code Playgroud)

编辑:将返回无限!

public class Demo {

    public static void main(String[] args) {
        Demo obj = new Demo();
        System.out.println(obj.factorial(500));
    }

    public double  factorial(long n) {
       double fact = 1;

        for (int i = 2; i <= n; i++) {
            fact= fact*i;
        }
        return fact;
    }
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 18

因为500!等于1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000你不能适应它int(范围最大2147483647).

  • 使用int你只能存储12!.
  • 使用long你将起床20!
  • 使用double你将起床170!.

这是一个解决方案BigInteger:

public static BigInteger factorial(int i) {
    BigInteger n = BigInteger.valueOf(i);
    while (--i > 0)
        n = n.multiply(BigInteger.valueOf(i));
    return n;
}
Run Code Online (Sandbox Code Playgroud)

  • 这将是一个小的改进,因为它只优化了非常小的输入值的方法. (3认同)