Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a56b839

Browse files
Merge pull request #113 from SmartyPants042/master
Added Program to Calculate nCr of Large Numbers Using Modular Arithmetic
2 parents f1fdc08 + 9b4296c commit a56b839

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

‎a.out‎

-8.26 KB
Binary file not shown.

‎nCrCalculatorLargeNumbers.c‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <stdio.h>
2+
#define m 1000000007
3+
#include <math.h>
4+
5+
// This function calcualtes the large powers with O(log(n))
6+
long fastexp(long x, long y)
7+
{
8+
// In the form of pow(x, y) % m
9+
if(y == 0)
10+
return 1;
11+
else if (y == 1)
12+
return x;
13+
else
14+
{
15+
long ans = fastexp(x, y/2);
16+
if(y % 2 == 0)
17+
return (ans % m * ans % m) % m;
18+
else
19+
return ((ans % m * ans % m) % m * x % m) % m;
20+
}
21+
}
22+
23+
long fact[2000001] = {1};
24+
25+
int main()
26+
{
27+
// FACTORIAL CALCULATION
28+
// Using (a * b) % m = (a % m * b % m) % m
29+
for(int i = 1; i < 2000001; i++)
30+
fact[i] = ((fact[i-1] % m) * (i % m)) % m;
31+
32+
// Number of test cases
33+
int T;
34+
long n, r, ans;
35+
printf("Enter the number of test cases: ");
36+
scanf("%d", &T);
37+
while(T--)
38+
{
39+
printf("Enter the two numbers in the form of xCy: ");
40+
scanf("%ld%ld", &n, &r);
41+
42+
// Formula used: (n)!/ (r! * (n-r)!)
43+
// = (n+r)! * pow((r! * (n-r)!), -1)
44+
// Using FERMAT's LITTLE THEOREM (Google it!)
45+
// = (fact[n]%m * pow((r! * (n-r)!), m - 2) % m) % m
46+
// = (fact[n]%m * fastexp((fact[r] * fact[n-r])%m, m - 2)%m)%m
47+
48+
ans = (fact[n]%m * fastexp((fact[r]%m * fact[n-r]%m) % m, m - 2) % m) % m;
49+
printf("%ld\n", ans);
50+
}
51+
return 0;
52+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /