Write a C++ program to list all solutions of x1 + x2 + ... xn = c.
x1 ... xn are non-negative integers.
Hi,
Here is the code:
#include<iostream>
using namespace std;
int countSolutions(int n, int val)
{
int total = 0;
// Base Case if n = 1 and val >= 0
if (n == 1 && val >=0)
return 1;
// iterate the loop till equal the val
for (int i = 0; i <= val; i++){
total += countSolutions(n-1, val-i);
}
// return the total no possible solution
return total;
}
int main(){
int n = 5;
int val = 20;
cout<<countSolutions(n, val);
}
The code outputs the number of solutions to a given equation.
Thanks :)
Get Answers For Free
Most questions answered within 1 hours.