I've been doing a code to get the combinatory function. it must be a recursive function, using the formula C(n,k)= n!/k!(n-k)!, I am not allowed to create a recursive factorial function. I was solving it this way: C(n,k)=(n/k(x))*(n-1/(k-1)(x-1))*...*1.until n,k and x = 1. I have a certain solution, but it keeps giving me the sam problem, it compiles but once I run it I get a segmentation fault. can't find the reason.
#include <iostream>
usingnamespace std;
double C( double n, double k ) {
double x = n-k;
double Res = n/k*(x);
if ( n == k == x) {
return 1;
}
else {
if (n != 1) {
n -= 1;
}
if (k != 1) {
k -= 1;
}
if (x == 0) {
x = 1;
}
if ( x > 1 ) {
x -= 1;
}
return Res = Res* C(n,k);
}
}
int main(){
cout << C(6,2) << endl;
}
Equality comparison of floating point values is not trivial. Lets skip that.
1 2 3 4
if ( n == k == x )
// is equivalent to
bool b = ( n == k );
if ( b == x )
Perhaps you mean: if ( (n == k) && (k == x) )
However, if x = n-k; and n == k then x == 0
and (n == k) && (k == x) is true only if n == 0.
There is your reason.
Note that lines 20-26 are totally useless.
I can't create a recursive factorial function.
"Can't" as in "I am not allowed" or as in "I fail"?
n! == 1*2*3*..*n
You have x = n-k
Lets call y = max(k,x) and z = min(k,x)
#include <iostream>
#include <algorithm>
usingnamespace std;
int nCr( int n, int r, int k = -1 )
{
if ( k < 0 ) k = r = min( r, n - r );
return k == 0 ? 1 : nCr( n, r, k - 1 ) * ( n - r + k ) / k;
}
int main()
{
int n, r;
cout << "Input n and r: "; cin >> n >> r;
cout << n << 'C' << r << " = " << nCr( n, r ) << '\n';
}