To my mind the statement of the problem is incorrect. N is supposed to be infinte. So if N = 10^200 that's OK. And in this case there is an enormous amount of possible equations.
Let's consider that N <= 100. Now we can write a beautiful C++ solution of the problem.
Code:
#include <iostream>
#include <vector>
using namespace std;
int n, k, total;
void rec(int cur, int k, int last, vector < int >& items)
{
if (k == 1)
{
++total;
items.push_back(cur);
for (size_t i = 0; i < items.size(); ++i)
{
cout << items[i] << " " << (i < items.size() - 1 ? "+ " : "= ");
}
cout << n << endl << endl;
items.pop_back();
}
else
{
for (int i = last; i <= cur / k; ++i)
{
items.push_back(i);
rec(cur - i, k - 1, i, items);
items.pop_back();
}
}
}
int main()
{
cin >> k >> n;
total = 0;
vector < int > items;
items.reserve(k);
rec(n, k, 1, items);
cout << "Total unique equations = " << total << endl;
return 0;
}
Excuse me, but I haven't implemented input checking.
Some tips about code posted:
- cin is used for input and cout for output. These classes are not as fast as scanf and printf. So we use them because we know that the input and output are not very large.
- We use vector<int> to keep numbers used in the current equation. vector is a standard C++ template, it is an array with variable length.
- The major idea of the recursive solution is as follows. We need to generate K numbers sum of which equals to N. Let's take a number 1 <= X <= N and generate (K - 1) numbers sum of which is (N - X).
- To make our program generate only unique euqations we use numbers not less than one used on the previous step.
I hope that you will understand my explanation because I'm not sure in quality of my English :)