Ray's playground

 

Project Euler Problem 21

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.

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int SumOfDivisors(int num)
 6 {
 7     int sum = 1;
 8     for(int i=2; i<sqrt((float)num); i++)
 9     {
10         if(num % i == 0)
11         {
12             sum += i + num /i;
13         }
14     }
15     return sum;
16 }
17 
18 int main()
19 {
20     long sum = 0;
21     for(int i=1; i<10000; i++)
22     {
23         int value = SumOfDivisors(i);
24         if(value != i && SumOfDivisors(value) == i)
25         {
26             sum += i;
27         } 
28     }
29 
30     cout << sum << endl;
31     cin.get();
32 }

posted on 2011-03-11 22:40  Ray Z  阅读(194)  评论(0编辑  收藏  举报

导航