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.
Input: l = 2, r = 5
fib(2) + fib(3) + fib(4) + fib(5) = 1 + 2 + 3 + 5 = 11
Input: l = 4, r = 8
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 help of Golden Ratio.
Fibonacci calculation using Binet’s Formula
fib(n) = phin – psin) / ?5
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:
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.
- F(i) refers to the ith Fibonacci number.
- S(i) refers to sum of Fibonacci numbers till F(i).
We can rewrite the relation F(n + 1) = F(n) + F(n – 1) as below:
F(n – 1) = F(n + 1) – F(n)
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)
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.
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)
# Python3 implementation of the approach
# Function to return the nth
# Fibonacci number
phi = (1 + math.sqrt(5)) / 2;
return int(round(pow(phi, n) /
# Function to return the required sum
def calculateSum(l, r):
# Using our deduced result
sum = fib(r + 2) – fib(l + 1);
# Driver code
l = 4;
r = 8;
# This code is contributed by mits
- Count Fibonacci numbers in given range in O(Log n) time and O(1) space
- Sum of Fibonacci Numbers
- Non Fibonacci Numbers
- Even Fibonacci Numbers Sum
- GCD and Fibonacci Numbers
- C Program for Fibonacci numbers
- Sum of squares of Fibonacci numbers
- Find the sum of first N odd Fibonacci numbers
- Prime numbers and Fibonacci
- The Magic of Fibonacci Numbers
- Program for Fibonacci numbers
- Alternate Fibonacci Numbers
- Sum of Fibonacci Numbers with alternate negatives
- Interesting facts about Fibonacci numbers
- Large Fibonacci Numbers in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.