1

I've tried the Marbles pkroblem on spoj - (link: http://www.spoj.com/problems/MARBLES/ )

However I'm getting Runtime Error(SIGSEGV) after multiple tries.

Here's the code I submitted -

#include <stdio.h>
int comb(long int n, long int k)
{

if (n==k || k==0)
    return 1;
else
    return (comb(n-1, k) + comb(n-1, k-1));
}

int main() {

int t;
long int n, k;
scanf("%d", &t);
while(t--)

{
    scanf("%ld %ld", &n, &k);
    printf("%d\n", comb(n-1, k-1));

}

return 0;
}

I cant understand why I'm getting the error. Other solutions on the internet have all used iterative way to calculate the nCr combination. I've tried using a recursive approach. Any help would be highly appreciated.

simonc
  • 41,632
  • 12
  • 85
  • 103

1 Answers1

0

you are decrementing n in the recursion but you don't check the case when n becomes 0 or negative, so the segfaul basically tells you that you get into an infinite recursion.

just add some stop criterion in addition to n==k || k==0.

I didn't look at the problem description so I don't know what the correct condition is, but perhaps you need something like

if (n==k || k==0 || n==0)
Pavel
  • 7,436
  • 2
  • 29
  • 42
  • I did what you said, and it does seem right. But I'm still getting the same runtime error. The problem is basically to calculate nCr (PnC) where n and r are very large. Therefore, instead of explicitly calculating factorials, I have used the identity nCr = (n-1)Cr + (n-1)C(r-1) in the recursive function. – user3719850 Jun 08 '14 at 19:54
  • well in most default settings, there's only a limited number of recursive function calls since they all need space on the stack. on linux, `ulimit -s` can sometimes be used to increase the size of the stack, but it is still not a solution for *very* large numbers. – Pavel Jun 08 '14 at 19:57
  • just look for a non-recursive solution, e.g. http://stackoverflow.com/questions/13156584/binomial-coefficient, http://stackoverflow.com/questions/13671614/binomial-coefficient-in-c etc. – Pavel Jun 08 '14 at 19:59