No.9
A Pythagorean triplet is a set of three natural numbers, a b
c, for which, a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Haskell:
answer9Slow = head [ a*b*c | a <- [1..1000], b <- [a..1000], c <- [b..1000], a^2 + b^2 == c^2, a + b + c == 1000 ]
-- a2 + b2 = (1000 - a - b)^2, after reduce it is a little faster, but still slow for it won't jump out when the correct answer is found.
answer9 = head [ a*b*(1000-a-b) | a <- [1..1000], b <- [a..1000], 2000*(a+b) - 2*a*b == 1000^2 ]
F# :
let answer9slow =
let ans = ref 0
for a in [0..1000] do
for b in [a..1000] do
if 2000*(a+b) - 2*a*b = 1000000 then ans := a*b*(1000-a-b)
!ans
let answer9 =
let mutable a = 1
let ans = ref 0
let exit = ref false
while (not !exit) do
for b in [a..1000] do
if 2000*(a+b) - 2*a*b = 1000000 then exit := true; ans := a*b*(1000-a-b)
a <- a + 1
!ans
Answer: 31875000
后语:怀念 break 与 goto .
No10.
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Haskell:
-- 'primes' is defined in question No7. it is a set of all prime numbers include 1.
-- Note: this is very slow.
answer10 = (sum . takeWhile ( < 2000000) $ primes) - 1
F#:
let isPrime64 n=
let upper = uint64 (sqrt (float n))
let rec auxPrime n m = if n % m = 0UL then false
elif m > upper then true
else auxPrime n ( m + 1UL )
auxPrime n 2UL
let answer10 =
Seq.unfold (fun state ->
if state > 2000000UL then None
elif isPrime64 state then Some (state, state + 1UL)
else Some (0UL, state + 1UL) ) 2UL
|> Seq.sum |> (+) 2UL
Answer: 142913828922
后语: 2 也是素数, isPrime64 没定义好,需改进。