Last active
October 24, 2025 05:26
-
-
Save valarpirai/b66992a36b50c8f77f5c2040f2fcd8d2 to your computer and use it in GitHub Desktop.
Fibonacci calculation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Fibonacci { | |
| // Recursive approach without optimizations | |
| // Recursive: O(2^n) time, O(n) space | |
| public static long fibonacciRecursive(int n) { | |
| return n <= 1 ? n : fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); | |
| } | |
| // Iterative: O(n) time, O(1) space | |
| public static long fibonacciIterative(int n) { | |
| if (n <= 1) return n; | |
| long prev = 0, curr = 1; | |
| for (int i = 2; i <= n; i++) { | |
| long next = prev + curr; | |
| prev = curr; | |
| curr = next; | |
| } | |
| return curr; | |
| } | |
| public static void findFib(int n) { | |
| long start = System.nanoTime(); | |
| long iterative = fibonacciIterative(n); | |
| double iterativeTime = (System.nanoTime() - start) / 1_000_000.0; | |
| System.out.printf("Iterative (n=%d): %d, Time: %.3f ms%n", n, iterative, iterativeTime); | |
| start = System.nanoTime(); | |
| long recursive = fibonacciRecursive(n); | |
| double recursiveTime = (System.nanoTime() - start) / 1_000_000.0; | |
| System.out.printf("Recursive (n=%d): %d, Time: %.3f ms%n", n, recursive, recursiveTime); | |
| } | |
| public static void main(String[] args) { | |
| findFib(10); | |
| findFib(45); | |
| // findFib(100); - I will never call this method with recursive approach | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// findFib(100); - I will never call this method with a recursive approach
Want to know how long it will take with n =100?