简体   繁体   中英

F# Trying to generate a list of prime numbers

let isPrime n =
    let rec check i =
        i > n/2 || (n % i <> 0 && check (i + 1))
    check 2

let rec Primes t =

   [ for n in 1..t do if isPrime n then yield n]


//[<EntryPoint>]
let main argv =
    printfn "Testing Exercise 16: Primes"

    test (lazy (Primes 1)) [] NoException
    test (lazy (Primes 2)) [2] NoException
    test (lazy (Primes 4)) [2;3] NoException
    test (lazy (Primes 11)) [2;3;5;7;11] NoException
                
    printfn ""
    0 // return an integer exit code

I'm new to F#, but why is it generating a list from 1-t instead of a list of prime numbers

If you run your Primes function on its own:

> Primes 11;;
val it : int list = [1; 2; 3; 5; 7; 11]

You are getting 1 as a prime when you shouldn't, the for should be from 2 not from 1.

Also:

  • there is no need to for Primes to be declared as rec , it isn't calling itself recursively
  • i > n/2 , you only need to check i up to the square root on n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM