Project euler problem 21找合适的一对数之总和

Amicable numbers

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.


Answer:
31626
Completed on Mon, 7 Oct 2013, 09:27

这个比较容易,而省时提高效率是这道题的本质。

#include <iostream>
#include <map>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int f[10002]={0};
int cmp(int n)
{
    int i,sum=0;
    for(i=1;i<=n/2;i++)  //最大能被自身整除的就是它的二分之一
        if(n%i==0) sum+=i;
    return sum;
}
int main()
{
    int i,s,sum=0;
    for(i=1;i<=10000;i++)
    {
        s=cmp(i);
        if(f[i]==0&&s!=i&&cmp(s)==i)  //两个数不能相等,f[i]标记已经找到的,因为可能会重复,这样可以提高效率,省时!
            sum+=i+s;
        f[i]=1;      //f[i]标记已经找到的,因为可能会重复,这样可以提高效率,省时!
        if(s<=10000) f[s]=1;
    }
    cout<<sum<<endl;  //最后结果
    return 0;
}

你可能感兴趣的:(Project euler problem 21找合适的一对数之总和)