emodev

Untitled

Dec 13th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. package Arrays.MoreExercise;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6.  
  7. public class FibonacciRecurs {
  8.     private static long[] memo;
  9.     public static void main(String[] args) throws IOException {
  10.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  11.         int n = Integer.parseInt(reader.readLine());
  12.  
  13.         memo = new long[n+1];
  14.         System.out.println(recursiveFibonacciWithMemoization(n));
  15.     }
  16.  
  17.  
  18.     private static long getFibonacci(long number) {
  19.         if (number <= 1) {
  20.             return 1;
  21.         }
  22.             long prev = getFibonacci(number - 1);
  23.             long prevPrev = getFibonacci(number - 2);
  24.  
  25.             return prev + prevPrev;
  26.  
  27.     }
  28.  
  29.     private static long recursiveFibonacciWithMemoization(int n) {
  30.         if (n <= 1) {
  31.             return 1;
  32.         }
  33.  
  34.         if (memo[n] != 0) {
  35.             return memo[n];
  36.         }
  37.  
  38.         memo[n] =
  39.                 recursiveFibonacciWithMemoization(n - 1) +
  40.                         recursiveFibonacciWithMemoization(n - 2);
  41.         return memo[n];
  42.     }
  43. }
Add Comment
Please, Sign In to add comment