开发者

How do I solve Euler problem 12? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Project Euler Problem 12 - C++

I've been working on Euler problems and hit a wall with problem 12. I read up on some mathematical solutions for large numbers but I'm still not getting the right answer. This is my code:

#include <iostream>
using namespace std;

int divisorCount(const unsigned long long x)
{
    int divizers = 0;
    unsigned long long i = 1;
    while(i <= x/i)
    {
        if(x % i == 0)
        {
            divizers++;
        }
        i++;
    }
    return divizers;
}

int main()
{
    bool test;
    unsigned long long total = 0, spread = 1;
    int divisors = 1;

    while(divisors < 501)
    {
        total+=spread;
        divisors = divisorCount(to开发者_如何学Pythontal);
        spread++;
        if(divisors > 501)
            cout << total << " " << spread << " " << divisors << endl;
    }


    cout << total << " is divisible by 500+ numbers" << endl;
    system("pause");
    return 0;
}

Any suggestions?


there are divisors for x above sqrt(x), so fix this:

while(i <= x/i)

to:

while(i <= x)

also, do spread++; after the printing so it shows the correct number.

Note: for testing it's good idea to remove the if before the printing so you see what's going on.

Note2: a lot quicker way to solve this is to realise the properties of those numbers, see: triangular numbers. The Euler project is heavily math based, so don't code brute-force solutions.


Think about your if statement:

if(x % i == 0)
{
    divizers++;
}

Since i is a factor of x, what other factor of x can you immediately write down? If 3 is a factor of 24, what other factor of 24 do you know? There is a hidden catch in this hint, just so you are aware.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜