diff --git a/math/least_common_multiple.cpp b/math/least_common_multiple.cpp index 741945716..e9e46490a 100644 --- a/math/least_common_multiple.cpp +++ b/math/least_common_multiple.cpp @@ -26,12 +26,12 @@ unsigned int gcd(unsigned int x, unsigned int y) { if (x > y) { // The following is valid because we have checked whether y == 0 - int temp = x / y; + unsigned int temp = x / y; return gcd(y, x - temp * y); } // Again the following is valid because we have checked whether x == 0 - int temp = y / x; + unsigned int temp = y / x; return gcd(x, y - temp * x); } @@ -40,7 +40,9 @@ unsigned int gcd(unsigned int x, unsigned int y) { * @params integer x and y whose lcm we want to find. * @return lcm of x and y using the relation x * y = gcd(x, y) * lcm(x, y) */ -unsigned int lcm(unsigned int x, unsigned int y) { return x * y / gcd(x, y); } +unsigned int lcm(unsigned int x, unsigned int y) { + return x / gcd(x, y) * y; +} /** * Function for testing the lcm() functions with some assert statements. @@ -59,6 +61,15 @@ void tests() { lcm(2, 3) == 6)); std::cout << "Second assertion passes: LCM of 2 and 3 is " << lcm(2, 3) << std::endl; + + // Testing an integer overflow. + // The algorithm should work as long as the result fits into integer. + assert(((void)"LCM of 987654321 and 987654321 is 987654321 but lcm function" + " gives a different result.\n", + lcm(987654321, 987654321) == 987654321)); + std::cout << "Third assertion passes: LCM of 987654321 and 987654321 is " + << lcm(987654321, 987654321) + << std::endl; } /**