当找到最大素数因子时,"整数常数对于'long'类型来说太大了"

Mae*_*024 4 c++ prime-factoring

我正在努力解决欧拉项目3:

Description: The prime factors of 13195 are 5, 7, 13 and 29.
             What is the largest prime factor of the number 600851475143 ?
Run Code Online (Sandbox Code Playgroud)

这是我生成答案的代码.但是我需要一个整数类型来保存600851475143.当我在Mac上的GCC上编译它时,我得到:

integer constant is too large for ‘long’ type". 
Run Code Online (Sandbox Code Playgroud)

我希望很久很久就可以很容易地掌握这个数字 我也试过让它没有签名.为什么我的代码不能容纳那么少的数字,我该怎么做才能使它工作?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Bjö*_*lex 6

检查这个问题.你必须像这样指定你的文字:

600851475143LL
Run Code Online (Sandbox Code Playgroud)