Skip to content

Commit 23eec39

Browse files
Aayush2111Debasish Biswas
and
Debasish Biswas
authored
Fibonacci optimized using binet's formula (TheAlgorithms#3728)
* Fibonacci optimized using binet's formula * Update Fibonacci.java * Update Fibonacci.java * updated changes Co-authored-by: Debasish Biswas <[email protected]>
1 parent 8efc71e commit 23eec39

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java

+18-1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public static void main(String[] args) {
1919
System.out.println(fibMemo(n));
2020
System.out.println(fibBotUp(n));
2121
System.out.println(fibOptimized(n));
22+
System.out.println(fibBinet(n));
2223
sc.close();
2324
}
2425

@@ -90,5 +91,21 @@ public static int fibOptimized(int n) {
9091
res = next;
9192
}
9293
return res;
93-
}
9494
}
95+
96+
/**
97+
* 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.
98+
* The Fibonacci terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced ‘phi'.
99+
* First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 = 1.6180339887...
100+
* Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5
101+
* We first calculate the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get the required term.
102+
* Time Complexity will be O(1)
103+
*/
104+
105+
public static int fibBinet(int n) {
106+
double squareRootOf5 = Math.sqrt(5);
107+
double phi = (1 + squareRootOf5)/2;
108+
int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5);
109+
return nthTerm;
110+
}
111+
}

0 commit comments

Comments
 (0)