@@ -26,12 +26,12 @@ unsigned int gcd(unsigned int x, unsigned int y) {
26
26
if (x > y) {
27
27
// The following is valid because we have checked whether y == 0
28
28
29
- int temp = x / y;
29
+ unsigned int temp = x / y;
30
30
return gcd (y, x - temp * y);
31
31
}
32
32
// Again the following is valid because we have checked whether x == 0
33
33
34
- int temp = y / x;
34
+ unsigned int temp = y / x;
35
35
return gcd (x, y - temp * x);
36
36
}
37
37
@@ -40,7 +40,9 @@ unsigned int gcd(unsigned int x, unsigned int y) {
40
40
* @params integer x and y whose lcm we want to find.
41
41
* @return lcm of x and y using the relation x * y = gcd(x, y) * lcm(x, y)
42
42
*/
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
+ }
44
46
45
47
/* *
46
48
* Function for testing the lcm() functions with some assert statements.
@@ -59,6 +61,15 @@ void tests() {
59
61
lcm (2 , 3 ) == 6 ));
60
62
std::cout << " Second assertion passes: LCM of 2 and 3 is " << lcm (2 , 3 )
61
63
<< 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;
62
73
}
63
74
64
75
/* *
0 commit comments