使用递归对ktolin进行阶乘的Stackoverflow错误

这是我的代码这使输出控制台上的堆栈溢出错误30次

fun main(args:Array<String>){ var no:Int=Integer.parseInt(readLine())//read input from user and convert to Integer var ans:Int=calculateFact(no) //call function and store to ans variable println("Factorial of "+no+" is "+ans) //print result } fun calculateFact(no:Int):Int //function for recursion { if(no==0) { return 1 } return (no*calculateFact(no)) } 

我不知道什么是错误解决PLZ

你应该回来

 no*calculateFact(no - 1) 

 no*calculateFact(no) 

否则递归永远不会结束。

除了已经指出的递归错误之外,值得一提的是,从13! ,你的方法仍然只能正确工作于12以下的数字13! 大于可以存储在Int的最大值。 因此,对于数字13和以上,由于溢出,你基本上会得到“随机”的结果。

如果您只是使用BigInteger ,它将工作,直到调用堆栈变得太深,并导致堆栈溢出,这发生在我的机器上大约8000

 fun calculateFact(no: BigInteger): BigInteger { if (no == BigInteger.ZERO) { return BigInteger.ONE } return (no * calculateFact(no - BigInteger.ONE)) } fun main(args: Array<String>) { val no: BigInteger = BigInteger(readLine()) val ans: BigInteger = calculateFact(no) println("Factorial of $no is $ans") } 

如果你想处理大于这个数字的数字,你可以使用tailrec函数(这个特定的解决方案来自这篇文章):

 tailrec fun calculateFact(acc: BigInteger, n: BigInteger): BigInteger { if (n == BigInteger.ZERO) { return acc } return calculateFact(n * acc, n - BigInteger.ONE) } fun calculateFact(n: BigInteger) : BigInteger { return calculateFact(BigInteger.ONE, n) } fun main(args: Array<String>) { val n: BigInteger = BigInteger(readLine()) val ans: BigInteger = calculateFact(n) println("Factorial of $n is $ans") } 

这对于数字高达几十万的数字来说是有效的,你用这个数字的问题将成为运行时间而不是内存限制。

  fun main(args:Array<String>) { var no:Int = Integer.parseInt(readLine()) //read input from user and convert to Integer var ans:Int=calculateFact(no) //call function and store to ans variable println("Factorial of "+no+" is "+ans) //print result } fun calculateFact(no:Int):Int { //function for recursion if(no==0) { return 1 } return (no*calculateFact(no - 1)) // you forgot to decrease the no here. } 

如果你没有减少否则它会一直调用calculateFact()方法。 请检查代码,它会工作。