Skip to content

Commit 369900f

Browse files
William FisetWilliam Fiset
William Fiset
authored and
William Fiset
committed
2 parents 82d1f89 + f232fa4 commit 369900f

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/** @author Rohit Mazumder, mazumder.rohit7@gmai.com */
2+
package com.williamfiset.algorithms.math;
3+
4+
import java.math.BigInteger;
5+
6+
public class NChooseRModPrime {
7+
/**
8+
* Calculate the value of C(N, R) % P using Fermat's Little Theorem.
9+
*
10+
* @param N
11+
* @param R
12+
* @param P
13+
* @return The value of N choose R Modulus P
14+
*/
15+
public static long compute(int N, int R, int P) {
16+
if (R == 0) return 1;
17+
18+
long[] factorial = new long[N + 1];
19+
factorial[0] = 1;
20+
21+
for (int i = 1; i <= N; i++) {
22+
factorial[i] = factorial[i - 1] * i % P;
23+
}
24+
25+
return (factorial[N]
26+
* ModularInverse.modInv(factorial[R], P)
27+
% P
28+
* ModularInverse.modInv(factorial[N - R], P)
29+
% P)
30+
% P;
31+
}
32+
33+
// Method for testing output against the output generated by the compute(int,int,int) function
34+
private static String bigIntegerNChooseRModP(int N, int R, int P) {
35+
if (R == 0) return "1";
36+
BigInteger num = new BigInteger("1");
37+
BigInteger den = new BigInteger("1");
38+
while (R > 0) {
39+
num = num.multiply(new BigInteger("" + N));
40+
den = den.multiply(new BigInteger("" + R));
41+
BigInteger gcd = num.gcd(den);
42+
num = num.divide(gcd);
43+
den = den.divide(gcd);
44+
N--;
45+
R--;
46+
}
47+
num = num.divide(den);
48+
num = num.mod(new BigInteger("" + P));
49+
return num.toString();
50+
}
51+
52+
public static void main(String args[]) {
53+
int N = 500;
54+
int R = 250;
55+
int P = 1000000007;
56+
int expected = Integer.parseInt(bigIntegerNChooseRModP(N, R, P));
57+
long actual = compute(N, R, P);
58+
System.out.println(expected); // 515561345
59+
System.out.println(actual); // 515561345
60+
}
61+
}

0 commit comments

Comments
 (0)