简要描述:
斐波纳契数列,又称黄金分割数列,指的是这样一个数列: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));
}
}
}
/**基本思想:
* 使用递推法。
* 后面方法,通过有限的变量存储信息/
*/
本文深入探讨了斐波纳契数列的定义与特性,并通过两种不同方式实现其计算:一种使用数组存储中间结果,节省空间;另一种通过有限变量存储信息,优化内存使用。同时,阐述了基本思想与算法复杂度分析。
778

被折叠的 条评论
为什么被折叠?



