码迷,mamicode.com
首页 > 其他好文 > 详细

scala之尾递归

时间:2015-09-22 18:13:45      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

 

待整理

 

scala之尾递归

标签:

原文地址:http://www.cnblogs.com/wzyj/p/4829297.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!