Last active
October 24, 2025 05:26
-
-
Save valarpirai/b66992a36b50c8f77f5c2040f2fcd8d2 to your computer and use it in GitHub Desktop.
Revisions
-
valarpirai revised this gist
Oct 24, 2025 . 1 changed file with 2 additions and 0 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,5 @@ 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); @@ -33,5 +34,6 @@ public static void findFib(int n) { public static void main(String[] args) { findFib(10); findFib(45); // findFib(100); - I will never call this method with recursive approach } } -
valarpirai created this gist
Oct 24, 2025 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,37 @@ public class Fibonacci { // 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); } }