I have a small program. I have to calculate combination with repetition.
My code:
int factorial(int a){
if (a<0)
return 0;
if (a==0 || a==1)
return 1;
return factorial(a-1)*a;
}
long int combinationWithRepetion(int n, int k){
long int a,b,wyn=0;
wyn=factorial(n+(k-1))/(factorial(k)*factorial(n-1));
return wyn;
}
int main()
{
int k,n=0;
cout<<"Give n: ";
cin>>n;
cout<<"Give k: ";
cin>>k;
cout<<"combination With Repetion for n="<<n<<
" k="<<k<<".\n Is equal to "<<combinationWithRepetion(n,k)<<endl;
return 0;
}
For n=9 and k=6 in Wolfram alfa I get 3003, but in this program the result is 44.
For me the code is fine.
With
n=9andk=6you computefactorial(14)which is87,178,291,200which will overflow a 4-byteint. You need to use something likelong longto get an 8-byteintif you want to use this formula.There are better formulas for computing binomial coefficients which do not rely on computing the full factorials then doing the division. See Binomial coefficient in programming languages, the direct method (rather than using recursion).
In C++ you can use: