繁体   English   中英

Java:如何使用数组解决大型阶乘?

[英]Java: How to solve a large factorial using arrays?

我可以在网上找到的所有解决方案都使用BigInteger但我必须使用数组来解决这个问题。

我只是一个初学者,我什至把它带到了我的计算机科学俱乐部,甚至无法弄清楚。

每次输入大于31的数字时,输出始终为零。

此外,当我输入一个大于12的数字时,输出总是不正确的。

例如, fact(13)在它应该返回1932053504时返回6227020800

这是我到目前为止所拥有的:

import java.util.Scanner;

class Fact
{
    public static void main(String[] args)
    {
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter the number you wish to factorial");
        int x = kb.nextInt();
        System.out.println(fact(x));
    }

    public static int fact(int x)
    {
        int[] a = new int[x];

        int product = 1;

        for(int i = 0; i < a.length; i++)
        {
            a[i] = x;
            x--;
        }

        for(int i = 0; i < a.length; i++)
        {
            product = product * a[i];
        }

        return product;
    }
}

最大值使大数变得可怕

可悲的是,由于integers 和 longs最大值,您无法大于

对于多头:

2^63 - 1

9223372036854775807

9 quintillion 223 quadrillion 372 trillion 36 billion 854 million 775 thousand 807

对于整数:

2^31 - 1

2147483647

2 billion 147 million 483 thousand 647

(我把写的名字放进去显示尺寸)

在计算过程中的任何时间点,您都会查看这些“最大值”,您将溢出变量,导致它的行为与您预期的不同,有时会导致形成奇怪的零。

甚至BigInteger也有这个问题,尽管它可以上升到比longsints高得多的数字,这就是为什么它们与生成大量数字(如阶乘)的方法一起使用的原因。

你似乎想避免使用BigInteger ,只有使用primatives这么long将成为最大的数据类型,您可以使用。

即使您将所有内容都转换为long (当然除了数组迭代器),您也只能准确计算最多 20 的阶乘。 任何超过的东西都会溢出变量。 这是因为21! 超过多头的“最大值”。

简而言之,您需要使用BigInteger或创建自己的类来计算大于 20 的数字的阶乘。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM