C++ Program for Ways to sum to N using Natural Numbers up to K with repetitions allowed
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}, the sum is 8.
- {2, 1, 1, 1, 1, 1, 1}, the sum is 8.
- {2, 2, 1, 1, 1, 1}, the sum is 8.
- 2, 2, 2, 1, 1}, the sum is 8.
- {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.
Please refer complete article on Ways to sum to N using Natural Numbers up to K with repetitions allowed for more details!
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 Codeint 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!


.png)

