0

I wrote a program that generates prime numbers. Are there better ways of doing so? Additionally, how could I improve my own method.

public static void main(String[] args) {
        ArrayList<Integer> primeNumbers = new ArrayList<Integer>(primeNumberGenerator(1000));
        System.out.println(primeNumbers);
    
    }

    public static ArrayList<Integer> primeNumberGenerator(int range){
        
        ArrayList<Integer> primeNumbers = new ArrayList<Integer>();
        int brake = 0;
        int index = 0;

        for(int i = 2; i < range; i++){
            brake = 0;
            for(int p = 2; p < range; p++){
                if((i%p) == 0 && i != p && brake == 0){
                    brake = 1;
                }
            }
            if(brake == 0){
                primeNumbers.add(index, i);
                index += 1;
            }
            brake = 0;
        }
    return primeNumbers;
    }
  • There are a large number of variations of this algorithm. Check out Wikipedia: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_and_variants Don't overlook `BigInteger.nextProbablePrime()`. – markspace Apr 20 '21 at 03:54
  • 1
    As I commented last time you asked this question: `brake` should be a boolean; your inner loop condition could be `p*p <= i && brake == 0`; you don't need the `index` variable, as `add` will append to the end of the list anyway. But there are lots of other ways to calculate primes, and "better" depends on your criterion of quality; sieves (e.g. Sieve of Eratosthenes) are probably faster. – Andy Turner Apr 20 '21 at 04:16

1 Answers1

0

You can use Sieve Method to generate primes with better time complexity.

Vinay Jain
  • 398
  • 2
  • 6