Trying to calculate the 10001st prime number in Java.
Posted
by user247679
on Stack Overflow
See other posts from Stack Overflow
or by user247679
Published on 2010-03-21T02:23:12Z
Indexed on
2010/03/21
2:31 UTC
Read the original article
Hit count: 475
Greetings. I am doing Problem 7 from Project Euler. What I am supposed to do is calculate the 10001st prime number. (A prime number being a number that is only divisible by itself and one.)
Here is my current program:
public class Problem7 {
public static void main(String args []){
long numberOfPrimes = 0;
long number = 2;
while (numberOfPrimes < 10001){
if(isPrime(number)){
numberOfPrimes++;
}
number++;
}
System.out.println("10001st prime: "+ number);
}
public static boolean isPrime(long N)
{
if (N <= 1) return false;
else return Prime(N,N-1);
}
public static boolean Prime(long X,long Y)
{
if (Y == 1) return true;
else if (X % Y == 0) return false;
else return Prime(X, Y-1);
}
}
It works okay with finding, say the 100th prime number, but when I enter very large numbers such as 10001 it causes a stack overflow. Does anyone know of a way to fix this? Thanks for reading my problem!
© Stack Overflow or respective owner