object Main extends App { def Fibonacci1(n: Int): Int = { if (n == 1 || n == 0) 1 else Fibonacci1(n - 1) + Fibonacci1(n - 2) } def Fibonacci2(n: Int): Int = { if (n == 1 || n == 0) 1 else { var lop = 2 var sum = 0 while (lop > 0) { sum = sum + Fibonacci2(n - lop) lop = lop - 1 } sum } } val t1 = System.nanoTime(); println(Fibonacci1(10)) val t2 = System.nanoTime(); println(Fibonacci2(10)) val t3 = System.nanoTime(); println(t2 - t1) println(t3 - t2) }
输出为:
89 89 43777662 29317
object Main extends App { def sumInts1(a:Int,b:Int,sum:Int):Int={ if(a>b) sum else sumInts1(a+1,b,sum+a) } def sumInts2(a:Int,b:Int):Int={ if(a>b) 0 else a+sumInts2(a+1,b) } val t1 = System.nanoTime(); println(sumInts1(10,100,0)) val t2 = System.nanoTime(); println(sumInts2(10,100)) val t3 = System.nanoTime(); println(t2 - t1) println(t3 - t2) }
输出为:
5005 5005 45856323 44255
待整理
时间: 2024-10-11 21:20:01