Guest User

Untitled

a guest
Nov 23rd, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. import java.math.*;
  2.  
  3. public class Fibonacci{
  4.     private static int counter = 0;
  5.  
  6.     public static final BigInteger[] fibMemory = new BigInteger[2001];
  7.  
  8.     static {
  9.         fibMemory[0] = BigInteger.ONE;
  10.         fibMemory[1] = BigInteger.ONE;
  11.     }
  12.  
  13.     public static BigInteger fibonacci(int n) {
  14.         counter++;
  15.         if(fibMemory[n] == null)
  16.         if(n == 0) {
  17.             fibMemory[n] = BigInteger.valueOf(0);
  18.         } else if(n == 1 || n ==2) {
  19.             fibMemory[n]= BigInteger.valueOf(1);
  20.         } else {
  21.             fibMemory[n] = fibonacci(n-1).add(fibonacci(n-2));
  22.         }
  23.         return fibMemory[n];
  24.     }
  25.  
  26.     public static void main(String[] args) {
  27.         long time, newTime;
  28.         time = System.currentTimeMillis();
  29.         System.out.println("The 2000-th Fibonacci Number is " + fibonacci(2000) );
  30.         newTime = System.currentTimeMillis();
  31.         System.out.println("and was calculated in " + (newTime - time) + " ms" );
  32.         System.out.println("The fibonacci() method was called " + counter + " times");
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment