1. 程式人生 > >用for迴圈\遞迴寫斐波那契數列

用for迴圈\遞迴寫斐波那契數列

for迴圈

public class Test{
	public static int fib(int n){
	if(n == 1 || n == 2){
		return 1;
		}else{
		int a = 1;
		int b = 1;
		int s = 0;
		for(int i = 2;i<n;i++){
			s = a + b;
			a = b;
			b = s;
			}
			return s;
		}
	}
	public static void main (String[] args){
	int result = fib(5);
	System.out.println(result);
	}
}

遞迴

public class Test2{
	public static int fib(int n){
	if(n == 1 || n == 2){
		return 1;
		}else{
		return fib(n-1)+fib(n-2);
		}
	}
	public static void main (String[] args){
	int result = fib(3);
	System.out.println(result);
	}
}