desislava_topuzakova

07. Recursive Fibonacci

May 21st, 2021
2,198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.68 KB | None | 0 0
  1. package Exercise;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Scanner;
  5.  
  6. public class demo {
  7.     public static  long [] memoryForFib;
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.         int n = Integer.parseInt(scanner.nextLine());
  12.         memoryForFib = new long [n + 1];
  13.         System.out.println(fib(n));
  14.  
  15.  
  16.     }
  17.  
  18.     public static long fib (int n) {
  19.         if (n <= 1) {
  20.             return 1;
  21.         }
  22.  
  23.         if (memoryForFib[n] != 0) {
  24.             //имаме го изчислено
  25.             return memoryForFib[n];
  26.         }
  27.  
  28.         return memoryForFib[n] = fib(n - 1) + fib (n - 2);
  29.  
  30.     }
  31.  
  32.  
  33. }
Advertisement
Add Comment
Please, Sign In to add comment