Generating an infinite set of numbers

110 views Asked by At

I'm trying to make a prime number generator which should be able to return a sequence of prime numbers up to the nth number. Now I figured there should be a more elegant way to do this with sequences besides my current solution which feels a bit 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)
2

There are 2 answers

2
John Palmer On BEST ANSWER

A simple solution using filter

let t = Seq.initInfinite id |> Seq.filter isPrime |> Seq.take n
0
sgtz On

just for completeness see this MSDN treatment of sequences. It includes this isPrime definition

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