views:

49

answers:

2

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?

+2  A: 

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.

Peter Lang
Cheers, must of got out the wrong side of bed this morning.
devilcrack
+1  A: 

Your condition right now evaluates to true if the number is not divisible by any of (2,3,5). This holds for all numbers except multiples of (all of) 2, 3, and 5. Try logical and (&&) instead of logical or (||).

danben