GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Total ways to distribute choclates

Imagine you have been recently placed in a very good company ;D and as celebration you decide to distribute chocolates to kids in your society, you being humble and rash give at least one chocolate to each kid. You tell me the total number of ways in which you can distribute R chocolates to N kids. As total number of ways can go very large so output total number ways modulo 10000007. If not possible to distribute print -1.

R = 2, N = 1
Output : 1

R = 4, N = 2
Output : 3

asked Aug 27, 2015 by Gaurav

1 Answer

Basically the answer of this problem is  N-1 C R-N     and if N > R then -1

but as this value can be very large , calculating N C R is tricky with mod , I have calculated NCR with Lucas theorem check the code below - 

#include <bits/stdc++.h>
using namespace std;

long long SmallC(int n, int r, int MOD)
    vector< vector<long long> > C(2,vector<long long> (r+1,0));
    for (int i=0; i<=n; i++)
        for (int k=0; k<=r && k<=i; k++)
            if (k==0 || k==i)
                C[i&1][k] = 1;
                C[i&1][k] = (C[(i-1)&1][k-1] + C[(i-1)&1][k])%MOD;
    return C[n&1][r];
long long Lucas(int n, int m, int p)
    if (n==0 && m==0) return 1;
    int ni = n % p;
    int mi = m % p;
    if (mi>ni) return 0;
    return Lucas(n/p, m/p, p) * SmallC(ni, mi, p);
long long NCR(int n, int r, int MOD)
    return Lucas(n, r, MOD);

int main()
	int Cases;
	int N , R;
	scanf("%d" , &Cases);

		scanf("%d %d" , &R, &N);
		int res = -1;

		if(R >= N)
			res = NCR(R - 1, R - N, 10000007);

		printf("%d\n", res);


answered Aug 27, 2015 by utkarsh111

Okay..It's nice and you are correct.. :) though can be easily solved using dp too .. can try if you want to...