I’m trying to build an array of prime numbers in Java.
if(c % 2 != 0 || c % 3 != 0 || c % 5 != 0) {
n.add(c);
}
But my program seems to ignore the condition and just adds every number to my list.
But if I just use one condition for example,
if(c % 2 != 0)
The code works perfectly in ignoring any number which is a multiple of 2. What am I missing here?
You need to use logical and (
&&) instead of or(||), as you want all conditions to be true before adding.With logical or, each condition is evaluated from left to right, until finding one that matches.