NCR For Larger Numbers - 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

nCr without factorial

n n!
Cr = r!(n−r)!

20! = 2432902008176640000. 21! = 51090942171709440000. Value up to 20! can


be stored in the long long data type(in C/C++, long in Java). After that answer
goes beyond the range of long long data type. So calculating n Cr till factorial
less than equal to 20! works with the normal approach but it fails for larger
values.
Therefore we need another method to calculate n Cr for factorial more than 20!
The method discussed below required knowledge of calculating GCD.
For example N=50, R=25
n n! 50 50!
Cr = r!(n−r)! becomes C25 = 25!(50−25)! which is equal to
50 50!
C25 = 25!∗25! (we cannot calculate this using the normal factorial method, so
we simplify the above equation)
1∗2∗3∗4∗5....∗24∗25∗26∗27....∗49∗50
= 25!∗25! = 25!∗26∗27∗28∗29.....∗49∗50
25!∗25! = 26∗27∗28∗......∗49∗50
25!

Still, in this case, numerator and denominator both will be above long long
range, so we can do this step by step.
26∗27∗28∗......∗49∗50 26∗27∗28∗......∗49∗50
= 25! = 2∗3∗4∗5∗....∗24∗25

Step 1 : n = 50, r = 25.


50 2
25 (GCD(50,25) = 25, so divide both numbers by 25) = 1

Step 2 : n = 49, r = 24.


49∗2 98 49
24∗1 = 24 (GCD(98,24) = 2, so divide both numbers by 2) = 12

Step 3 : n = 48, r = 23.


48∗49 2352 196
23∗12 = 276 (GCD(2352,276) = 12, so divide both numbers by 12) = 23

Step 4 : n = 47, r = 22.


47∗196 9212 4606
22∗23 = 506 (GCD(9212,506) = 2, so divide both numbers by 2) = 253

and so on. . . This loop will run till r > 0 and numerator value will be the
answer.

long nCr(int n, int r)


{
long ans = 1, den = 1;
if(r!=0)
{
while(r>0){
ans*=n;

1
den*=r;

long gcd = gcdFun(ans,den);


ans/=gcd;
den/=gcd;
n--;
r--;
}
}
else
ans=1;

return ans;

You might also like