斐波那契数列用JAVA实现

import java.util.Scanner;


public class Test {
	public static void main(String[] args) {
	
		int r = test(7);
		int rs = test2(7);
		System.out.println("==="+r+"========"+rs);
		
		
	}
	public static int test(int n){//递归的方式
		// 1 1 2 3 5 8 13 21 34 55 89
//		该算法利用递归的方式计算第几项的值
		if(n==1 || n==2){
			return 1;
		}
			return test(n-1) + test(n-2);
	}
	
	public static int test2(int n){//非递归的方式
		int first = 1;
		int second = 1;
		int  result = 0 ;
		//result用来记录结果,first用来记录计算项的前面的前面的数,second用来记录当前计算项的前一项
		if(n==1 || n==2){
			return 1;
		}
		for (int i = 1; i < n - 1; i++) {
			result = first + second;
			first = second;
			second =result;
		}
		
		return result;
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/BearDie/article/details/82818593