Problem 21
Let d(n) be defined as the sum of proper divisors ofn (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 andb 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.
C++:
#include <iostream>
#include <cstring>
using namespace std;
#define MAXN 10000
int sum[MAXN+1];
void maketable(int n)
{
memset(sum, 0, sizeof(sum));
sum[1] = 0;
int i=2, j;
while(i<=n) {
sum[i]++;
j = i + i; /* j=ki, k>1 */
while(j <= n) {
sum[j] += i;
j += i;
}
i++;
}
}
int main()
{
maketable(MAXN);
int allsum = 0;
for(int i=1; i<=MAXN; i++)
if(sum[i] <= MAXN && i < sum[i] && sum[sum[i]] == i)
allsum += i + sum[i];
cout << allsum << endl;
return 0;
}
参考链接:I00039 亲密数