1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
long LargestPrimeFactor(long n)
{
long rem = 1;
long prime_factor = 1;
int simples[] = {2, 3, 5};
for (int& i : simples)
{
while (n%i == 0)
{
prime_factor = i;
rem = n/=i;
}
}
// Toggles incrementing by 4 or 2
bool toggle = true;
long search = sqrt(n);
for (long i=7; i<=search; i+=2)
{
while (n%i == 0)
{
prime_factor = i;
rem = n/=i;
search = sqrt(n);
}
if (toggle)
i+=2;
toggle = !toggle;
}
return (rem==1 && prime_factor==1) ? n : max(rem, prime_factor);
}
//The prime factors of 13195 are 5, 7, 13 and 29.
//what is the largest prime factor of the number 600851475143 ?
int main()
{
vector<long> examples =
{
100,
326,
1693, // Prime
2282,
13195,
13197,
13199,
13201,
13203,
13207,
13209,
13211,
13213,
13217, // Prime
600851475143,
999998727899999 // Prime
};
for (auto& e: examples)
{
cout << e << ": " << LargestPrimeFactor(e) << endl;
}
}
|