下面我们展示一段Java实现费切那波数列的代码。有两个特点,它将已经运算过的数存在数组中,从而避免了重复运算;还有采用的big integer来存储,可存储的数据更大。
import java.math.BigInteger;
import java.util.Scanner;
public class Experiment1
{
static BigInteger f[] = new BigInteger[200];
public static void main(String[]args)
{
f[0]=new BigInteger("1");
f[1]=new BigInteger("2");
for(int i=2;i<f.length;i++)
{
f[i]=new BigInteger("0");
}
Scanner scan=new Scanner(System.in);
while(scan.hasNext())
{
int n=scan.nextInt();
printFibonacciArray( n-1);
System.out.println(f[n-1]);
}
}
public static BigInteger printFibonacciArray(int n)
{//the first number, the second number,the totel fibonacci numbers
if(n==0)
{
return f[0];
}
else if(n==1)
return f[1];
else
{
if(f[n].compareTo(new BigInteger("0"))!=0)
return f[n];
else
{
f[n]=printFibonacciArray(n-1).add(printFibonacciArray(n-2));
return f[n];
}
}
}
}