Created
May 19, 2011 03:00
-
-
Save clementi/980108 to your computer and use it in GitHub Desktop.
Fermat Primality Tester
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.util.Random | |
import scala.collection.immutable._ | |
import scala.math._ | |
class FermatPrimalityTester(rounds: Int) { | |
private val this.rounds = rounds | |
private val random = new Random | |
def isPrime(subject: Int): Boolean = { | |
return this.getRandomIntegers(subject) | |
.forall(randomInt => this.modExp(randomInt, subject - 1, subject) == 1) | |
} | |
private def getRandomIntegers(subject: Int): Iterable[Int] = { | |
return 0.until(this.rounds) | |
.map(index => this.random.nextInt(subject - 1) + 1) | |
} | |
private def modExp(base: Long, exponent: Long, modulus: Long): Long = { | |
if (exponent == 0) | |
return 1 | |
val z = this.modExp(base, exponent / 2, modulus) | |
if (exponent % 2 == 0) | |
return (z * z) % modulus | |
return base * (z * z) % modulus | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment