我试图找到数字 600851475143 的最大质因数。我的代码适用于我测试的较小数字(低于 100)。然而,当遇到 600851475143 时,它返回 4370432,绝对不是质数。知道我的代码可能有什么问题吗?
#include <iostream>
#include <time.h>
#include <math.h>
using namespace std;
int main()
{
int num;
int largest;
int count;
cout<<"Please enter a number to have its Largest Prime Factor found"<<endl;
cin>>num;
num = 600851475143;
for (int factor = 1; factor <= num; factor++)
{
if (num % factor == 0)
{
count = 0;
for (int primetest=2; count == 0 && factor > primetest ; primetest++)
{
if (factor % primetest == 0)
count ++;
//endif
}
if (count == 0)
largest = factor;
//endif
}
}//endif
cout<<largest<<endl;
system("PAUSE");
}
最佳答案
num = 600851475143;
此处发生整数溢出。 num
的大小不足以包含您提供的值。
使用uint64_t
。
#include <cstdint> //must include this!
uint64_t num = 600851475143;
读这个:cstdint
关于c++ - 最大质因数 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7062442/