Project Euler with Ruby on WSL [Problem 1]

問題1

ネタばれありありで行きます。 ということで一応下は隠しましょう

[問題文(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の倍数の和を求めよ

解答の前に WSL 的な

ファイルシステムがよく分らないので調べる。 ふつーに explorer が起動するのか面白い。

$ explorer .

おお。便利便利。

解答

まず、「1 から n までの k の倍数の和」を考える。 これは k, 2k, 3k, ... の和を n まで取るということで、つまり  \displaystyle
  \sum_{i=1}^{\lfloor n/k \rfloor} ki = k\cdot\sum_{i=1}^{\lfloor n/k \rfloor}i = k\cdot\frac{(\lfloor n/k \rfloor + 1)(\lfloor n/k \rfloor )}{2}

そして、3 の倍数と 5 の倍数の和から、15 の倍数の和を引き去ればよいので

# Project Euler
# problem 1

# sum of k's multiples from 1 to n
def multiples(k, n)
    last = n / k
    k * last * (last + 1) / 2 
end

puts multiples(3,1000) + multiples(5,1000) - multiples(15,1000)

あーこれだと below になってない。 小手先で last = (n-1) / k としよう