I made a little program that finds all prime numbers from 0 - 5000, but the program crashes after about a number of recursions which gives me this error:
at main.LargePrimeNumber.recursion(LargePrimeNumber.java:37)
What is causing this? My first guess is that my RAM fills up and crashes, but that doesn't make too much sense seeing as everything else is still running. My second idea is that my IDE (eclipse neon) has a max limit or that recursion overloads my IDE so it throws errors.
Below is my code
import java.util.ArrayList;
public class LargePrimeNumber {
static ArrayList<Integer> PrimeDataBase = new ArrayList<Integer>();
static int cd = 12; //current digit that is being compared to see if it's prime
public static void main(String[] args){
PrimeDataBase.add(2);
PrimeDataBase.add(3);
PrimeDataBase.add(5);
PrimeDataBase.add(7);
PrimeDataBase.add(11);
recursion(PrimeDataBase.size()-1);
}
public static void recursion(int dbsize){
boolean prime = true;
for(int i = 0; i<dbsize; i++){
if(cd % PrimeDataBase.get(i) == 0){
prime = false;
break;
}
}
if(cd<4330){ //I can get this to work up to 4330, but no larger
if (prime == true){
PrimeDataBase.add(cd);
System.out.println(cd + " is prime");
cd++;
recursion(PrimeDataBase.size()-1);
}else{
cd++;
recursion(PrimeDataBase.size()-1);
}}
}
}
Here are the outputs:
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
...
4271 is prime
4273 is prime
4283 is prime
Exception in thread "main" java.lang.StackOverflowError
at java.lang.Integer.toString(Unknown Source)
at java.lang.String.valueOf(Unknown Source)
at main.LargePrimeNumber.recursion(LargePrimeNumber.java:32)
... // it gives me like 50 of ^ these errors