First shot at Euler #3 in F#, and I would like to return a boolean more elegantly than this mutable value.
// A number is prime if can only divide by itself and 1. Can only be odd.
let isPrime x =
if (x%2L = 0L) then
false
else
let mutable result = true
for i in 3L..x/2L do
if (x%i = 0L) then
result <- false
result
let a = isPrime(17L)
// True
printfn "%b" a
The L's are as I'm forcing the function to return bigints (there has to be a better way too, but 1 step at a time)....
Edit Gradbot's solution
let isPrime x =
// A prime number can't be even
if (x%2L = 0L) then
false
else
// Check for divisors (other than 1 and itself) up to half the value of the number eg for 15 will check up to 7
let maxI = x / 2L
let rec notDivisible i =
// If we're reached more than the value to check then we are prime
if i > maxI then
true
// Found a divisor so false
elif x % i = 0L then
false
// Add 2 to the 'loop' and call again
else
notDivisible (i + 2L)
// Start at 3
notDivisible 3L
you can replace the else clause with a forall:
Seq.forall (fun i -> x % i <> 0L) { 3L .. x/2L }
and then further reduce it to a single expression:
x % 2L <> 0L && Seq.forall (fun i -> x % i <> 0L) { 3L .. x/2L }
although I see no reason for treating 2 differently, you can simply do:
let isPrime x =
{ 2L .. x/2L } |> Seq.forall (fun i -> x % i <> 0L)
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.