From 23eec39a29fc7fdf9c35fdec1920de4eb6d32150 Mon Sep 17 00:00:00 2001 From: Aayush2111 <85586404+Aayush2111@users.noreply.github.com> Date: Sun, 30 Oct 2022 09:26:08 +0530 Subject: [PATCH] Fibonacci optimized using binet's formula (#3728) * Fibonacci optimized using binet's formula * Update Fibonacci.java * Update Fibonacci.java * updated changes Co-authored-by: Debasish Biswas --- .../dynamicprogramming/Fibonacci.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java index aeabb20e..521bb2a9 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java @@ -19,6 +19,7 @@ public class Fibonacci { System.out.println(fibMemo(n)); System.out.println(fibBotUp(n)); System.out.println(fibOptimized(n)); + System.out.println(fibBinet(n)); sc.close(); } @@ -90,5 +91,21 @@ public class Fibonacci { res = next; } return res; - } } + + /** + * We have only defined the nth Fibonacci number in terms of the two before it. Now, we will look at Binet's formula to calculate the nth Fibonacci number in constant time. + * The Fibonacci terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced ‘phi'. + * First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 = 1.6180339887... + * Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5 + * We first calculate the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get the required term. + * Time Complexity will be O(1) + */ + + public static int fibBinet(int n) { + double squareRootOf5 = Math.sqrt(5); + double phi = (1 + squareRootOf5)/2; + int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5); + return nthTerm; + } +} \ No newline at end of file