reason why I get a segmentation fault: 11

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace 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;
  return 0;
}


thanks for your help! :)
Last edited on
First, code tags make posts more readable. See http://www.cplusplus.com/articles/jEywvCM9/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace 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)

You equation is binomial coefficient, isn't it?
n! / (y! * z!)

However,
n! = y! * (y+1) * (y+2) * .. * n

therefore
n! / (y! * z!) == ((y+1) * (y+2) * .. * n) / z!

Whether that note helps you ... don't know.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <algorithm>
using namespace 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';
}

Input n and r: 6 2
6C2 = 15
Last edited on
Topic archived. No new replies allowed.