Project Euler with Ruby on WSL [Problem 21]

どんどこ進むぞ

問題の難易度に差があるなぁ

問題

Amicable numbers

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

私訳

友愛数

d(n) を n の真の*1約数の和と定義する。 d(a) = b かつ d(b) = a で、しかも a ≠ b ならば、a, b の組を「友愛数」と呼ぶ。

例えば d(220) = 284, d(284) = 220

10000 までの友愛数の和を求めよ

解答方針

例によって素因数分解する。 本当に中学?数学だな。

合成数 c が、素因数  p_0, p_1, \cdots, p_n と 指数  \alpha_0, \alpha_1, \cdots, \alpha_n によって  \displaystyle
c = \prod_{i=0}^{n} p_i^{\alpha_i} と表せるとき、約数の和 S は  \displaystyle
S = \prod_{i=0}^{n} \sum_{j=0}^{\alpha_i} p_i^j  = \prod_{i=0}^{n} \frac{p_i^{1+\alpha_i} - 1}{p_i - 1}

ただし S は c を含むから、友愛数を考えるときは最後に S-c をする必要がある

あああああああああああああくだらないバグでハマった…。 素因数の個数を数えるとき失敗しとる

*1:つまり n 自身を含まない