Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 0’s.
Examples :
Input : N = 2 Output : 3 Explanation : 01,10,11 are binary strings of length 2 without consecutive 0’s Input : N = 3 Output : 5 Explanation : 010, 011, 101, 110, 111 are binary strings of length 3 without consecutive 0’s
Approach :
If we take a closer look at the pattern, we can observe that the count is actually (n+2)’th Fibonacci number for n >= 1. 2, 3, 5, 8, 13, 21, 34, 55……………………
Implementation :
#include<bits/stdc++.h>
using namespace std;
int fib(int n) {
double phi = (1 + sqrt(5)) / 2;
return round(pow(phi, n) / sqrt(5));
}
int main()
{
int n = 4;
cout<<fib(n+2); //(n+2)th fibonacci number
return 0;
}