Project Euler -- 欧拉题集 F#及Haskell 版 - No.9, No.10


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


Answer31875000

后语:怀念 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 没定义好,需改进。








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值