我有这个递归函数:
def series(n: Int): Double =
{
if(n == 1)
return 3
if (n == 2)
return 5
Math.pow(-1, n) * 5 * series(n - 1) + Math.pow(-1, n-1) * 3 * series(n - 2)
}
我必须把它变成尾递归的。我不知道如何执行此操作 谢谢
答案 0 :(得分:3)
这个系列的尾递归版本是可能的。诀窍是将current
和previous
结果保留在函数参数中。
fooSeries
遵循自下而上的方法,首先将n = 1
和n = 2
结果作为输入,然后根据较小的n
计算较大的n
。
注意helper
将counter
的初始值设为3,初始current
为5
,previous
为3
def fooSeries(n: Int): Double = {
@scala.annotation.tailrec
def helper(counter: Int, current: Double, previous: Double): Double = {
n match {
case 1 => previous
case 2 => current
case _ =>
if (counter > n) current
else
helper(counter + 1, Math.pow(-1, counter) * 5 * current + Math.pow(-1, counter - 1) * 3 * previous, current)
}
}
helper(3, 5, 3)
}
Scala REPL
scala> fooSeries(1)
res46: Double = 3.0
scala> series(1)
res47: Double = 3.0
scala> fooSeries(2)
res48: Double = 5.0
scala> series(2)
res49: Double = 5.0
scala> fooSeries(3)
res50: Double = -16.0
scala> series(3)
res51: Double = -16.0
scala> fooSeries(4)
res52: Double = -95.0
scala> series(4)
res53: Double = -95.0
scala> fooSeries(5)
res54: Double = 427.0
scala> series(5)
res55: Double = 427.0
scala> fooSeries(6)
res56: Double = 2420.0
scala> series(6)
res57: Double = 2420.0
scala> fooSeries(11)
res58: Double = -6955321.0
scala> series(11)
res59: Double = -6955321.0