Use Euclid's method to write gcd(a, b), which returns the greatest common divisor (a, b are not negative and not both 0): divide a by b to get remainder r, then go on with b and r until the remainder is 0. For 12 and 18: 12, 18 → 18, 12 → 12, 6 → 6, 0, so the answer is 6. Then the LCM is a / gcd(a, b) * b.
gcd(12, 18)→6gcd(100, 75)→25gcd(7, 5)→1int gcd(int a, int b)int gcd(int a, int b) {
while (b != 0) {
int r = a % b;
// your code here: move b forward to be the new a
b = r;
}
return a;
}
Run tries the examples. When they look right, Submit.