Home > Software engineering >  Difference between if (j%3 != 0 && j%4 != 0) and (!((j%3 == 0) && (j%4 == 0))), and why (!((j%3 == 0
Difference between if (j%3 != 0 && j%4 != 0) and (!((j%3 == 0) && (j%4 == 0))), and why (!((j%3 == 0

Time:03-25

I don't understand why the following syntax are not the same

if (j%3 != 0 && j%4 != 0)
if (!((j%3 == 0) && (j%4 == 0)))

Yet, the followings are.

if (j%3 != 0 && j%4 != 0) /
if (!((j%3 == 0) || (j%4 == 0)))

Why is that

!(A && B) != !A && !B

and

!(A || B) == !A && !B / !(A && B) == !A || !B

CodePudding user response:

This is the mathematic boolean logic.

A and B <=> not (not A or not B)

not A and not B <=> not (A or B)

not (A and B) <=> not A or not B

For proving these equations, use value tables.

0 & 0 = 0   !(1 | 1) = !1 = 0
0 & 1 = 0   !(1 | 0) = !1 = 0
1 & 0 = 0   !(0 | 1) = !1 = 0
1 & 1 = 1   !(0 | 0) = !0 = 1

CodePudding user response:

Say I have a red car and grey house, then "my car is blue and my house is grey" is false (!(A && B)). Yet "my car isn't blue and my house isn't grey" is also false (!(!A && !B)). So !(A && B) and !A && !B clearly aren't equivalent.

The actual negation of "my car is blue and my house is grey" is "my car isn't blue or my house isn't grey" (!A || !B).

We can also clearly see this is the case by plugging all possible values into the equations.

A B !(A && B) !A || !B !(A || B) !A && !B
0 0 !(0 && 0) = !0 = 1 !0 || !0 = 1 || 1 = 1 !(0 || 0) = !0 = 1 !0 && !0 = 1 && 1 = 1
0 1 !(0 && 1) = !0 = 1 !0 || !1 = 1 || 0 = 1 !(0 || 1) = !1 = 0 !0 && !1 = 1 && 0 = 0
1 0 !(1 && 0) = !0 = 1 !1 || !0 = 0 || 1 = 1 !(1 || 0) = !1 = 0 !1 && !0 = 0 && 1 = 0
1 1 !(1 && 1) = !1 = 0 !1 || !1 = 0 || 0 = 0 !(1 || 1) = !1 = 0 !1 && !1 = 0 && 0 = 0

Two equivalences that are identified by the above table:

!(A && B) = !A || !B
!(A || B) = !A && !B

These are known as De Morgan's laws.

  •  Tags:  
  • c
  • Related