Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating an infinite set of numbers

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)
like image 483
Overly Excessive Avatar asked Nov 19 '25 03:11

Overly Excessive


1 Answers

A simple solution using filter

let t = Seq.initInfinite id |> Seq.filter isPrime |> Seq.take n
like image 158
John Palmer Avatar answered Nov 21 '25 09:11

John Palmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!