1+ import java .util .*;
2+
3+ import java .util .ArrayList ;
4+
15/**
26 * @verified
37 * <ul>
610 * <li> https://atcoder.jp/contests/abc129/tasks/abc129_f : (2 <= M <= 1000000000)
711 * <li> https://atcoder.jp/contests/arc050/tasks/arc050_c : (2 <= M <= 1000000000)
812 * <li> https://atcoder.jp/contests/arc012/tasks/arc012_4 : (1 <= M <= 1000000007)
13+ * <li> https://atcoder.jp/contests/abc042/tasks/arc058_b : (M = 1000000007, combination ver.)
914 * </ul>
1015 */
1116class ModIntFactory {
@@ -15,11 +20,15 @@ class ModIntFactory {
1520 private final boolean usesMontgomery ;
1621 private final ModArithmetic .ModArithmeticMontgomery maMontgomery ;
1722
23+ private ArrayList <Integer > factorial ;
24+
1825 public ModIntFactory (int mod ) {
1926 this .ma = ModArithmetic .of (mod );
2027 this .usesMontgomery = ma instanceof ModArithmetic .ModArithmeticMontgomery ;
2128 this .maMontgomery = usesMontgomery ? (ModArithmetic .ModArithmeticMontgomery ) ma : null ;
2229 this .mod = mod ;
30+
31+ this .factorial = new ArrayList <>();
2332 }
2433
2534 public ModInt create (long value ) {
@@ -31,6 +40,30 @@ public ModInt create(long value) {
3140 }
3241 }
3342
43+ private void prepareFactorial (int max ){
44+ factorial .ensureCapacity (max +1 );
45+ if (factorial .size ()==0 ) factorial .add (1 );
46+ for (int i =factorial .size (); i <=max ; i ++){
47+ factorial .add (ma .mul (factorial .get (i -1 ), i ));
48+ }
49+ }
50+
51+ public ModInt factorial (int i ){
52+ prepareFactorial (i );
53+ return create (factorial .get (i ));
54+ }
55+
56+ public ModInt permutation (int n , int r ){
57+ if (n < 0 || r < 0 || n < r ) return create (0 );
58+ prepareFactorial (n );
59+ return create (ma .div (factorial .get (n ), factorial .get (r )));
60+ }
61+ public ModInt combination (int n , int r ){
62+ if (n < 0 || r < 0 || n < r ) return create (0 );
63+ prepareFactorial (n );
64+ return create (ma .div (factorial .get (n ), ma .mul (factorial .get (r ),factorial .get (n -r ))));
65+ }
66+
3467 public int getMod () {
3568 return mod ;
3669 }
0 commit comments