Creating an endless set of numbers
I am trying to create a prime number generator that should be able to return a sequence of primes up to the nth number. Now I figured there must be a more elegant way to do this with sequences, other than my current solution, which looks a little verbose, and I had to use mutables.
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)
+3
source to share
2 answers
just for completeness see this MSDN sequence handling . It includes this definition of 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 10
0
source to share