第一次使用 F# 中的Euler #3,我想返回一个比这个可变值更优雅的布尔值。
// 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
L 是因为我正在强制函数返回 bigints(也必须有更好的方法,但一次只有一步)......
编辑 Gradbot 的解决方案
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