I'm attempting problem 7 on Project Euler. It is asking for the 10,001th prime number. Now, in my head I have a good idea on how to tackle this one systematically, but I'm having a hard time translating this into code. My method for finding this prime number is this (please tell me if there are any flaws in my logic!):

Any number that is not prime can be broken up into smaller prime numbers. Thus, if some number n cannot be divided evenly into any of the prime numbers smaller than it, then n must be a prime number. With that being said, one could identify the 10,001th prime number by starting at 2, adding 1 (3), and checking to see if this number can be divided evenly by 2. Since 3 cannot be divided evenly by 2, it is also prime and can be added to the "prime list". Then the next number, 4, could be checked by dividing it by 2 and 3. Since it can be divided by at least one of these numbers (2), then it is not prime. Then 5 would be checked, and since it cannot be evenly divided by 2 or 3, it is prime and would be added to the list. This process would continue until 10001 prime numbers are present in the list, and the final one would be the answer.

I know that was probably an unnecessary explanation, but I wanted to give a clear explanation of my intention behind writing my code. So..here it is:

package find.a.prime.number; import java.util.Scanner; public class FindAPrimeNumber { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[] numberOfprimes = new int[10001]; numberOfprimes[0] = 2; int test = 3; int numberIndices = 0; int b = 0; int a = 0; while(numberIndices <= 10001){ while(b <= numberIndices){ if(test%numberOfprimes[b]!= 0){ if(b == numberIndices){ numberOfprimes[b] = a; numberIndices = numberIndices + 1; } b = b + 1; } else{ test = test + 1; break; } } b=1; } System.out.println("The 10,001st prime number is " + test); } }

Alright, so here are my two questions..

1) Am I even approaching this correctly? If not, feel free to nudge me in the right direction. And by nudge, I do not mean "give me the answer". I'd like to figure this out on my own.

2) When I compile this program, it says that I can't "divide by zero" on the line "if(test%numberOfprimes[b] != 0){". Why is it doing that? When does numberOfprimes[b] ever equal zero?

Thanks in advance for taking your time reading this! And again, try not to judge me too harshly! I just started learning this a couple days ago, so I'm still very much a novice..

-Jacob

This post has been edited by **jacobsnakob94**: 02 October 2011 - 07:00 PM