Skip to content

Commit d589545

Browse files
authored
fix: Integer overflow of least_common_multiple. (#970)
* fix: Integer overflow of least_common_multiple. * Update the typing (linter warning).
1 parent 794e176 commit d589545

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

math/least_common_multiple.cpp

+14-3
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,12 @@ unsigned int gcd(unsigned int x, unsigned int y) {
2626
if (x > y) {
2727
// The following is valid because we have checked whether y == 0
2828

29-
int temp = x / y;
29+
unsigned int temp = x / y;
3030
return gcd(y, x - temp * y);
3131
}
3232
// Again the following is valid because we have checked whether x == 0
3333

34-
int temp = y / x;
34+
unsigned int temp = y / x;
3535
return gcd(x, y - temp * x);
3636
}
3737

@@ -40,7 +40,9 @@ unsigned int gcd(unsigned int x, unsigned int y) {
4040
* @params integer x and y whose lcm we want to find.
4141
* @return lcm of x and y using the relation x * y = gcd(x, y) * lcm(x, y)
4242
*/
43-
unsigned int lcm(unsigned int x, unsigned int y) { return x * y / gcd(x, y); }
43+
unsigned int lcm(unsigned int x, unsigned int y) {
44+
return x / gcd(x, y) * y;
45+
}
4446

4547
/**
4648
* Function for testing the lcm() functions with some assert statements.
@@ -59,6 +61,15 @@ void tests() {
5961
lcm(2, 3) == 6));
6062
std::cout << "Second assertion passes: LCM of 2 and 3 is " << lcm(2, 3)
6163
<< std::endl;
64+
65+
// Testing an integer overflow.
66+
// The algorithm should work as long as the result fits into integer.
67+
assert(((void)"LCM of 987654321 and 987654321 is 987654321 but lcm function"
68+
" gives a different result.\n",
69+
lcm(987654321, 987654321) == 987654321));
70+
std::cout << "Third assertion passes: LCM of 987654321 and 987654321 is "
71+
<< lcm(987654321, 987654321)
72+
<< std::endl;
6273
}
6374

6475
/**

0 commit comments

Comments
 (0)