/*
Calculates the highest prime factor of 600,851,475,143.
*/
#include<iostream>
#include <cmath>
using namespace std;
bool is_prime(const unsigned long long);
int main(){
//Program assumes a is not even
const unsigned long long a=600851475143;
// const unsigned long long a=533;
// largest prime factor of 533 is 41
const unsigned long long sqrta=pow(a, 0.5);
unsigned long long sqrta_tmp = sqrta;
if((sqrta % 2) == 0) sqrta_tmp--;
const unsigned long long sqrta_madeodd = sqrta_tmp;
//to make it odd
const unsigned long long MAX = a/7-1;
// MAX needs to be odd. MAX is the largest possible prime factor
unsigned long long i;
cout << MAX <<endl;
cout << sqrta << endl;
bool found = false;
//Case 1 where the max prime factor is bigger than sqrta
//we iterate over the lower factor because then we only need to have
//sqrt iterations
//Note the increasing order of the loop
for(i=7; i <sqrta; i= i+2){
if((a%i == 0) && is_prime(a/i)){
found = true;
cout <<"The largest prime factor of " <<a <<" is " <<a/i <<endl;
return 0;
}
}
//Case 2 where the max prime factor is less than or equal to sqrta
//Note the decreasing order of the loop
//And note the odd starting number
for(i= sqrta_madeodd; i >=7; i= i-2){
if((a%i == 0) && is_prime(i)){
found = true;
cout <<"The largest prime factor of " <<a <<" is " <<i <<endl;
return 0;
}
}
//if we are here then no prime factor found.
cout <<a <<" is a prime." <<endl;
return 0;
}
bool is_prime(const unsigned long long num) {
// checks if num is prime, given odd num geq 3
unsigned long long fac;
const unsigned long long fac_max = pow(num, 0.5);
//max factor to check for in prime test
cout <<"Checking for primality " << num << endl;
for(fac=3; fac <=fac_max; fac= fac+2)
if((num % fac) == 0) {
cout <<"Factor in primality: ";
cout << fac <<endl;
return(false);
}
return true;
}