Search code examples
booleanboolean-logicboolean-operations

Comparing not then and vs and then not


I'm just wondering if there's a difference between an if or a while statement if the condition is either (!a && !b) (let's call this statement 1) or !(a && b) (let's call this statement 2).

I was thinking about it, and we have four combinations of a and b possible, and I think that the condition would be different if a != b. I'm just hoping someone can check my logic.

If a and b are both true, then statements 1 and 2 are both false. If a and b are both false, then statements 1 and 2 are both true. ?However, if a is true and b is false, or the inverse, then statement 1 is false, but statement 2 is true. Is this correct?


Solution

  • You are actually asking about a fundamental law of Boolean Algebra: De Morgan's Laws are very useful to know when re-working or simplifying conditionals.

    De Morgan's Laws

    !(a && b)  =  (!a || !b)
    !(a || b)  =  (!a && !b)
    

    Your intuition that your statements 1 and 2 might not be equivalent is correct. Working through the four possibilities of a and b above shows that the actual equivalencies are those given by De Morgan's Laws.

    enter image description here

    Key: ∧ is logical AND (&&); ∨ is logical OR (||).

    Image source: http://ndp.jct.ac.il/tutorials/mavomath/node15.html