Last active
April 15, 2016 19:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, this doesn't terminate if gcd(n,m) > 1. Need to fix this.