Skip to contentSkip to conversation

lib/lcm.c: Ensure correct result whenever it fits

PATCH In review Rasmus Villemoes 1 participant 3 messages Dec 17, 2013 – Jan 14, 2014 Library code

lore
Share & tools
lore
#0 lore raw

PATCH 1/2 lib/lcm.c: Ensure correct result whenever it fits

Ensure that lcm(a,b) returns the mathematically correct result, provided it fits in an unsigned long. The current version returns garbage if a*b overflows, even if the final result would fit.

---
There are of course still plenty of cases where the return value is wrong.

 lib/lcm.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/lcm.c +1 -1
index b9c8de4..01b3aa9 100644
@@ -7,7 +7,7 @@
 unsigned long lcm(unsigned long a, unsigned long b)
 {
 	if (a && b)
-		return (a * b) / gcd(a, b);
+		return (a / gcd(a, b)) * b;
 	else if (b)
 		return b;
 
Signature · 1 line
1.8.4.rc3.2.g61bff3f
#1 lore raw

PATCH 2/2 lib/lcm.c: lcm(n,0)=lcm(0,n) is 0, not n

Return the mathematically correct answer when an argument is 0.

---
I don't think there is any instance of lcm(0,n) in the kernel, but at least this reduces code size a little.

 lib/lcm.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
lib/lcm.c +2 -4
index 01b3aa9..51cc6b1 100644
@@ -8,9 +8,7 @@ unsigned long lcm(unsigned long a, unsigned long b)
 {
 	if (a && b)
 		return (a / gcd(a, b)) * b;
-	else if (b)
-		return b;
-
-	return a;
+	else
+		return 0;
 }
 EXPORT_SYMBOL_GPL(lcm);
Signature · 1 line
1.8.4.rc3.2.g61bff3f
#2 lore raw
In reply to Rasmus Villemoes

Rasmus Villemoes <[email protected]> writes:

Ping...

Quoted 24 lines

Ensure that lcm(a,b) returns the mathematically correct result, provided it fits in an unsigned long. The current version returns garbage if a*b overflows, even if the final result would fit.

---
There are of course still plenty of cases where the return value is wrong.

 lib/lcm.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/lcm.c +1 -1
index b9c8de4..01b3aa9 100644
@@ -7,7 +7,7 @@
 unsigned long lcm(unsigned long a, unsigned long b)
 {
 	if (a && b)
-		return (a * b) / gcd(a, b);
+		return (a / gcd(a, b)) * b;
 	else if (b)
 		return b;