![](/img/trans.png)
[英]integer constant is too large for ‘long’ type when searching for large primes
[英]“integer constant is too large for ‘long’ type” when finding largest prime factor
我正在解決Euler項目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;
}
檢查這個問題。 您必須像這樣指定文字:
600851475143LL
正如@ Space_C0wb0y所說的,您需要為文字指定后綴。
另外,您的IsPrimeFactor
函數IsPrimeFactor
遇到問題-參數為整數,但是正如您已經發現的那樣,一個整數甚至一個long都不足以存儲您將反復傳遞的數字。 ..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.