Problems with prime number generator, using ArrayList

1.3k views Asked by At

I have been having a heck of a time trying to make a prime number generator work. It's supposed to list the first 100 primes, so sieving means either cheating and looking up an artificial limit to the composites, or creating a bunch of needless arrays of composite numbers.

Just by dividing and testing, I've tried using a simple array of primes and then testing against them, but that left the array mostly empty and returning "x/0" errors. ArrayList lets me expand the array as needed, but I've had trouble getting my test loop to work. It's to the point where the variables just look like gibberish in my head and I'm changing values at random. Can anyone point out where my concept went wrong?

public static void main(String[] args) {
    ArrayList<Integer> primes = new ArrayList<>();
    int testNum = 1;

    while (primes.size() < 100)
    {
        for (int index = 0; index <= testNum; index++)
        {
            if ((testNum % primes.get(index)) == 0)
                primes.add(testNum);
        }
        testNum++;
    }

    System.out.println("The first 100 prime numbers are:");
    for (int index = 0; index < 100; index++)
        System.out.println((index + 1) + ": " + primes.get(index));
}

}

fixed: thanks to Saleem Khan. had to mess with the upper limit and a few other things to get it working and printing right.

ArrayList<Integer> primes = new ArrayList<Integer>();
    int testNum;
    int index;

    for (index = 1; index <= 1000; index++) //index counts up to 100 primes
    {
        int factors = 0; 
        for (testNum = index; testNum >= 1; testNum--)
        {
            if (index % testNum == 0)
            {
                factors = factors + 1;
            }
        }

        if (factors == 2)
        {
            primes.add(index);
        }
    }

    System.out.println("The first 100 prime numbers are:");
    for (int prime = 0; prime < 100; prime++)
    {
        System.out.print((prime + 1) + ": ");
        System.out.println(primes.get(prime));
    }
}

edit: deleted erroneous code at 20 and 21

1

There are 1 answers

0
Saleem Khan On BEST ANSWER

Hi use this code and problem is with your logic.

public static void main(String[] args) {
    int i = 0;
    int num = 0;

    List<Integer> primes = new ArrayList<Integer>();

    for (i = 1; i <= 100; i++) {
        int counter = 0;

        for (num = i; num >= 1; num--) {
            if (i % num == 0) {
                counter = counter + 1;
            }
        }

        if (counter == 2) {
            primes.add(i);
        }
    }
    System.out.println("The first 100 prime numbers are:");
    for(int prime : primes) {
        System.out.println(prime);
    }
}

you cant get value from empty List, it will throw indexOutOfBoundException