First, solve the problem. Then, write the code. ” - John Johnson

It's not at all important to get it right the first time. It's vitally important to get it right the last time. ” - Andrew Hunt and David Thomas

Tuesday, September 23, 2014

495 - Fibonacci Freeze (Dynamic approach)

Author : Jisan
Programming language : Java 
Difficulty : Easy
Status : Accepted
Problem number : UVA-495
 http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=436

Code:

import java.math.BigInteger;
import java.util.Scanner;
public class Uva_495 {
    public static void main(String[] args) {
        BigInteger[] fib = fib(5001);
        Scanner in= new Scanner(System.in);
        while(in.hasNext()){
            int n = in.nextInt();
            System.out.printf("The Fibonacci number for %d is %d\n", n, fib[n] );
        }
    }

    public static BigInteger[] fib(int n) {
        BigInteger[] fib = new BigInteger[n + 1];
        fib[0] = BigInteger.ZERO;
        fib[1] = BigInteger.ONE;
        for (int i = 2; i <= n; i++)
            fib[i]= fib[i-1].add(fib[i-2]);
        return fib;
    }
}

No comments:

Post a Comment