eBash

It is not the mountain we conquer but ourselves

Project Euler Problem 21

| Comments

Table of Contents

1 Problem

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.

2 Solution

按题意暴力求解,但我们还是能在细节进行一些优化.

  1. 我们只寻找amicable pair numbers中小的数,但相加时把两者都加上.
  2. getDivisorSum的优化
    1. 直观的,循环只要到sqrt(n)就行,因为除数是对应的,n = a * b,由反证法易知一数小于等于sqrt(n),另一数大于等于sqrt(n);
    2. 我们考虑求质数,公式( \ref{ref1} ),公式( \ref{ref2} )明显成立,公式( \ref{ref3} )左右两边展开相等可证
      getDivisorSum(p1*p2*..p_n) = 1+ p1 + p2 + ... pn + p1p2 + .. + p(n-1)p(n) + ... + p1p2..pn 
                                 = (1 + p1)(1 + p2)...(1 + pn) 
                                 = getDivisorSum(p1) * getDivisorSum(p2) * ... * getDivisorSum(pn)
      
\begin{eqnarray} getDivisorSum(p) = (p + 1)\label{ref1}\ \end{eqnarray} \begin{eqnarray} getDivisorSum(p^i) = 1 + p^2 + … + p^i = \frac{p^{i+1}-1}{p-1}\label{ref2}\ \end{eqnarray} \begin{eqnarray} getDivisorSum(p1*p2*..p_n) = getDivisorSum(p1) * getDivisorSum(p2) * …\label{ref3} \end{eqnarray}

3 Answer

31626

Source:C++

Comments