I am doing an assignment for a Coursera class that asks me to calculate the Lowest Common Multiple of two numbers, either of which are no larger than 2 * 10 ^ 9. I'm writing this in C and I'm running my code on a test case with the numbers 226553150 and 1023473145. The answer is 46374212988031350, but I'm getting 46374212988031344, which is off by 6!
I've written a correct solution in Python that uses essentially the same approach as the one I've posted below, but the details of numeric precision are obviously taken care of for me. I post this to SO to learn something about floating point precision in C, and because most of the questions I've seen on the internet and SO regarding LCM deal only with integers.
Here is my code, which I'm compiling with gcc -pipe -O2 -std=c11 lcm.c
:
#include <stdio.h>
#include <math.h>
double gcd(double a, double b) {
if (b == 0) {
return a;
}
return gcd(b, fmod(a,b));
}
double lcm(double a, double b) {
return (a * b) / gcd(a,b);
}
int main() {
double a;
double b;
scanf("%lf %lf", &a, &b);
printf("%.0lf\n", lcm(a,b));
return 0;
}