I\'m trying to work through Project Euler and I\'m hitting a barrier on problem 03. I have an algorithm that works for smaller numbers, but problem 3 uses a very, very large
Easy peasy in C++:
#include <iostream>
using namespace std;
int main()
{
unsigned long long int largefactor = 600851475143;
for(int i = 2;;)
{
if (largefactor <= i)
break;
if (largefactor % i == 0)
{
largefactor = largefactor / i;
}
else
i++;
}
cout << largefactor << endl;
cin.get();
return 0;
}
you might want to see this: Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer?
and I like lill mud's solution:
require "mathn.rb"
puts 600851475143.prime_division.last.first
I checked it here
Once you find the answer, enter the following in your browser ;)
http://www.wolframalpha.com/input/?i=FactorInteger(600851475143)
Wofram Alpha is your friend
Although the question asks for the largest prime factor, it doesn't necessarily mean you have to find that one first...
long n = 600851475143L; //not even, so 2 wont be a factor
int factor = 3;
while( n > 1)
{
if(n % factor == 0)
{
n/=factor;
}else
factor += 2; //skip even numbrs
}
print factor;
This should be quick enough...Notice, there's no need to check for prime...
The way I did it was to search for primes (p
), starting at 2 using the Sieve of Eratosthenes. This algorithm can find all the primes under 10 million in <2s on a decently fast machine.
For every prime you find, test divide it into the number you are testing against untill you can't do integer division anymore. (ie. check n % p == 0
and if true, then divide.)
Once n = 1
, you're done. The last value of n
that successfully divided is your answer. On a sidenote, you've also found all the prime factors of n
on the way.
PS: As been noted before, you only need to search for primes between 2 <= n <= sqrt(p)
. This makes the Sieve of Eratosthenes a very fast and easy to implement algorithm for our purposes.