For a given number n > 0, find the number of different ways in which n can be written as a sum of at two or more positive integers.
Input : n = 5 Output : 6 Explanation : All possible six ways are : 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 Input : 4 Output : 4 Explanation : All possible four ways are : 3 + 1 2 + 2 2 + 1 + 1 1 + 1 + 1 + 1
This problem can be solved in the similar fashion as coin change problem, the difference is only that in this case we should iterate for 1 to n-1 instead of particular values of coin as in coin-change problem.
Time complexity O(n2)
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Ways to write N as sum of two or more positive integers | Set-2
- Number of ways to write N as a sum of K non-negative integers
- Number of arrays of size N whose elements are positive integers and sum is K
- Longest alternating subsequence in terms of positive and negative integers
- Number of ways to form a heap with n distinct integers
- Ways to form an array having integers in given range such that total sum is divisible by 2
- Longest alternating (positive and negative) subarray starting at every index
- Minimum time to write characters using insert, delete and copy operation
- Number of n-digits non-decreasing integers
- Count of integers of length N and value less than K such that they contain digits only from the given set
- Count of subsets of integers from 1 to N having no adjacent elements
- Count of integers from the range [0, N] whose digit sum is a multiple of K
- Number of integers in a range [L, R] which are divisible by exactly K of it's digits
- Count of different ways to express N as the sum of 1, 3 and 4
- All ways to add parenthesis for evaluation
Improved By : chitranayal