找到最大的质因数
Finding the largest prime factor
本文关键字:质因数 更新时间:2023-10-16
我正在研究欧拉项目的以下问题。
What is the largest prime factor of the number 600851475143?
我想出了以下解决方案。
#include<iostream>
#include<cstdlib>
#include <limits>
#include <math.h>
/**Project Euler:What is the largest prime factor of the number 600851475143**/
using namespace std;
bool isPrime(int n){
int sq,a=2;
sq=sqrt(n);
while(a<sq)
{
if(n%a==0)
return false;
}
return true;
}
int main() {
int c=2,max_prime;
long long d=600851475143;
int e=sqrt(d);
while(c<e)
{
if(isPrime(c))
{
if(d%c==0)
max_prime=c;
}
c++;
}
cout<<max_prime;
return 0;
}
程序中没有编译错误,但运行需要花费大量时间。我已经查看了其他解决方案,但无法找出解决方案中的错误。我怀疑有问题,因为涉及大量。那会是什么?任何帮助表示赞赏。
你的 isPrime 函数永远不会递增a
,所以你在那里处于无限循环中。
在 isPrime
方法中,您不会更改任何控制 while
语句主体中while
条件的变量,因此循环将永远运行。