Fibonacci in Log (n) without using Matrix Exponentiation
As for calculating the n we can express it as the product of n/2 and n/2 ((n/2+1) for n is odd) as they are independent ,now as there are the cases when we combining these two half values to get full length there may be occurrence of consecutive 1’s at the joining. So we have to subtract those cases to get the final result.
f(n)=f(n/2)*f(n/2) – (those values which has consecutive 1’s at the joining part)
Below is the implementation of the above approach:
Python3
class Solution: def __init__( self ): self .mp = {} def countStrings( self , N): if N = = 0 : return 1 if N = = 1 : return 2 if N = = 2 : return 3 mod = 10 * * 9 + 7 a = self .mp.get(N / / 2 - 1 , self .countStrings(N / / 2 - 1 )) % mod b = self .mp.get(N / / 2 , self .countStrings(N / / 2 )) % mod c = self .mp.get(N / / 2 + 1 , self .countStrings(N / / 2 + 1 )) % mod if N % 2 : return (b * c - (c - b) * (b - a) + mod) % mod return (b * b - (b - a) * (b - a) + mod) % mod # t = int(input()) t = 1 while t > 0 : # N = int(input()) N = 10 obj = Solution() print (obj.countStrings(N)) t - = 1 # Code contributed by Chetan Chaudhary |
144
Time Complexity: O(log N)
Auxiliary Space: O(log N)
Please refer complete article on Count number of binary strings without consecutive 1’s for more details!
Python Program to Count number of binary strings without consecutive 1’s
Write a Python program for a given positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1s.
Examples:
Input: N = 2
Output: 3
// The 3 strings are 00, 01, 10Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101