Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type-safe modular arithmetic #18

Open
pathikrit opened this issue Oct 6, 2017 · 0 comments
Open

Type-safe modular arithmetic #18

pathikrit opened this issue Oct 6, 2017 · 0 comments

Comments

@pathikrit
Copy link
Owner

class ModularArithmetic(val mod: Long) {
  class Mod(val value: Long) {
    override val toString = value.toString
  }
  implicit def fromMod(mod: Mod): Long = mod.value
  implicit def toMod(x: Long): Mod = new Mod(x%mod)

  val factorial: IndexedSeq[Mod] = {
    val N = 5500
    val f = Array.ofDim[Mod](N)
    f(0) = 1L
    (1 until N).foreach(i => f(i) = f(i-1) * i)
    f
  }

  def modularInverse(n: Long): Mod = BigInt(n).modInverse(mod).toLong //If mod is prime override this with BigInt(n).modPow(mod - 2, mod).toLong

  def modDiv(a: Long, b: Long): Mod = a * modularInverse(b)

  def permutations(n: Int, k: Int): Mod = modDiv(factorial(n), factorial(n - k))

  def combinations(n: Int, k: Int): Mod = modDiv(permutations(n, k), factorial(k))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant