Search code examples
c++greatest-common-divisor

Two && in a while condition?


I was trying to help a friend with a problem, he asked me how can he make the GCD of 3 numbers using the Nicomachus method. Everything went great until I tried to enter this condition:

while (a!=b && b!=c && a!=c)

But the problem is it would only execute once. I changed it into this:

while (a!=b && b!=c)

I know it results into the same thing but I was just wondering why the first one can't work ? I can't add 2 && in the same condition ?


Solution

  • You certainly can have 2 && in the same condition - you can have as many as you want. The fact that the loop stops depends on something else.

    By the way, if you had a=10, b=20, C=10, the first condition (while (a!=b && b!=c && a!=c)) would stop (because a != c would be false), but the second one (while (a!=b && b!=c)) would continue. Probably this is what happened.

    Transforming 3 conditions into just 2 can be done in the opposite case, that is, if you want to make sure they are all equal: a ==b && b == c automatically implies that a == c (see Transitive relation of equality), so adding this 3rd condition or not doesn't make any difference. But the same is not true for inequality, as I have shown.