Problem 1
- 2010年 1月 21日
- 投稿者 : rei
Original
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.
和訳
10未満の自然数のうち、3 もしくは 5 の倍数になっているものは 3, 5, 6, 9 の4つがあり、 これらの合計は 23 になる。
同じようにして、1,000 未満の 3 か 5 の倍数になっている数字の合計を求めよ。
当てにならないソースコード(C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | using System; namespace ProjectEuler { class Problem1 { public Problem1() { Console.WriteLine(this.ToString()); int sum = 0; for (int i = 1; i < 1000; i++) { if (0 == i % 3 || 0 == i % 5) { sum += i; } } Console.WriteLine("> " + sum); } } } |
おそらくほとんどの人が最初に書くであろうコード。
1000までのループ中に条件に合ったものを足していくだけ。
当てにならないソースコード(F#)
1 2 3 4 5 | module Problem1 let problem1 _ = let is3or5 n = n % 3 = 0 || n % 5 = 0 [1..999] |> List.filter is3or5 |> List.sum |
0 3 5 6 9 10 12 15 18 20 21 24 25 27 30 …
[ 3 2 1 3 1 2 3 ] [ 3 2 1 3 1 2 3 ]…