Advertisement
Ligh7_of_H3av3n

RecursiveFibonacci

May 14th, 2024
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. package Uprajneniq;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Scanner;
  5.  
  6. public class RecursiveFibonacci {
  7.     public static void main(String[] args) {
  8.         Scanner scanner = new Scanner(System.in);
  9.  
  10.  
  11.         ArrayDeque<Long> Fibonacci = new ArrayDeque<>(); // Create a deque to store Fibonacci numbers
  12.  
  13.         // Read the input: the nth Fibonacci number to calculate
  14.         Scanner input = new Scanner(System.in);
  15.         int N = input.nextInt();
  16.  
  17.         // Call the getFibonacci method to calculate the nth Fibonacci number and print the result
  18.         System.out.println(getFibonacci(Fibonacci, N));
  19.     }
  20.  
  21.     // Method to calculate the nth Fibonacci number using recursion
  22.     private static Long getFibonacci(ArrayDeque<Long> Fibonacci, int N) {
  23.         if (N < 2) {
  24.             return 1L; // Base case: if N is 0 or 1, return 1
  25.         } else {
  26.             // Initialize the first two Fibonacci numbers
  27.             Fibonacci.offer(0L);
  28.             Fibonacci.offer(1L);
  29.  
  30.             // Generate the Fibonacci sequence up to N
  31.             for (int i = 0; i < N; i++) {
  32.                 long Sum = Fibonacci.poll() + Fibonacci.peek(); // Calculate the sum of the last two Fibonacci numbers
  33.                 Fibonacci.offer(Sum); // Add the sum to the sequence
  34.             }
  35.         }
  36.  
  37.         Fibonacci.poll(); // Remove the first element (0) as it's not part of the Fibonacci sequence
  38.         return Fibonacci.peek(); // Return the nth Fibonacci number
  39.     }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement