Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.math.BigInteger;
- public class problem5 {
- static BigInteger fib_cash[] = new BigInteger[100];
- public static BigInteger fibonacci(int n)
- {
- if (fib_cash[n].compareTo(BigInteger.ZERO) >= 0)
- return fib_cash[n];
- if (n == 0) return BigInteger.ZERO;
- if (n == 1) return BigInteger.ONE;
- fib_cash[n] = fibonacci(n - 1).add(fibonacci(n - 2));
- return fib_cash[n];
- }
- public static void main(String[] args) throws IOException
- {
- for (int i = 0; i < 100; i++)
- fib_cash[i] = BigInteger.valueOf(-1);
- fib_cash[0] = BigInteger.ZERO;
- fib_cash[1] = BigInteger.ONE;
- BigInteger n;
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- System.out.print("Input n: ");
- String s = reader.readLine();
- try
- {
- n = BigInteger.valueOf(Long.parseLong(s));
- if (n.compareTo(BigInteger.valueOf(0)) < 0 || n.compareTo(BigInteger.valueOf(100)) > 0)
- {
- System.out.print("Wrong n!");
- reader.readLine();
- return;
- }
- }
- catch(Exception e)
- {
- System.out.print("Wrong n!");
- reader.readLine();
- return;
- }
- System.out.println("Fibonacci numbers:");
- for (int i = 0; i < n.intValue(); i++)
- System.out.print(fibonacci(i).toString() + " ");
- }
- }
Add Comment
Please, Sign In to add comment