Reputation: 1
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
Upvotes: 0
Views: 199
Reputation: 5657
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:
Primes
to be declared as rec
, it isn't calling itself recursivelyi > n/2
, you only need to check i
up to the square root on n
Upvotes: 1