Fibonacci递归非递归方法

public class FibonacciTest {
    public static void main(String args[]){
    	long start = System.nanoTime();
    	System.out.println(fibonacci(30));
    	long end = System.nanoTime();
    	System.out.println("Time " + (end - start));
    	System.out.println(fibonacci1(30));
    	long end1 = System.nanoTime();
    	System.out.println("Time " + (end1 - end));
    }
    
    public static int fibonacci(int n){
    	//System.out.println(n);
    	int result = 0;
    	if(n == 0){
    		result = 0;
    	} else if(n == 1) {
    		result = 1;
    	} else {
    		return fibonacci(n - 1) + fibonacci(n - 2);
    	}
    	return result;
    }
    
    public static int fibonacci1(int n){
    	int result = 0;
    	if( n == 0){
    		return 0;
    	} else if(n == 1){
    		return 1;
    	} else {
    		int first = 0;
    		int second = 1;
    		for(int i = 2; i <= n; i++){
    			result = first + second;
    			first = second;
    			second = result;
    		}
    	}
    	return result;
    }
}


你可能感兴趣的:(Fibonacci递归非递归方法)