I have the following problem:
How many different ticket numbers are there with n digits that add up to "sum"?
For example:
How many different ticket numbers are there with 3 digits that add up to 4?
There are exactly 15 different such numbers:
004, 013, 022, 031, 040, 103, 112, 121, 130, 202, 211, 220, 301, 310, 400.
And I have the following code:
#include <iostream.h>
using namespace std;
int n,st[100],ok=0, sum;
void afisare()
{
int s=0;
for(int i=0;i<n;i++)
s=s+st[i];
if (s==sum)
{
for(int i=0;i<n;i++)
cout<<st[i]<<' ';
cout<<'\n';
ok++;
}
}
void back(int k)
{
int i;
if(k>n)
afisare();
else
for(i=0;i<10;i++)
{
st[k]=i;
back(k+1);
}
}
int main()
{
cout<<"n=";cin>>n;
cout << "sum= "; cin >> sum;
back(0);
cout << endl << endl << ok/10;
return 0;
}
The problem is that it types each solution exactly 10 times and I can't understand way...What am I doing wrong?