【ProjectEuler】ProjectEuler_021

// 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.

#include <iostream>
#include <windows.h>
using namespace std;

const int MAX_NUM = 10000;
int number[MAX_NUM + 1];

//获取某数亲和数
int GetAmicableNum(int num)
{
    //寻找此数的亲和数
    int amicableNum = 0;

    for(int i = num / 2; i >= 1; i--)
    {
        if(num % i == 0)
        {
            amicableNum += i;
        }
    }

    //记录此数的亲和数
    number[num] = amicableNum;

    //返回亲和数
    return amicableNum;
}

void F1()
{
    cout << "void F1()" << endl;

    LARGE_INTEGER timeStart, timeEnd, freq;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&timeStart);

    int result = 0;	//亲和数的数目
    int tempAmicableNum = 0;

    for(int i = 1; i <= MAX_NUM; i++)
    {
        tempAmicableNum = GetAmicableNum(i);

        //是亲和数
        if(tempAmicableNum <= MAX_NUM && number[tempAmicableNum] == i && tempAmicableNum != i)
        {
            cout << number[i] << " " << i << endl;
            result += i + tempAmicableNum;
        }
    }

    cout << MAX_NUM << "以内的亲和数之和为" << result << endl;


    QueryPerformanceCounter(&timeEnd);
    cout << "Total Milliseconds is " << (double)((double)(timeEnd.QuadPart - timeStart.QuadPart) * 1000 / (double)freq.QuadPart) << endl;
}

//主函数
int main()
{
    F1();
    return 0;
}

/*
void F1()
220 284
1184 1210
2620 2924
5020 5564
6232 6368
10000以内的亲和数之和为31626
Total Milliseconds is 216.438

By GodMoon
*/

你可能感兴趣的:(Integer,less,each,pair,Numbers)