I am trying to write a little script myself to compute all of the prime numbers up to n (a user submitted argument) and would appreciate a little bit of help. I want to use ArrayLists to write this function, and hopefully make it as efficient as possible - another big thing for me that I can't seem to grasp is doing everything as is standard and good practice (i.e having classes in capital letters, etc) so if you wouldn't mind please point out any mistakes in that regard so I can fix them.
Here is the code I have written thus far, but I know there are many ways of optimising it - specifically, I have a boolean array storing whether a number is prime or not. Surely there is a better way of doing this than cycling through the array and making everything prime, then getting rid of the numbers that are not ?
Thanks a lot for your time ! :)
(tl;dr - Writing a script to computer prime numbers up to N. I wish to use ArrayLists to do this. How can I make my code better - specifically the inefficient boolean array).
import java.util.*;
public class Prime {
public static void main( String[] args ){
}
public static void prime( int initialCapacity){
int index=0;
ArrayList<Integer> listOfPrimeNumbers = new ArrayList<Integer>( );
boolean[] isPrimeNumber = new boolean[initialCapacity + 1]; // boolean defaults to
// false
while ( index <= listOfPrimeNumbers.size() )
{
isPrimeNumber[index] = true;
if (isPrimeNumber[index]) {
listOfPrimeNumbers.add(index);
}
for (int j = index; j * index <= initialCapacity; j++) {
isPrimeNumber[index * j] = false;
}
// Now mark the multiple of i as non-prime number
index++;
}
}
}