c++ - 如何解决欧拉问题 12?

标签 c++

<分区>

Possible Duplicate:
Project Euler Problem 12 - C++

我一直在研究欧拉问题,但遇到问题 12 时碰壁了。我阅读了一些大数的数学解决方案,但仍然没有得到正确的答案。这是我的代码:

#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(total);
        spread++;
        if(divisors > 501)
            cout << total << " " << spread << " " << divisors << endl;
    }


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

有什么建议吗?

最佳答案

x 在 sqrt(x) 之上有除数,所以解决这个问题:

while(i <= x/i)

到:

while(i <= x)

此外,在打印后执行 spread++; 以显示正确的数字。

注意:为了进行测试,最好在打印之前删除 if,这样您就可以看到发生了什么。

注意 2:解决这个问题的更快方法是了解这些数字的属性,请参阅:triangular numbers . Euler 项目非常依赖数学,所以不要编写暴力解决方案。

关于c++ - 如何解决欧拉问题 12?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6937888/

相关文章:

c++ - _declspec 和 __declspec 之间的区别?

c++ - 在 Windows 中执行全屏抓取

c++ - MySQL C++ 连接器内存溢出错误

c++ - 'DLLVERSIONINFO' 将项目从 VS2008 更新到 VS2012 后出现编译错误

c++ - 在没有括号的宏中使用逗号 : How can I mix and match with a template?

c++ - 我可以使用 std::vector 作为模板参数还是必须是 std::vector<T>?

c++ - 一些固定数字的排列

c++ - 设置为值的指针和设置为值地址的指针有什么区别?

c++ - std::vector<A> error C2582: 'operator =' 函数在

C++ : Function return String in Static Library give Error : expected '=' , ',' , ';' , 'asm' 或 '__attribute__' token 之前的 ':'