4

私はオイラープロジェクト3の解決に取り組んでいます。

Description: The prime factors of 13195 are 5, 7, 13 and 29.
             What is the largest prime factor of the number 600851475143 ?

これは答えを生成するための私のコードです。ただし、を保持するには整数型が必要600851475143です。MacのGCCでこれをコンパイルすると、次のようになります。

integer constant is too large for ‘long’ type". 

長い間、この数を簡単に保持できると思います。また、署名なしにしてみました。なぜ私のコードはその小さな数を保持しないのですか、そしてそれを機能させるために何ができますか?

#include <iostream>
#include <vector>

using namespace std;

static bool IsPrimeFactor(int numToTest,int testNum,vector<int> factors)
{
    if(numToTest%testNum==0) // is it a factor?
    {
        // see if it is a prime factor
        for(unsigned int i=0; i < factors.size(); i++)
        {
            if(testNum%factors[i]==0)  // see if this factor
            {                          //is divisble by one we have already

                return false;
            }
        }

        return true;
    }
    return false;
}

int main() {
    unsigned long long numToTest=600851475143;
    unsigned int testNum=2;  // 0 and 1 are assumed
    vector<int> factors;   

    while(testNum<numToTest)   // don't go higher than the max num
    {
        if(IsPrimeFactor(numToTest,testNum,factors)) // is it a factor?
        {
            factors.push_back(testNum); // got through prime factors 
        }                                   // and none divided it

        testNum++;
    }

    for(unsigned int i=0; i < factors.size(); i++)
    {
        cout << "factor " <<factors[i] << endl;
    }

    cout<<"Highest factor: " << factors[factors.size()-1]<<endl;

    return 0;
}
4

2 に答える 2

6

この質問を確認してください。次のようにリテラルを指定する必要があります。

600851475143LL
于 2011-01-25T11:33:52.357 に答える
1

@ Space_C0wb0yが言ったように、リテラルのサフィックスを指定する必要があります。

また、関数に問題が発生します。IsPrimeFactorパラメーターはintですが、すでに知っているように、intまたはlongでさえ、繰り返し渡す数値を格納するのに十分な大きさではありません。 。

于 2011-01-25T11:37:44.473 に答える