斐波那契数列,F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)
硬件: I3 Cpu + 8G Ram
1.用C#递归计算:
1 static void Main(string[] args) 2 { 3 int n = 40; 4 Stopwatch watch = new Stopwatch(); 5 watch.Start(); 6 int num = RecursionFibonacci(n); 7 watch.Stop(); 8 Console.WriteLine("n="+n); 9 Console.WriteLine("num=" + num); 10 Console.WriteLine("time=" + watch.ElapsedMilliseconds+"ms"); 11 } 12 static int RecursionFibonacci(int n) 13 { 14 if (n < 1) 15 return 0; 16 if (n == 1) 17 return 1; 18 return RecursionFibonacci(n - 1) + RecursionFibonacci(n - 2); 19 }
2.用java递归计算:
1 package com.example.fibonacci; 2 3 /** 4 * Created by Administrator on 3/22/2014. 5 */ 6 public class Fibonacci { 7 public static void main(String[] args){ 8 int n=40; 9 long startTime=System.currentTimeMillis(); 10 int num=RecursionFibonacci(n); 11 long endTime=System.currentTimeMillis(); 12 System.out.println("n="+n); 13 System.out.println("num="+num); 14 System.out.println("time="+(endTime-startTime)+"ms"); 15 } 16 public static int RecursionFibonacci(int n){ 17 if(n<1) 18 return 0; 19 if(n==1) 20 return 1; 21 return RecursionFibonacci(n-1)+RecursionFibonacci(n-2); 22 } 23 }
c#怎么就用了2238ms呢,落后的原因是什么?
3.用javascript递归计算:
1 <div> 2 Fibonacci 3 <input type="text" id="txtNum" value="40"/> 4 <input type='button' id='btnFibonacci' value='Recursion' onclick="Do()" /> 5 </div> 6 <script type="text/javascript"> 7 function RecursionFibonacci(n) { 8 if (n < 1) { 9 return 0; 10 } 11 if (n == 1) { 12 return 1; 13 } 14 var num = RecursionFibonacci(n - 1) + RecursionFibonacci(n - 2); 15 return num; 16 } 17 function Do () { 18 var n = document.getElementById("txtNum").value; 19 var beginDate = new Date(); 20 var num = RecursionFibonacci(n); 21 var time = new Date() - beginDate; 22 alert("n=" + n + "; num=" + num + "; time=" +time+"ms"); 23 } 24 </script>