Question:

This question already has an answer here:

<ul><li> <a href="/questions/8176928/project-euler-3-highest-prime-factor" dir="ltr" rel="nofollow">Project Euler 3 - Highest Prime Factor</a> <span class="question-originals-answer-count"> 2 answers </span> </li> <li> <a href="/questions/12025378/project-euler-3-takes-forever-in-java" dir="ltr" rel="nofollow">Project Euler #3 takes forever in Java</a> <span class="question-originals-answer-count"> 9 answers </span> </li> </ul>I am trying <a href="https://projecteuler.net/problem=3" rel="nofollow">Problem 3</a> 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:

<ul><li>Go through all the numbers from 3 until that number-1</li> <li>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.</li> <li>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++;
}
}
```

</li>
</ul>********** 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.

<hr />Answer1:You don't have to divide by every number. You only have to divide by each prime number between 2 and the square root of your number.

Answer2:The first thing you can do is only test possible factors up through the square root of the number that you're testing, because if you find a factor greater than the square root, then you should have found a factor less than the square root.

If you need additional performance, then use the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">Sieve of Eratosthenes</a>. That allows you to use the results of previous primes to cut down the work on determining if larger numbers are prime.