Java数组预处理实现费切那波数列

下面我们展示一段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];
         }
     }



}   

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章