Given N and K. The task is to find out how many different ways are there to represent N as the sum of K non-zero integers.
Input: N = 5, K = 3
The possible combinations of integers are:
( 1, 1, 3 )
( 1, 3, 1 )
( 3, 1, 1 )
( 1, 2, 2 )
( 2, 2, 1 )
( 2, 1, 2 )
Input: N = 10, K = 4
The approach to the problem is to observe a sequence and use combinations to solve the problem. To obtain a number N, N 1’s are required, summation of N 1’s will give N. The problem allows to use K integers only to make N.
Let's take N = 5 and K = 3, then all possible combinations of K numbers are: ( 1, 1, 3 ) ( 1, 3, 1 ) ( 3, 1, 1 ) ( 1, 2, 2 ) ( 2, 2, 1 ) ( 2, 1, 2 ) The above can be rewritten as: ( 1, 1, 1 + 1 + 1 ) ( 1, 1 + 1 + 1, 1 ) ( 1 + 1 + 1, 1, 1 ) ( 1, 1 + 1, 1 + 1 ) ( 1 + 1, 1 + 1, 1 ) ( 1 + 1, 1, 1 + 1 )
From above, a conclusion can be drawn that of N 1’s, k-1 commas have to be placed in between N 1’s and the remaining places are to be filled with ‘+’ signs. All combinations of placing k-1 commas and placing ‘+’ signs in the remaining places will be the answer. So, in general, for N there will be N-1 spaces between all 1, and out of those choose k-1 and place a comma in between those 1. In between the rest 1’s, place ‘+’ signs. So ways of choosing K-1 objects out of N-1 is . The dynamic programming approach is used to calculate .
Below is the implementation of the above approach:
Total number of different ways are 6
- Ways to represent a number as a sum of 1's and 2's
- Number of ways to represent a number as sum of k fibonacci numbers
- Count ways to express 'n' as sum of odd integers
- Count ways to express even number ‘n’ as sum of even 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
- Represent a number as a sum of maximum possible number of Prime Numbers
- Factorial of an Array of integers
- Maximum GCD of N integers with given product
- Count of integers of the form (2^x * 3^y) in the range [L, R]
- Count of integers of length N and value less than K such that they contain digits only from the given set
- Queries for number of distinct integers in Suffix
- Minimum number of integers required to fill the NxM grid
- Number of arrays of size N whose elements are positive integers and sum is K
- Count integers in a range which are divisible by their euler totient value
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.