Guest User

Untitled

a guest
Jan 19th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.math.BigInteger;
  5.  
  6.  
  7. public class problem5 {
  8.     static BigInteger fib_cash[] = new BigInteger[100];
  9.    
  10.     public static BigInteger fibonacci(int n)
  11.     {
  12.         if (fib_cash[n].compareTo(BigInteger.ZERO) >= 0)
  13.             return fib_cash[n];
  14.        
  15.         if (n == 0) return BigInteger.ZERO;
  16.         if (n == 1) return BigInteger.ONE;
  17.        
  18.         fib_cash[n] = fibonacci(n - 1).add(fibonacci(n - 2));
  19.         return fib_cash[n];
  20.     }
  21.    
  22.     public static void main(String[] args) throws IOException
  23.     {
  24.         for (int i = 0; i < 100; i++)
  25.             fib_cash[i] = BigInteger.valueOf(-1);
  26.        
  27.         fib_cash[0] = BigInteger.ZERO;
  28.         fib_cash[1] = BigInteger.ONE;
  29.        
  30.         BigInteger n;
  31.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  32.         System.out.print("Input n: ");
  33.         String s = reader.readLine();
  34.         try
  35.         {
  36.             n = BigInteger.valueOf(Long.parseLong(s));
  37.             if (n.compareTo(BigInteger.valueOf(0)) < 0 || n.compareTo(BigInteger.valueOf(100)) > 0)
  38.             {
  39.                 System.out.print("Wrong n!");
  40.                 reader.readLine();
  41.                 return;
  42.             }
  43.         }
  44.         catch(Exception e)
  45.         {
  46.             System.out.print("Wrong n!");
  47.             reader.readLine();
  48.             return;
  49.         }
  50.         System.out.println("Fibonacci numbers:");
  51.         for (int i = 0; i < n.intValue(); i++)
  52.             System.out.print(fibonacci(i).toString() + " ");
  53.  
  54.     }
  55.  
  56. }
Add Comment
Please, Sign In to add comment