fibonacci Dynamic Programming via BigInteger - Java java.lang

Java examples for java.lang:Math Number

Description

fibonacci Dynamic Programming via BigInteger

Demo Code


//package com.java2s;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        int n = 2;
        System.out.println(fibonacciDynamicProgramming(n));
    }//from w w w  .  ja  v a2 s. c  om

    private static List<BigInteger> mSavedFibonacci = new ArrayList<>();

    public static BigInteger fibonacciDynamicProgramming(int n) {
        if (0 == n) {
            mSavedFibonacci.add(BigInteger.ZERO);
            return BigInteger.ZERO;
        }

        if (1 == n) {
            mSavedFibonacci.add(BigInteger.ONE);
            return BigInteger.ONE;
        }

        for (int i = mSavedFibonacci.size(); i <= n; ++i) {
            mSavedFibonacci.add(mSavedFibonacci.get(i - 2).add(
                    mSavedFibonacci.get(i - 1)));
        }

        return mSavedFibonacci.get(n);
    }
}

Related Tutorials