1 package com.atguigu.function
2
3 object Recursion {
4 def main(args: Array[String]): Unit = {
5 // 阶乘
6 // 递归算法
7 // 1) 方法调用自身
8 // 2) 方法必须要有跳出的逻辑
9 // 3) 方法调用自身时,传递的参数应该有规律
10 // 4) scala 中的递归必须声明函数返回值类型
11 println("递归 :"+test(5))
12 println("尾递归:"+tailFact(5))
13 }
14 //
15 def test(i : Int) : Int = {
16 if (i == 1) {
17 1 //退出基准
18 } else {
19 i * test(i - 1)
20 }
21 }
22
23 //尾递归调用
24 def tailFact(n:Int ):Int = {
25 def loop(n: Int, currRes: Int): Int = {
26 if (n == 0) {
27 return currRes
28 }
29 loop(n - 1, currRes * n)
30 }
31 loop(n, 1)
32 }
33
34 }