Given a positive integer N. The task is to find the number of ways of representing N as a sum of 1s and 2s.
Input : N = 3 Output : 3 3 can be represented as (1+1+1), (2+1), (1+2). Input : N = 5 Output : 8
For N = 1, answer is 1.
For N = 2. (1 + 1), (2), answer is 2.
For N = 3. (1 + 1 + 1), (2 + 1), (1 + 2), answer is 3.
For N = 4. (1 + 1 + 1 + 1), (2 + 1 + 1), (1 + 2 + 1), (1 + 1 + 2), (2 + 2) answer is 5.
And so on.
It can be observe that it form Fibonacci Series. So, the number of ways of representing N as a sum of 1s and 2s is (N + 1)th Fibonacci number.
We can easily see that the recursive function is exactly same as Fibonacci Numbers. To obtain the sum of N, we can add 1 to N – 1. Also, we can add 2 to N – 2. And only 1 and 2 are allowed to make the sum N. So, to obtain sum N using 1s and 2s, total ways are: number of ways to obtain (N – 1) + number of ways to obtain (N – 2).
We can find N’th Fibonacci Number in O(Log n) time. Please refer method 5 of this post.
Below is the implementation of this approach:
Time Complexity: O(logn).
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of ways to represent a number as sum of k fibonacci numbers
- Different ways to represent N as sum of K non-zero integers
- Minimum number of given powers of 2 required to represent a number
- Number of ways to reach the end of matrix with non-zero AND value
- Number of ways to get even sum by choosing three numbers from 1 to N
- Number of ways to pair people
- Number of ways to go from one point to another in a grid
- Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes
- Total number of ways to place X and Y at n places such that no two X are together
- Count ways to express even number ‘n’ as sum of even integers
- Number of ways to cut a stick of length N into K pieces
- Represent n as the sum of exactly k powers of two | Set 2
- Number of ways of scoring R runs in B balls with at most W wickets
- Number of ways to select a node from each connected component
- Number of ways to make mobile lock pattern