Fib(n)=Fib(n-1)+Fib(n-2);Fib1=Fib2=1;
递归
public static int fibonacci(int n){
if (n == 1 || n == 2) {
return 1;
}
if (n > 2) {
return fibonacci(n - 1) + fibonacci(n - 2);
}
return -1;
}
数值传递
public static long fibonacci2(int n) {
if (n < 1) {
return -1;
}
if (n ==1 || n == 2) {
return 1;
}
long a =1l, b= 1l, c =0l; //防止溢出
for (int i = 0; i < n - 2; i++) {
c = a + b; //a代表n-2 b代表n-1
a = b; //a代表下一次中的n-2
b = c; //b代表下一次中的n-1
}
return c;
}