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
|
#include <iostream>
#include <cmath>
using std::cout;
//if you have C++11 then use uint64_t in cstdint
typedef unsigned long long uint64_t;
void shrink(uint64_t& n, uint64_t i, uint64_t& lpf, uint64_t& stop)
{
lpf = i;
while (n%i==0) { n/= i; }
stop = ceil(sqrt(n));
}
uint64_t largest_prime_factor(uint64_t n)
{
uint64_t lpf = 0;
uint64_t stop = ceil(sqrt(n)); //should have ceil() or +1
if (n%2==0) { shrink(n, 2, lpf, stop); }
if (n%3==0) { shrink(n, 3, lpf, stop); }
for (uint64_t i=7; i<=stop; i+=6) //i ~ 6k+1
{
uint64_t j = i-2; //j ~ 6k-1
if (n%j==0) { shrink(n, j, lpf, stop); }
if (n%i==0) { shrink(n, i, lpf, stop); }
}
return n==1 ? lpf : n;
}
int main()
{
cout << largest_prime_factor(2147483647) << "\n";
cout << largest_prime_factor(4294967291) << "\n";
cout << largest_prime_factor(4294967294) << "\n";
cout << largest_prime_factor(65536) << "\n";
cout << largest_prime_factor(2*2*2*7*13*19) << "\n";
//cout << largest_prime_factor(2147483647ULL*2147483647ULL) << "\n";//28s
//cout << largest_prime_factor(9223372036854775783ULL * 2) << "\n"; //44s
//cout << largest_prime_factor(18446744073709551557ULL) << "\n"; //71s
}
|