我写了一个函数,使用流无限期地生成质数(维基百科:Erastothenes的增量筛).它返回一个流,但它也在内部合并素数倍流以标记即将到来的复合.如果我自己这样说,这个定义简洁,实用,优雅且易于理解:
def primes(): Stream[Int] = {
def merge(a: Stream[Int], b: Stream[Int]): Stream[Int] = {
def next = a.head min b.head
Stream.cons(next, merge(if (a.head == next) a.tail else a,
if (b.head == next) b.tail else b))
}
def test(n: Int, compositeStream: Stream[Int]): Stream[Int] = {
if (n == compositeStream.head) test(n+1, compositeStream.tail)
else Stream.cons(n, test(n+1, merge(compositeStream, Stream.from(n*n, n))))
}
test(2, Stream.from(4, 2))
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试生成第1000个素数时,我得到了"java.lang.OutOfMemoryError:超出GC开销限制".
我有一个替代解决方案,它在primes上返回一个迭代器,并在内部使用元组的优先级队列(multiple,prime用于生成多个)来标记即将到来的复合.它运行良好,但它需要大约两倍的代码,我基本上不得不从头重新开始:
import scala.collection.mutable.PriorityQueue
def primes(): Iterator[Int] = {
// Tuple (composite, prime) is used to generate …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个函数,该函数接受一个Int并返回直到该Int的所有素数。
例如“ 8的素数列表” = List(3,5,7)
这是我到目前为止所拥有的:
def isPrime(i: Int): Boolean = {
if (i <= 1)
false
else if (i == 2)
true
else
!(2 to (i - 1)).exists(x => i % x == 0)
} //> isPrime: (i: Int)Boolean
def getListOfPrimesToN(n : Int) = {
}
Run Code Online (Sandbox Code Playgroud)
对于功能getListOfPrimesToN,我打算1.创建一个大小为n的列表“ l”,并使用介于0到n之间的元素填充它。2.调用“ l”的映射函数,并为List中的每个元素调用isPrime。
如何创建元素1到N的列表?
用于返回所有质数直至(包括Int N)欢迎数的任何其他解决方案。
我想检查一个数字是否为素数.我编写了以下代码,但它没有返回任何值:
def isprime(x:Int) = {
| if (x==1) false
| else {
| for (i <- 2 to x-1) {
| if (x % i == 0) false
| else true
| }
| }
| }
Run Code Online (Sandbox Code Playgroud)