Tag: 尾递归

Kotlin递归

fun fact(x: Int): Int{ tailrec fun factTail(y: Int, z: Int): Int{ if (y == 0) return z else return factTail(y – 1, y * z) } return factTail(x, 1) } 有人请向我解释一下上面的递归函数在kotlin中是如何工作的?

Kotlin – 为什么这个函数不适合尾递归?

下面的例子中的函数send()递归地调用它自己: internal inner class RouteSender( val features: List<Feature>, val exchange: GrpcUniExchange<Point, RouteSummary> ) { var result: AsyncResult<RouteSummary>? = null // Set in stub for recordRoute. fun send(numPoints: Int) { result?.let { // RPC completed or err'd before sending completed. // Sending further requests won't error, but they will be thrown away. return } val index […]

当使用Java / Kotlin进行编程时,建议使用尾递归还是迭代版本? 性能有什么不同?

我试图了解编程中的良好实践,我坚持这个问题。 我知道,在Java中,递归函数可能是“一个痛苦的屁股”(有时),我尽可能实现该函数的尾部版本。 这是值得打扰,还是应该以旧式的方式? 这两个函数(在Kotlin中)有什么区别: tailrec fun tail_fibonacci(n : BigInteger, fib1 : BigInteger = BigInteger.ZERO , fib2 : BigInteger = BigInteger.ONE) : BigInteger { return when(n){ BigInteger.ZERO -> fib1 else -> tail_fibonacci(n.minus(BigInteger.ONE),fib1.plus(fib2),fib1) } } fun iterative_fibonacci(n: BigInteger) : BigInteger { var count : BigInteger = BigInteger.ONE var a : BigInteger = BigInteger.ZERO var b : BigInteger […]

如何避免Java / Kotlin / IntelliJ IDEA中的StackOverFlow错误?

我想做一个BigInteger的阶乘(在Kotlin中)。 有了尾递归,当我尝试做9000时,会出现StackOverFlow错误! 。 有了一个非递归函数,我可以做到这一点…但我很好奇如何避免这种错误。 这是我的代码: import java.math.BigInteger fun tail_recursion_factorial(n: BigInteger, factorialOfN: BigInteger = BigInteger.valueOf(2)): BigInteger { return when(n){ BigInteger.ONE -> BigInteger.ONE BigInteger.valueOf(2) -> factorialOfN else -> tail_recursion_factorial(n.minus(BigInteger.ONE), n.times(factorialOfN)) } } fun non_recursive_factorial(n: BigInteger): BigInteger{ var i: BigInteger = BigInteger.ONE var factorial: BigInteger = BigInteger.ONE while (i<=n){ factorial = factorial.times(i) i = i.plus(BigInteger.ONE) } return factorial […]

Kotlin:相互递归函数的尾递归

假设我写这样的代码: tailrec fun odd(n: Int): Boolean = if (n == 0) false else even(n – 1) tailrec fun even(n: Int): Boolean = if (n == 0) true else odd(n – 1) fun main(args:Array<String>) { // 🙁 java.lang.StackOverflowError System.out.println(even(99999)) } 我如何让Kotlin优化这些相互递归的函数,这样我就可以运行main而不抛出StackOverflowError了? tailrec关键字适用于单一函数递归,但没有更复杂的。 我也看到一个警告,就是在使用tailrec关键字的地方找不到tail-calls。 编译器也许这太难了?