简要描述:
斐波纳契数列,又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、……在数学上,以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)
代码实现:
import java.util.Scanner;
public class Test{
public static int Fibo1(int n){
//使用数组
int[] a = new int[n];
a[0]=a[1]=1;
for(int t = 2;t<n;t++)
a[t]=a[t-1]+a[t-2];
return a[n-1];
}
public static int Fibo2(int n){
//与1比,节省空间
int a=1;
int b=1;
int c=0;
for(int i = 2;i<n;i++){
c = a+b;
a = b;
b = c;
}
return c;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n<1)
System.out.print("error");
else if (n==1 || n==2)
System.out.print("1");
else
{
System.out.print(Fibo1(n));
System.out.print(Fibo2(n));
}
}
}
/**基本思想:
* 使用递推法。
* 后面方法,通过有限的变量存储信息/
*/