java基础练习01--查询Fibonacci数列第n个数

package cn.drc.fibonacci;
/**
 * Fibonacci数列是这样的一个数列:
 * 	1 1 2 3 5 8 13 21 ...
 * 求出这个数列第 n 个数是多少
 * @author drc
 *
 */
public class FibonacciDemo {
	public static void main(String[] args) {
                // 测试结果
		System.out.println(getNumberInSequence1(5));
		System.out.println("=====================");
		System.out.println(getNumberInSequence2(8));
	}
	/**
	 * 通过递归的方式查询fibonacci数列第index个数
	 * @param index 位置
	 * @return 数
	 */
	public static int getNumberInSequence1(int index) {
		if(index==1 || index==2) {
			return 1;
		}
		return getNumberInSequence1(index-1) + getNumberInSequence1(index-2);
	}
	/**
	 * 通过循环的方式查询fibonacci数列第index个数
	 * @param index 位置
	 * @return 数
	 */
	public static int getNumberInSequence2(int index) {
		if(index==1 || index==2) {
			return 1;
		}
		
		int before_1 = 1; // 目标位置前两项的第一项
		int before_2 = 1; // 目标位置前两项的第二项
		int target = 0; // 目标项
		for(int x=3; x<=index; x++) { // 从第三项开始计算,直到目标索引的位置
			target = before_1 + before_2; // 前两项的和为目标项的数值
			before_1 = before_2;
			before_2 = target;
		}
		return target;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40650532/article/details/84618701