-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodular.kt
More file actions
46 lines (42 loc) · 2.32 KB
/
modular.kt
File metadata and controls
46 lines (42 loc) · 2.32 KB
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
@file:Suppress("unused")
//typealias Modular = Double; fun Number.toModular() = toDouble(); fun Number.toModularUnsafe() = toDouble()
//typealias ModularArray = DoubleArray; val ModularArray.data; get() = this
private fun Double.inverse() = 1 / this
@JvmInline
@Suppress("NOTHING_TO_INLINE")
private value class Modular(val x: Int) {
companion object {
const val M = 998244353; val MOD_BIG_INTEGER = M.toBigInteger()
}
inline operator fun plus(that: Modular) = Modular((x + that.x).let { if (it >= M) it - M else it })
inline operator fun minus(that: Modular) = Modular((x - that.x).let { if (it < 0) it + M else it })
inline operator fun times(that: Modular) = Modular((x.toLong() * that.x % M).toInt())
inline operator fun div(that: Modular) = times(that.inverse())
inline fun inverse() = Modular(x.toBigInteger().modInverse(MOD_BIG_INTEGER).toInt())
fun pow(p: Int): Modular = when {
p < 0 -> this.inverse().pow(-p)
p == 0 -> 1.toModularUnsafe()
p == 1 -> this
p % 2 != 0 -> this.times(this.pow(p - 1))
else -> this.pow(p / 2).let { it.times(it) }
}
override fun toString() = x.toString()
}
private fun Int.toModularUnsafe() = Modular(this)
private fun Int.toModular() = Modular(if (this >= 0) { if (this < Modular.M) this else this % Modular.M } else { Modular.M - 1 - inv() % Modular.M })
private fun Long.toModular() = Modular((if (this >= 0) { if (this < Modular.M) this else this % Modular.M } else { Modular.M - 1 - inv() % Modular.M }).toInt())
private fun java.math.BigInteger.toModular() = Modular(mod(Modular.MOD_BIG_INTEGER).toInt())
private fun String.toModular() = Modular(fold(0L) { acc, c -> (c - '0' + 10 * acc) % Modular.M }.toInt())
@JvmInline
private value class ModularArray(val data: IntArray) {
operator fun get(index: Int) = data[index].toModularUnsafe()
operator fun set(index: Int, value: Modular) { data[index] = value.x }
fun sum() = (data.sumOf { it.toLong() } % Modular.M).toInt().toModularUnsafe()
}
private inline fun ModularArray(n: Int, init: (Int) -> Modular) = ModularArray(IntArray(n) { init(it).x })
private val factorials = mutableListOf(1.toModularUnsafe())
private fun factorial(n: Int): Modular {
while (n >= factorials.size) factorials.add(factorials.last() * factorials.size.toModularUnsafe())
return factorials[n]
}
private fun cnk(n: Int, k: Int) = factorial(n) / factorial(k) / factorial(n - k)