Skip to content
Related Articles

Related Articles

C++ Program for Ways to sum to N using Natural Numbers up to K with repetitions allowed

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 27 Jan, 2022

Given two integers N and K, the task is to find the total number of ways of representing N as the sum of positive integers in the range [1, K], where each integer can be chosen multiple times.

Examples:

Input: N = 8, K = 2
Output: 5
Explanation: All possible ways of representing N as sum of positive integers less than or equal to K are:

  1. {1, 1, 1, 1, 1, 1, 1, 1}, the sum is 8.
  2. {2, 1, 1, 1, 1, 1, 1}, the sum is 8.
  3. {2, 2, 1, 1, 1, 1}, the sum is 8.
  4. 2, 2, 2, 1, 1}, the sum is 8.
  5. {2, 2, 2, 2}}, the sum is 8.

Therefore, the total number of ways is 5.

Input: N = 2, K = 2
Output: 2

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the total number of
// ways to represent N as the sum of
// integers over the range [1, K]
int NumberOfways(int N, int K)
{
  
    // Initialize a list
    vector<int> dp(N + 1, 0);
    
    // Update dp[0] to 1
    dp[0] = 1;
  
    // Iterate over the range [1, K + 1]
    for (int row = 1; row < K + 1; row++)
    {
  
        // Iterate over the range [1, N + 1]
        for (int col = 1; col < N + 1; col++)
        {
  
            // If col is greater
            // than or equal to row
            if (col >= row)
                
                // Update current
                // dp[col] state
                dp[col] = dp[col] + dp[col - row];
          }
    }
  
    // Return the total number of ways
    return(dp[N]);
}
  
// Driver Code
int main()
{
  int N = 8;
  int K = 2;
  
  cout << (NumberOfways(N, K));
}
  
// This code is contributed by mohit kumar 29.


Please refer complete article on Ways to sum to N using Natural Numbers up to K with repetitions allowed for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!