0

我想先说我还不太擅长编程,可能有更好的方法来做我想做的事。如果看到如此公然糟糕的事情让你烦恼,那么继续前进。

我一直在尝试欧拉计划的第三个问题,即“找到 600851475143 的最大素数”。首先,我做了一些计算数字因数的东西。(对不起名字,我什么都想不起来。)

#include <iostream>

using namespace std;

void Factor (double dFactorer)
{
    long dUpperlimit;
    dUpperlimit = (int)dFactorer/2;
    float fnumTouse;
    fnumTouse = 1;
    int nCounter;
    nCounter = 0;
    while (fnumTouse <= dUpperlimit)
    {
        if ((long)dFactorer % (long)fnumTouse == 0)
        {
            cout << fnumTouse << endl;
            fnumTouse++;
            nCounter++;
        }
        else
        {
            fnumTouse++;
        }
    }
    cout << dFactorer << endl;
    cout << "There are " << nCounter + 1 << " factors in this number";
}

int main()
{
    double dNumtofac;
    cout << "Enter a number to factor: ";
    cin >> dNumtofac;
    cout << endl;
    Factor (dNumtofac);
    return 0;
}

好吧,所以,我知道这是一个非常糟糕的工作,我必须做所有的演员才能让某些事情发挥作用。它适用于较小的数字,但任何大约 1 亿的数字都使它在完全停止之前只输出一定数量的因子。我试了题号,它的输出就是数字本身,说这个600851475143只有一个因素。我想知道为什么会这样说,是不是和我使用的变量的限制有关? 还有什么?我没有足够的知识来解决这个问题。

4

1 回答 1

0
#include <iostream>

using namespace std;

int main()
{
long long n=0;
//to do: verify that the number is positive and below the limit of long long
cout <<"The number to factor : ";
cin  >>n;
long long aux = n%2==0 ? 2 : 1;
for (long long i=3;i<=n/2;i+=2)
    if(n%i==0)
         aux = aux>n/i ? aux : n/i;
cout<<"Greatest factor = "<<aux;
return 0;
}

当然,您可以通过使 for 从高到低并在第一次出现因素时停止来大大改善这一点。不要忘记验证 n/2 是奇数还是偶数。(没有测试代码)。

于 2013-11-20T12:12:16.150 回答