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
You need to reduce the amount of checking you are doing ... think about what numbers you need to test.
For a better approach read up on the Sieve of Erathosthenes ... it should get you pointed in the right direction.
As for the reason to accepted nicf's answer:
It is OK for the problem at Euler, but does not make this an efficient solution in the general case. Why would you try even numbers for factors?
This would lead to some code like this:
n = abs(number);
result = 1;
if (n mod 2 = 0) {
result = 2;
while (n mod 2 = 0) n /= 2;
}
for(i=3; i<sqrt(n); i+=2) {
if (n mod i = 0) {
result = i;
while (n mod i = 0) n /= i;
}
}
return max(n,result)
There are some modulo tests that are superflous, as n can never be divided by 6 if all factors 2 and 3 have been removed. You could only allow primes for i.
Just as an example lets look at the result for 21:
21 is not even, so we go into the for loop with upper limit sqrt(21) (~4.6). We can then divide 21 by 3, therefore result = 3 and n = 21/3 = 7. We now only have to test up to sqrt(7). which is smaller then 3, so we are done with the for loop. We return the max of n and result, which is n = 7.
Try using the Miller-Rabin Primality Test to test for a number being prime. That should speed things up considerably.
Another approach is to get all primes up to n/2 first and then to check if the modulus is 0. An algorithm I use to get all the primes up to n can be found here.