VOOZH about

URL: https://www.geeksforgeeks.org/dsa/different-ways-to-represent-n-as-sum-of-k-non-zero-integers/

⇱ Different ways to represent N as sum of K non-zero integers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Different ways to represent N as sum of K non-zero integers

Last Updated : 11 Jul, 2025

Given N and K. The task is to find out how many different ways there are to represent N as the sum of K non-zero integers.


Examples: 

Input: N = 5, K = 3 
Output:
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 
Output: 84

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 you to use K integers only to make N. 


Observation:  

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 the way 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: 


Output: 
Total number of different ways are 6

 

Time Complexity: O(N * K)
Auxiliary Space: O(N * K) 

Comment