![]() |
VOOZH | about |
Given a range [l, r], the task is to find the sum fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r) where fib(n) is the nth Fibonacci number.
Examples:
Input: l = 2, r = 5
Output: 11
fib(2) + fib(3) + fib(4) + fib(5) = 1 + 2 + 3 + 5 = 11Input: l = 4, r = 8
Output: 50
Naive approach: Simply calculate fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r) in O(r - l) time complexity.
In order to find fib(n) in O(1) we will take the help of the Golden Ratio.
Fibonacci's calculation using Binet's Formula
fib(n) = phin - psin) / ?5
Where,
phi = (1 + sqrt(5)) / 2 which is roughly equal to 1.61803398875
psi = 1 - phi = (1 - sqrt(5)) / 2 which is roughly equal to 0.61803398875
Below is the implementation of the above approach:
50
Efficient approach: The idea is to find the relationship between the sum of Fibonacci numbers and nth Fibonacci number and use Binet's Formula to calculate its value.
Relationship Deduction
We can rewrite the relation F(n + 1) = F(n) + F(n - 1) as below:
F(n - 1) = F(n + 1) - F(n)
Similarly,
F(n - 2) = F(n) - F(n - 1)
...
...
...
F(0) = F(2) - F(1)
Adding all the equations, on left side, we have
F(0) + F(1) + ... + F(n - 1) which is S(n - 1)
Therefore,
S(n - 1) = F(n + 1) – F(1)
S(n - 1) = F(n + 1) – 1
S(n) = F(n + 2) – 1
In order to find S(n), simply calculate the (n + 2)th Fibonacci number and subtract 1 from the result.
Therefore,
S(l, r) = S(r) - S(l - 1)
S(l, r) = F(r + 2) - 1 - (F(l + 1) - 1)
S(l, r) = F(r + 2) - F(l + 1)
50
Time Complexity: O(log r)
Auxiliary Space: O(1)