While loop stops with one condition being true

Hi, I am trying to find a common denominator, but my while loop stops with just one conditiong being true, instead of 3. What am I doing wrong ?

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
int main(){
    int a12=12, a15=15, a18=18, i=1;
    while(i%a12!=0 && i%a15!=0 && i%a18!=0)
    {
        i++;
        cout << i%a12 << " " << i%a15 << " " << i%a18 << endl; // results in : 0 12 12
    }
    return 0;
}
Last edited on
Your loop will execute as long as ALL inequalities are met. In other words, as soon as ANY of those inequalities become an equality. Therefore, your loop finds the smallest i that's divisible by ANY of {12, 15, 18}.
If you want to find the smallest i that's divisible by ALL of {12, 15, 18}, the loop should continue executing as long as ANY of the inequalities are true.

In other words, replace the && with ||.
Needed some time to figure out why it was supposed to be || instead of &&, but now its clear. Thank you !
Topic archived. No new replies allowed.