|
| 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