2012-03-28 16:34:22Morris
[UVA][JAVA] 495 - Fibonacci Freeze
Fibonacci Freeze
Fibonacci Freeze |
The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) are defined by the recurrence:
Write a program to calculate the Fibonacci Numbers.
Input and Output
The input to your program would be a sequence of numbers smaller or equal than 5000, each on a separate line, specifying which Fibonacci number to calculate.
Your program should output the Fibonacci number for each input value, one per line.
Sample Input
5 7 11
Sample Output
The Fibonacci number for 5 is 5 The Fibonacci number for 7 is 13 The Fibonacci number for 11 is 89
import java.util.Scanner;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
BigInteger[] F = new BigInteger[5001];
F[0] = BigInteger.valueOf(0);
F[1] = BigInteger.valueOf(1);
for(int i = 2; i <= 5000; i++) {
F[i] = F[i-1].add(F[i-2]);
}
int n;
while(keyboard.hasNextInt()) {
n = keyboard.nextInt();
System.out.println("The Fibonacci number for " + n + " is " + F[n].toString());
}
}
}