Fibonacci数列四种实现
public class demo4_Fibonacci {
public static void main(String[] args) {
demo4_Fibonacci demo4 = new demo4_Fibonacci();
System.out.println("请输入N的值");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
System.out.println(demo4.fibD(n));
System.out.println(demo4.fibC(n));
System.out.println(demo4.fibB(n));
System.out.println(demo4.fibA(n));
System.out.println("程序结束");
}
public long fibA(int n) {
if(n==0) return 0;
if(n==1) return 1;
return fibA(n-1)+fibA(n-2);
}
public long fibB(int n) {
long fibo[]= new long[100];
if(n==0) return 0;
if(n==1) return 1;
fibo[0]=0;
fibo[1]=1;
for(int i=2;i<=n;i++)
fibo[i]=fibo[i-2]+fibo[i-1];
return fibo[n];
}
long fib[]= new long[100];
public long fibC(int n) {
if(n==0) return 0;
if(n==1) return 1;
if(fib[n]!=0) return fib[n];
return fib[n]=fibC(n-1)+fibC(n-2);
}
public long fibD(int n) {
long front2=0,front1=1,sum = 0;
for(int i=2;i<=n;i++)
{
sum=front2+front1;
front2=front1;
front1=sum;
}
return sum;
}
}