[problem3]欧拉
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
注意:用long long避免类型overflow。并注意到600851475143是奇数所以只能被奇数整除。思路:在求质因子的算法基础上记一下max就好了。
View Code #include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
//bool isPrime(long long val)
//{
// long long limit = (long long)sqrt((double)val);
//
// for(long long i = 3; i <= limit; i += 2)
// {
// if(val%i == 0)
// return false;
// }
//
// return true;
//}
int _tmain(int argc, _TCHAR* argv[])
{
long long theNum = 600851475143;
// theNum can only be divided by odd number, 3, 5, 7, 9, etc.
int i = 3;
clock_t start = clock();
// By using below algorithm, it cost 2 milliseconds.
int max = 0;
while(theNum > 1)
{
if(theNum%i == 0)
{
if(i > max)
max = i;
theNum /= i;
}
i += 2;
}
cout << max << endl;
// By using this algorithm (mainly cost happens in isPrime function), it cost >1800 milliseconds.
//while(true)
//{
// if(theNum%i == 0)
// {
// long long val = theNum / i; // long long is a must to avoid overflow..
// if(isPrime(val))
// {
// cout << val << endl;
// break;
// }
// }
// i += 2;
//}
clock_t end = clock();
double spentTime = difftime(end, start);
cout << "spentTime: " << spentTime << endl;
return 0;
}
#include <cmath>
#include <ctime>
using namespace std;
//bool isPrime(long long val)
//{
// long long limit = (long long)sqrt((double)val);
//
// for(long long i = 3; i <= limit; i += 2)
// {
// if(val%i == 0)
// return false;
// }
//
// return true;
//}
int _tmain(int argc, _TCHAR* argv[])
{
long long theNum = 600851475143;
// theNum can only be divided by odd number, 3, 5, 7, 9, etc.
int i = 3;
clock_t start = clock();
// By using below algorithm, it cost 2 milliseconds.
int max = 0;
while(theNum > 1)
{
if(theNum%i == 0)
{
if(i > max)
max = i;
theNum /= i;
}
i += 2;
}
cout << max << endl;
// By using this algorithm (mainly cost happens in isPrime function), it cost >1800 milliseconds.
//while(true)
//{
// if(theNum%i == 0)
// {
// long long val = theNum / i; // long long is a must to avoid overflow..
// if(isPrime(val))
// {
// cout << val << endl;
// break;
// }
// }
// i += 2;
//}
clock_t end = clock();
double spentTime = difftime(end, start);
cout << "spentTime: " << spentTime << endl;
return 0;
}


浙公网安备 33010602011771号