我想在Scala中实现一个Stream
,用Lucas-Lehmer素性测试找到Mersenne素数。我已经有了:
object Main {
//Mersenne Numbers:
def msrn():Stream[BigInt] = 7#::msrn.map(_*2+1)
def s():Stream[BigInt] = 14 #:: s.map(n => n*n-2)
lazy val zips = s.zip(msrn)
def main(args: Array[String]) {
zips take 7 foreach println
}
}
我现在需要做的是找到所有梅森数字(msrn
中的元素),它们在s
中划分元素并将其写在Stream
中。
编辑:解决了它:
object Main {
def msrn():Stream[BigInt] = 7#::msrn.map(_*2+1)
def s():Stream[BigInt] = 14 #:: s.map(n => n*n-2)
lazy val zips = s.zip(msrn).filter(x=>x._1%x._2==0)
def mersennePrimeStream():Stream[BigInt] = zips.map(x => x._2)
def main(args: Array[String]) {
mersennePrimeStream take 4 foreach println
}
}
有没有办法缩短它?
答案 0 :(得分:0)
如果你计算正在测试的Mersenne数的s序列,你会快得多:
object Main {
def s(k: Int, m: BigInt) = Iterator.iterate(BigInt(14))(n => (n * n - 2) % m) drop k next
lazy val msrn: Stream[(Int,BigInt)] = (0,BigInt(7)) #:: msrn.map(t => (t._1 + 1, t._2 * 2 + 1))
val mersennePrimeStream = msrn filter(x => s(x._1, x._2) % x._2 == 0) map (_._2)
def main(args: Array[String]) = mersennePrimeStream take 10 foreach println
}