Given an positive integer n. Count total number of ways to express ‘n’ as sum of odd positive integers.
Input: 4 Output: 3 Explanation There are only three ways to write 4 as sum of odd integers: 1. 1 + 3 2. 3 + 1 3. 1 + 1 + 1 + 1 Input: 5 Output: 5
Simple approach is to find recursive nature of problem. The number ‘n’ can be written as sum of odd integers from either (n-1)th number or (n-2)th number. Let the total number of ways to write ‘n’ be ways(n). The value of ‘ways(n)’ can be written by recursive formula as follows:
ways(n) = ways(n-1) + ways(n-2)
The above expression is actually the expression for Fibonacci numbers. Therefore problem is reduced to find the nth fibonnaci number.
ways(1) = fib(1) = 1 ways(2) = fib(2) = 1 ways(3) = fib(2) = 2 ways(4) = fib(4) = 3
Note: The time complexity of the above implementation is O(n). It can be further optimized up-to O(Logn) time using Fibonacci function optimization by Matrix Exponential.
This article is contributed by Shubham Bansal. 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.
- Count ways to express even number ‘n’ as sum of even integers
- Count of different ways to express N as the sum of 1, 3 and 4
- Different ways to represent N as sum of K non-zero integers
- Number of ways to form a heap with n distinct integers
- Count possible ways to construct buildings
- Count ways to reach the nth stair using step 1, 2 or 3
- Count ways to distribute m items among n people
- Count ways to spell a number with repeated digits
- Count ways to form minimum product triplets
- Minimum numbers needed to express every integer below N as a sum
- Ways to represent a number as a sum of 1's and 2's
- Number of arrays of size N whose elements are positive integers and sum is K
- Different ways to sum n using numbers greater than or equal to m
- Ways to color a 3*N board using 4 colors
- Number of ways to get even sum by choosing three numbers from 1 to N
Improved By : vt_m