开发者

logical OR and modulus operator behaving oddly in Java

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 ign开发者_运维技巧oring 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.


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 (||).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜