I'm trying Euler problem 3 on http://projecteuler.net/ for fun. I think I have a program that works (with very small numbers), but it takes too long. Can anyone give me some hints to improve speed?
/**
* The prime factors of 13195 are 5, 7, 13 and 29.
* What is the largest prime factor of the number 600851475143 ?
*
* Start from 600851475143 and count backwards, looking for factors. Every time
* you get a factor, check to see if it is prime. The first prime factor starting
* for the top is the largest prime factor.
*/
public class Euler3
{
public static void main(String[] args)
{
Euler3 euler3 = new Euler3();
euler3.getLargestPrimeFactor();
}
public void getLargestPrimeFactor()
{
long number = 26;
boolean primeFactor = false;
boolean factorFound = false;
long originalNumber = number;
long factor = 0;
long index = originalNumber - 1;
while (!primeFactor)
{
while (!factorFound && index > 1)
{
if ( originalNumber % index == 0 )
{
factor = index;
factorFound = true;
}
index--;
}
if (isPrime(factor) == true)
primeFactor = true;
}
System.out.println( factor );
}
public boolean isPrime(long number)
{
boolean isNotPrime = false;
long primeCheck = number - 1;
while ( primeCheck > 1 && !isNotPrime )
{
if ( number % primeCheck == 0 )
{
isNotPrime = true;
}
primeCheck--;
}
if (!isNotPrime)
return true;
else
return false;
}
}
For instance, it will get that 13 is the largest prime factor of 26 just fine, but bigger numbers it can't compute within a reasonable amount of time. In particular I think my math probably isn't up to snuff for this problem, I feel like my solution was very.....roundabout.