我正在尝试做一个素数生成器,它应该能够返回到第n个数的素数序列。现在,我想,除了我目前的解决方案之外,应该有一种更优雅的方法来处理序列,这感觉有点冗长,我不得不使用可变变量。
0
|> Seq.unfold (fun x -> if isPrime x
then Some(x, x + 1)
else
let mutable y = x
while isPrime y <> true do
y <- y + 1
Some(y, y + 1))
|> Seq.take(n)发布于 2014-11-16 10:49:17
一种使用过滤器的简单解决方案
let t = Seq.initInfinite id |> Seq.filter isPrime |> Seq.take n发布于 2014-11-16 13:30:50
为了完整起见,请参阅此序列的MSDN处理。它包括这个isPrime定义。
let isPrime n =
let rec check i =
i > n/2 || (n % i <> 0 && check (i + 1))
check 2
let t2 n = seq { for n in 1..100 do if isPrime n then yield n }
t2 10https://stackoverflow.com/questions/26956101
复制相似问题