Write gcd() (Euclid's algorithm) and lcm() that cannot overflow for large inputs.
#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
long long lcm(int a, int b) {
return (long long) (a / gcd(a, b)) * b; /* divide first, then multiply */
}
int main(void) {
printf("gcd(48, 180) = %d, lcm(48, 180) = %lld\n", gcd(48, 180), lcm(48, 180));
return 0;
}
gcd(48, 180) = 12, lcm(48, 180) = 720
Euclid: gcd(a, b) = gcd(b, a mod b) until b is 0. For the LCM, dividing before multiplying keeps the intermediate value small, and the long long result has room for large products.