巨型数的阶乘不叠加,也不返回结果JAVA

问题描述

编辑:我专门尝试将这个问题看作是尾递归函数。不能使用迭代解决方案。

我正在尝试组装一个阶乘计算器,只要结果为

我遇到了一个问题,即使我不认为我已经通过了堆栈的容量,阶乘的结果也只能作为输出打印出来。它对于〜8000以下的值似乎始终如一地工作(估计,每次执行都不相同..?),但是对于〜8000和〜31400之间的值断断续续地不打印任何内容(随着数字的增加,空白的回报越来越频繁..?)

一次执行时,我得到13947作为堆栈溢出之前处理的最高整数,而另一次是在12000年代。我认为至少可以在执行过程中归因于可变堆栈状态(因为每次都要获取用户输入并每次都进行更改),但是我是一个相当新的程序员,我对某些事情的理论理解可能有些不稳定,所以我不确定。

有人知道为什么代码对于某些较高的值可能什么也不打印吗?我最好的猜测是

  1. 该结果大于2 ^ 2147483647,因此无法将其存储为BigInteger,(但这不能解释间歇性...)
  2. 计算花费了太长时间,并且循环在计算完成之前一直在继续(解释了间歇性,但似乎是不可能的)
  3. 即使计算正在进行中,我的Eclipse IDE仍然不能很好地将那么多的数字打印到屏幕上。

我不确定如何验证上述猜测。我已经了解了BigInteger的局限性以及Eclipse的局限性,但是没有找到可以与我的任务进行比较的答案。

这是代码:

render

以下是一些示例输出:

@testing-library/react

解决方法

阶乘方法可以很好地工作,但是当超出堆栈大小时,确实会得到相对一致的溢出。对我来说,这大约是9000-10000个电话。请记住,对于每个递归,n上的大值!在static int count; public static void main(String[] args) { count = 0; int n = 20000; BigInteger f = fact(n); } static BigInteger factoriel(BigInteger n,BigInteger m) { // calcule le factoriel pour n'importe quel entier. if (n.compareTo(BigInteger.ONE) < 1) return m; // théoriquement valide pour tout entier dont n! < 2^2147483647,mais count++; BigInteger f = null; try { f = factoriel(n.subtract(BigInteger.ONE),n.multiply(m));// limité par la capacité de la pile (à cause de la récursion). } catch(StackOverflowError e) { System.out.println(count); } return f; } static BigInteger fact(int n) { // convertir l'entree en BigInteger et lancer la recursion if (n < 0) { return BigInteger.valueOf(-1); } BigInteger b = BigInteger.valueOf(n); return factoriel(b,BigInteger.ONE); } 对象中占用了大量空间。因此,SO发生在堆栈跟踪的早期。

我建议您执行的操作是将值打印到文件中,而不是打印到IDE的控制台中。这样,您可以确定它是IDE(可能是)还是程序(可能不是)。我知道对于Eclipse,必须为控制台设置一个内部缓冲区大小,以及一个最大行大小。

s: five - letter string
psn: an int between 0 and 4
return: result the character that is at position psn in s

def index_string(s,psn):
   position = psn -1
   return s[position]
,

简单

public static BigInteger find(BigInteger B)
    {
        BigInteger res=BigInteger.ONE;
        int b=B.intValue();
        for(int i=1;i<=b;i++)
        {
            res=res.multiply(new BigInteger(new Integer(i).toString()));
            //System.out.println(res);
        }
        return res;
    }

,

如果您想递归方式

public static BigInteger find(BigInteger B)
    {
        BigInteger res=BigInteger.ONE;
        if(B.compareTo(BigInteger.ZERO)==0)
            res=BigInteger.ONE;
        else
        {
            res=B.multiply(find(B.subtract(new BigInteger(new Integer(1).toString()))));
            //System.out.println(res);
        }
        return res;
    }

29.9255秒 07:47:45 20/11/02

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...