开发者

"integer constant is too large for ‘long’ type" when finding largest prime factor

开发者 https://www.devze.com 2023-02-06 20:20 出处:网络
I am working on solving Euler project 3: Description: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

I am working on solving Euler project 3:

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

This is my code to generate the answer. However I need an integer type to hold 600851475143. When I compile this on GCC on a Mac I get:

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

I expect long long could easily hold this number. I also tried making it unsigned. Why doesn't my code hold that small number and what can I do to make it work?

#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<numTo开发者_高级运维Test)   // 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;
}


Check this question. You have to specify your literal like this:

600851475143LL


As @Space_C0wb0y said, you need to specify a suffix for the literal.

Also, you're going to have a problem with your IsPrimeFactor function - the parameters are ints, but as you've already discovered, an int or even a long is not big enough to store the number you'll be passing in repeatedly...

0

精彩评论

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

关注公众号