I am trying Problem 3 from Project Euler and my algorithm is far too slow. Does anyone know how to optimize this? The number I am trying to calculate up to is 600851475143L. It takes forever to calculate this so I need a way to speed up the calculations.
LOGIC:
- Go through all the numbers from 3 until that number-1
- For each of these numbers check if they are prime by dividing them by all the numbers in between and if they dont divide by any of them then they are prime.
If prime then add them to an array.
public static void problem3(long number){ long number2 = number; long sqrtNumber = (long)Math.sqrt(number2); int indexNum = 1; boolean isPrime = false; int primeNums[] = new int[2]; primeNums[0] = 2; //puts prime numbers into an array for(int y = 3; y < sqrtNumber; y++){ isPrime=true; for(int theNum = 2; theNum < y; theNum++){ //if y divides evenly by any number then it is not prime if(y%theNum==0){ //dont store in array isPrime=false; break; } } if(isPrime == true){ //add to array System.out.println(y); //put y in the array and exapnd the array //System.out.println("y: " + y); primeNums[indexNum] = y; int[] newArray = new int[primeNums.length + 1]; System.arraycopy(primeNums, 0, newArray, 0, primeNums.length); primeNums = newArray; indexNum++; } }
********** UPDATE **************
I calculated up to the square root which sped up the calculations a lot but I also done something else which was to add a break statement in the forloop to break once I discovered the number was not prime. I edited the code above to reflect these changes.
My algorithm is still wrong for calculating the prime factors though so I will need to have a look at it and maybe raise a new question.