Joe - 7 months ago 18

Java Question

I was working with coding in java and I am stuck in this code which I implemented for finding prime numbers .

`public class PrimeList {`

ArrayList<Integer> list;

public PrimeList(int n){

list = new ArrayList<Integer>();

preparePrimeList(n);

}

private void preparePrimeList(int n){

int c =0;

for (int i=0; i<=n; i++) {

if (i%2!=0 && i%3!=0 && i%5!=0 && i%7!=0) {

list.add(i);

c++;

}

}

list.remove(0);

list.remove(1);

}

public void printPrimeList(){

System.out.println(list);

}

public boolean isPrime(int nbr){

if (list.contains(nbr)) {

return true;

}

return false;

}

public static void main(String[] args) {

PrimeList primes = new PrimeList(100);

primes.printPrimeList();

primes.isPrime(33);

}

}

When I run the code I get the following :

`[11, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]`

Why I get wrong output ? the out put should be like this :

`2, 3, 4, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,`

83, 89, 97

false

What I am doing wrong ?

Thank you

Answer

Your code is doing exactly what you tell it to do. The reason it's starting at 11 is because your prime-check is flawed. For example, 2%2 == 0, so the program thinks 2 is not prime. Similarly for 3, 5, and 7. So the program starts at 11.

You could avoid this by writing a more accurate prime-check method, not one that just checks divisibility by 2, 3, 5, or 7. For example:

```
public boolean checkIfPrime(int num){
for (int x = 2; x < (int)Math.sqrt(num); x++)
if (num % x == 0)
return false;
return true;
}
```

In addition, in trying to remove the first items from the list, you actually removed the first and third items (since the third, position 2, moved to the second, position 1). Thats why 13 was removed in your program.

Replace list.remove(1) with list.remove(0) (so you have two).

Hope this helps!