fix: Integer overflow of least_common_multiple. (#970)

* fix: Integer overflow of least_common_multiple.

* Update the typing (linter warning).
This commit is contained in:
Filip Hlasek 2020-07-22 05:01:06 -07:00 committed by GitHub
parent 794e1765bd
commit d58954523f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -26,12 +26,12 @@ unsigned int gcd(unsigned int x, unsigned int y) {
if (x > y) { if (x > y) {
// The following is valid because we have checked whether y == 0 // 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); return gcd(y, x - temp * y);
} }
// Again the following is valid because we have checked whether x == 0 // 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); 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. * @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) * @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. * Function for testing the lcm() functions with some assert statements.
@ -59,6 +61,15 @@ void tests() {
lcm(2, 3) == 6)); lcm(2, 3) == 6));
std::cout << "Second assertion passes: LCM of 2 and 3 is " << lcm(2, 3) std::cout << "Second assertion passes: LCM of 2 and 3 is " << lcm(2, 3)
<< std::endl; << 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;
} }
/** /**