Thus, I would call myself a fairly novice programmer, since I mainly focused on the hardware in my school, and not many courses in computer science.
So, I solved the 7 Project Euler task:
Having listed the first six prime numbers: 2, 3, 5, 7, 11, and 13, we will see that the 6th prime number is 13.
What is the 10001st number of primes?
I managed to solve this problem without any problems in Java, but when I launched my solution, it took 8 and the number of seconds to execute changed. I was wondering how this can be optimized from a programming point of view, and not from a mathematical point of view.
Are array loop cycles and while operations the main ones of which are processing time? And how can this be optimized? Again, don't look for a fancy math equation. There are many solutions in the flow of decisions.
SPOILER My solution is given below.
public class PrimeNumberList {
private ArrayList<BigInteger> primesList = new ArrayList<BigInteger>();
public void fillList(int numberOfPrimes) {
primesList.add(new BigInteger("2"));
primesList.add(new BigInteger("3"));
while (primesList.size() < numberOfPrimes){
getNextPrime();
}
}
private void getNextPrime() {
BigInteger lastPrime = primesList.get(primesList.size()-1);
BigInteger currentTestNumber = lastPrime;
BigInteger modulusResult;
boolean prime = false;
while(!prime){
prime = true;
currentTestNumber = currentTestNumber.add(new BigInteger("2"));
for (BigInteger bi : primesList){
modulusResult = currentTestNumber.mod(bi);
if (modulusResult.equals(BigInteger.ZERO)){
prime = false;
break;
}
}
if(prime){
primesList.add(currentTestNumber);
}
}
}
public BigInteger get(int primeTerm) {
return primesList.get(primeTerm - 1);
}
}
source
share