LoginSignup
2
2

More than 5 years have passed since last update.

【ネタバレ注意】Project EulerをHaskellで思考過程から解いてみる【Problem 1】

Posted at

問題

Multiples of 3 and 5

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

環境は GHCi, version 7.10.2

解き方(ゴリ押し)

Haskellのリストの作り方から復習

Prelude> [3,6..10]
[3,6,9]

ふむふむ、これで3の倍数のリストが作れる。
楽!!

Prelude> sum[3,6..10]
18

これでリストの合計が作れる。
楽!

では、問題文の確かめ

Prelude> sum[3,6..9] + sum[5,10..10]
33

なんか、10多い

Prelude> [5,10..10]
[5,10]

原因はこいつ
10も含んでしまう

では実験。
最後の数字は10未満でも良いのかな?

Prelude> [5,10..9]
[5]

エラーが出るかも、と思ったら、無事通ってしまった。

Prelude> sum[3,6..9] + sum[5,10..9]
23

これで、無事、問題文の範囲では問題が解けた。

問題は範囲を大きくした時。
3と5の最小共倍数である15が、
このままでは被ってしまう。

だから15の倍数の合計値も引かなくてはいけない。

これをカイゼン

Prelude> sum[3,6..9] + sum[5,10..9] - sum[15,30..9]
23

このままでは範囲を毎回書き直さなくてはいけないので、
プログラミングっぽくする

Prelude> let hs n = sum[3,6..n] + sum[5,10..n] - sum[15,30..n]

ghciでやっているので、letを付けてます。

Prelude> hs 9
23
Prelude> hs 99
2318
Prelude> hs 999
233168

何となく上手く動いるっぽいですね。

解き方(数学的)

まだ確かめ中

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2