medium level problem - Marbles SIGSEGV error

for the problem Marbles : http://www.codechef.com/problems/MARBLES here is the code.
But the problem is code chef is returning SIGSEGV error and i am unable to find out the problem in my code. So please tell me can my code be modified to fit the conditions of the question or do i have to think from a new perspective?

here is the code:

#include<iostream>
using namespace std;

long long int C(int n,int r)
{
    if(r==1)
        return n;
    if(n==r)
        return 1;
    long long int c=C(n-1,r)+C(n-1,r-1);
    return c;
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,r;
        cin>>n>>r;
        cout<<C(n-1,r-1)<<endl;
    }
}

You are using recursion may be due to stackoverflow you are getting this error. You should find a better efficient method for calculating nCr for given “n” and “r”.
You can further optimiz it . Posting code here but don’t copy this code , try to understand it and then modify your code :slight_smile:


long long FindWays(int a,int b){
  int n = a-1;
  int r = b-1,i=0;
  long long result=1;
  if (r > n/2) {
    r = n - r;
  }
  for (i = 0; i < r; i++) {
    result *= (n-i);
    result /= (i+1);
  }
  return result;
}
2 Likes

I think chandan is right. . .

I think RachGonz is right. . .

I think codesniper99 is right. . .

I don’t understand how this is the solution.
in the example, aren’t we solving 30C7?
(30x29x28x27x26x25x24) / (1x2x3x4x5x6x7)?

the solution above and whats given as the example shows the solution to 29C6 unless there’s something I’m not understanding from the description

He is also finding 29C6. In function he had done n=a-1 and r=b-1.