Project Euler # 1
Haskellの勉強がてら、Project Eulerを解いてみる。
Multiples of 3 and 5
https://projecteuler.net/problem=1
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.
意訳)1000未満の3もしくは5の倍数の合計を示せ
below 10
で10未満、以下の場合は10 or below
と表すらしい。
Haskell
main = do
print $ sum (filter (\x -> mod x 3 == 0 || mod x 5 == 0) [1..999])
C#
using System;
using System.Linq;
public class Test
{
public static void Main()
{
Console.WriteLine(Enumerable.Range(1, 999).Where(i => i % 3 == 0 || i % 5 == 0).Sum());
}
}
Python
print(sum([i for i in range(1, 1000) if i % 3 == 0 or i % 5 == 0]))
Ruby
puts (1...1000).select { |i| (i % 3).zero? || (i % 5).zero? }.inject(:+)
JavaScript
console.log([...Array(1000).keys()].filter(i => i % 3 == 0 || i % 5 == 0).reduce((c, i) => c + i));
C#のSum()
の圧倒的楽さ、HaskellとPythonがスッと入ってこないのは慣れなのかなぁ…
JSはRange
を用意すべし