title: Project Euler: Programmatic Optimization for Problem 7?
body: <p>So I would call myself a fairly novice programmer as I focused mostly on hardware in my schooling and not a lot of Computer Science courses.</p>
  <p>So I solved Problem 7 of Project Euler:</p>
  <blockquote>
  <p>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.</p>
  <p>What is the 10001st prime number?</p>
  </blockquote>
  <p>I managed to solve this without problem in Java, but when I ran my solution it took 8 and change seconds to run.  I was wondering how this could be optimized from a programming standpoint, not a mathematical standpoint.</p>
  <p>Is the array looping and while statements the main things eating up processing time? And how could this be optimized?  Again not looking for a fancy mathematical equation..there are plenty of those in the solution thread.</p>
  <p><strong>SPOILER</strong> My solution is listed below.</p>
  <pre><code>public class PrimeNumberList {
  
  private ArrayList&lt;BigInteger&gt; primesList = new ArrayList&lt;BigInteger&gt;();
  
  public void fillList(int numberOfPrimes) {
      primesList.add(new BigInteger(&quot;2&quot;));
      primesList.add(new BigInteger(&quot;3&quot;));
      while (primesList.size() &lt; 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(&quot;2&quot;));
          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);
  }
  </code></pre>
  <p>}</p>