递归和非递归实现斐波那契序列

package com.edgar;

public class TestFibonacci {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		long start1 = System.currentTimeMillis();
		System.out.println(fibonacci(40));
		long end1 = System.currentTimeMillis();
		long start2 = System.currentTimeMillis(); 
		System.out.println(fibonacci2(40));
		long end2 = System.currentTimeMillis();
		
		System.out.println(end1-start1);
		System.out.println(end2-start2);
	}
	
	public static int fibonacci(int n){
		
		if(n ==0){
			return 0;
		}
		else if(n ==1 ||n==2){
			return 1;
		}
		else{
			return fibonacci(n-1)+ fibonacci(n-2);
		}
	}
	//  1 1  2  3  5  8 13
	//  1 2  3  4  5  6
	public static int fibonacci2(int n){
		if(n ==0){
			return 0;
		}
		else if(n ==1 ||n==2){
			return 1;
		}
		else{
			int temp1 =  1;
			int temp2 = 1;
			int temp = 0;
			for(int i=3;i<=n;i++){
				temp =  temp1+  temp2;			
			    temp2 = temp1;
			    temp1 = temp;
			}
			
			return temp;
		}
	}

}

猜你喜欢

转载自edgar108.iteye.com/blog/2274719