数学基础:
1,1,2,3,5,8,13 and so on
前两位特殊,其余各位符合F(n) = F(n-1)+F(n-2);
首先想到递归,如下:
public static int fibonacci(int n) {
if (n <= 0) {
return -1;
} else if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
private void testFibonacci(){
for (int i = 0; i < 10; i++) {
System.out.println("fibonacci i="+i+"--value="+TestAlgorithms.fibonacci(i));
}
}
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=0--value=-1
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=1--value=1
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=2--value=1
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=3--value=2
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=4--value=3
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=5--value=5
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=6--value=8
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=7--value=13
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=8--value=21
12-12 15:03:15.861 29816-29816/com.example.bxh.sayhello I/System.out: fibonacci i=9--value=34
但有同学说:此法没有保存前面的值,每次计算时都要重复计算前面的值。所以有人提出使用‘迭代’,关于迭代我没(首)啥(次)说(听)的(说)了(衰!).可以百度一下迭代与递归之间的区别。
public static int fibonacci02(int n) {
if (n <= 0) {
return -1;
} else if (n == 1 || n == 2) {
return 1;
} else {
int start = 3;
int f = 1;//第1位
int b = 1;//第2位
while (start++ <= n) {
//每次循环都把b和f右移一位,最终b就是我们要的值
//当n=3时,只需要执行1次
//当n=4时,移动1次以后要再移动1次
//当n=5时,在上面的基础上再移动1次
b = b + f;//b 变成它右边那一位
f = b - f;//f 变成b之前的值
}
return b;
}
}
结果与第一种方法相同。