-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModInt.kt
54 lines (47 loc) · 1.65 KB
/
ModInt.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@JvmInline
value class ModInt private constructor(val value: Int) {
operator fun plus(other: ModInt) = plus(other.value)
operator fun plus(other: Int) = from(value + other)
operator fun plus(other: Long) = from(value + other)
operator fun minus(other: ModInt) = minus(other.value)
operator fun minus(other: Int) = from(value - other)
operator fun minus(other: Long) = from(value - other)
operator fun times(other: ModInt) = times(other.value)
operator fun times(other: Int) = from(value.toLong() * other)
operator fun times(other: Long) = times(other.mod())
operator fun div(other: ModInt) = times(other.inv())
operator fun div(other: Int) = div(from(other))
operator fun div(other: Long) = div(from(other))
fun pow(exponent: Int): ModInt {
var ans = One
var a = this
var b = exponent
while (b > 0) {
if (b % 2 == 1) ans *= a
a *= a
b /= 2
}
return ans
}
fun inv(): ModInt = pow(MOD - 2)
override fun toString() = value.toString()
companion object {
fun combination(n: Int, k: Int): ModInt {
check(k in 0..n)
return (1..k).fold(One) { acc, i -> acc * (n - i + 1) / i }
}
fun from(value: Int) = ModInt(value.mod())
fun from(value: Long) = ModInt(value.mod())
fun Int.mod() = mod(MOD)
fun Long.mod() = mod(MOD)
val Zero = from(0)
val One = from(1)
const val MOD = 998244353
const val MOD = 1000000007
}
}
fun Array<ModInt>.sum(): ModInt {
var sum = ModInt.Zero
for (element in this) sum += element
return sum
}