projectEuler第三问:
13195的质因数是5,7,13和29。
600851475143的最大质因数是多少?
Haskell:
primes (x:xs) = x:primes [m|m<-xs,m `mod` x /= 0]
findBiggestFactor n primes
| factor==n = n
| otherwise = findBiggestFactor (n `div` factor) restPrimes
where restPrimes@(factor:rest) = dropWhile (\p->n `mod` p /=0) primes
answer = findBiggestFactor 600851475143 (primes [2..])
_ 顺便鄙视一下c++:
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include "util.h"
using namespace std;
const unsigned long long NB= 317584931803ULL;
long ProchainDiviseur(const unsigned long long& p_nb, const vector<long> p_nbPremiers){
long nb= 0;
for (int i= 0; i != p_nbPremiers.size() && nb == 0; ++i){
if (p_nb % p_nbPremiers[i] == 0)
nb= p_nbPremiers[i];
}
return nb;
}
long LargestPrimeFactor(const unsigned long long& p_nb){
long largestPrimeFactor= 0;
unsigned long long nbEnCours= NB;
vector<long> nbPremiers= ConstruireNbPremiers((int)sqrt((double)p_nb / 2));
long facteurPremierEnCours= 0;
do{
facteurPremierEnCours= ProchainDiviseur(nbEnCours, nbPremiers);
if (facteurPremierEnCours != 0){
nbEnCours/= facteurPremierEnCours;
}
if (facteurPremierEnCours > largestPrimeFactor)
largestPrimeFactor= facteurPremierEnCours;
}while (facteurPremierEnCours != 0);
return largestPrimeFactor;
}
int main(){
cout << LargestPrimeFactor(NB) << '\n';
return 0;
}
网友评论