Skip to content

Instantly share code, notes, and snippets.

@jayhutfles
Last active April 15, 2016 19:07
Show Gist options
  • Save jayhutfles/5eca4dd1b3e7fc5212f14ab1ac4950a6 to your computer and use it in GitHub Desktop.
Save jayhutfles/5eca4dd1b3e7fc5212f14ab1ac4950a6 to your computer and use it in GitHub Desktop.
Finding the order of integer n in the multiplicative group of integers mod m
import scala.annotation.tailrec
def order(n: Int, m: Int): Option[Int] = {
@tailrec
def loop(acc: Int, iters: Int): Option[Int] = {
(acc % m) match {
case 0 => None
case 1 => Some(iters)
case _ => loop((acc * n) % m, iters + 1)
}
}
loop(n % m, 1)
}
@jayhutfles
Copy link
Author

Note, this doesn't terminate if gcd(n,m) > 1. Need to fix this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment