F# Returning a Boolean -
first shot @ euler #3 in f#, , return boolean more elegantly mutable value.
// number prime if can divide , 1. can odd. let isprime x = if (x%2l = 0l) false else let mutable result = true in 3l..x/2l if (x%i = 0l) result <- false result let = isprime(17l) // true printfn "%b" the l's i'm forcing function return bigints (there has better way too, 1 step @ time)....
edit gradbot's solution
let isprime x = // prime number can't if (x%2l = 0l) false else // check divisors (other 1 , itself) half value of number eg 15 check 7 let maxi = x / 2l let rec notdivisible = // if we're reached more value check prime if > maxi true // found divisor false elif x % = 0l false // add 2 'loop' , call again else notdivisible (i + 2l) // start @ 3 notdivisible 3l
you can replace else clause forall:
seq.forall (fun -> x % <> 0l) { 3l .. x/2l } and further reduce single expression:
x % 2l <> 0l && seq.forall (fun -> x % <> 0l) { 3l .. x/2l } although see no reason treating 2 differently, can do:
let isprime x = { 2l .. x/2l } |> seq.forall (fun -> x % <> 0l)
Comments
Post a Comment