# Count Fibonacci numbers in given range in O(Log n) time and O(1) space in C++

C++Server Side ProgrammingProgramming

We are given the range having start and end numbers and the task is to calculate the total count of Fibonacci numbers available between the given range in O(Log n) time and O(1) space.

## What are Fibonacci numbers

Fibonacci numbers are the sequence of numbers known as Fibonacci sequence where every new number is the sum of the last two preceding numbers.

Where, f(0) = 0 and f(1) = 1 i.e. f(0) and f(1) have fixed positions in the sequence and the calculation will start from the third number.

Formula used for calculating the sequence is −

Fn = Fn-1 + Fn-2

Where,

F0 = 0, F1 = l

For Example

Input − start = 6 and last = 100
Output − Number of fibonacci Numbers in the series are 6

Explanation − fibonacci numbers between 6 and 100 are 8, 13, 21, 34, 55, 89 i.e. total count is 6

Input − start = 0 and last = 8
Output − Number of fibonacci Numbers in the series are 7

Explanation − fibonacci numbers between 0 and 8 are 0, 1, 1, 2, 3, 5, 8 i.e. total count is 7

## Approach used in the below program is as follows

• Input the start and end numbers to create a range

• Declare and initialise fib1 to 0, fib2 to 1, fib3 to 1

• Declare a temporary variable res and initialise it with 0

• Start a loop, while fib1 is less than or equals to end

• Inside the loop, check if fib1 is greater than or equals to the start then increment the res by 1

• Set fib1 to fib2, fib2 to fib3 and fib3 to fib1 + fib2

• Return res

• Print the result

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
// function to count fibonacci numbers in range
// from start to last
int count_fibonacci(int start, int last){
// First three Fibonacci Numbers
int fib1 = 0, fib2 = 1, fib3 = 1;
// res to count the number of fibonacci
int res = 0;
while (fib1 <= last){
if (fib1 >= start){
res++;
}
fib1 = fib2;
fib2 = fib3;
fib3 = fib1 + fib2;
}
return res;
}
// main function
int main(){
int start = 6, last = 100;
cout << "Number of fibonacci Numbers in the series are "
<< count_fibonacci(start, last);
return 0;
}

## Output

If we run the above code it will generate the following output −

Number of fibonacci Numbers in the series are 6