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;
}
1 Like

I think chandan is right. . .

I think RachGonz is right. . .

I think codesniper99 is right. . .