Skip to contentSkip to conversation

lib: gcd: prevent possible div by 0

PATCH Superseded Davidlohr Bueso 2 participants 3 messages Sep 9, 2012 – Sep 10, 2012 Library code

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 lib: gcd: prevent possible div by 0

Account for properties when a and/or b are 0:
gcd(0, 0) = 0
gcd(a, 0) = a
gcd(0, b) = b

---
 lib/gcd.c |    3 +++
 1 file changed, 3 insertions(+)
lib/gcd.c +3 -0
index cce4f3c..7e163c6 100644
@@ -7,6 +7,9 @@ unsigned long gcd(unsigned long a, unsigned long b)
 {
 	unsigned long r;
 
+	if (!a || !b)
+		return a | b;
+
 	if (a < b)
 		swap(a, b);
 	while ((r = a % b) != 0) {
Signature · 1 line
1.7.9.5
#1 lore raw
Quoted 16 lines · Davidlohr Bueso

Account for properties when a and/or b are 0:
gcd(0, 0) = 0
gcd(a, 0) = a
gcd(0, b) = b

---
 lib/gcd.c |    3 +++
 1 file changed, 3 insertions(+)
lib/gcd.c +0 -0
index cce4f3c..7e163c6 100644

lib/gcd.c unsigned long gcd(unsigned long a, unsigned long b) · line 11

Quoted 5 lines
lib/gcd.c +2 -0
@@ -7,6 +7,9 @@ unsigned long gcd(unsigned long a, unsigned long b)
 {
 	unsigned long r;
 
+	if (!a || !b)
+		return a | b;

This seems overkill

lib/gcd.c unsigned long gcd(unsigned long a, unsigned long b) · line 14

Quoted 3 lines
lib/gcd.c +1 -0
+
 	if (a < b)
 		swap(a, b);

better here to :

	if (!b)
		return a;
Quoted 1 line
lib/gcd.c +0 -0
 	while ((r = a % b) != 0) {
#2 lore raw
Quoted 20 lines · Eric Dumazet
Quoted 19 lines · Davidlohr Bueso

Account for properties when a and/or b are 0:
gcd(0, 0) = 0
gcd(a, 0) = a
gcd(0, b) = b

---
 lib/gcd.c |    3 +++
 1 file changed, 3 insertions(+)
lib/gcd.c +0 -0
index cce4f3c..7e163c6 100644
@@ -7,6 +7,9 @@ unsigned long gcd(unsigned long a, unsigned long b)
 {
 	unsigned long r;
 
Quoted 4 lines

lib/gcd.c unsigned long gcd(unsigned long a, unsigned long b) · line 11

Quoted 2 lines
lib/gcd.c +2 -0
+	if (!a || !b)
+		return a | b;

This seems overkill

It might, but it reads better, IMHO.

Quoted 9 lines

lib/gcd.c unsigned long gcd(unsigned long a, unsigned long b) · line 14

Quoted 4 lines
lib/gcd.c +1 -0
+
 	if (a < b)
 		swap(a, b);

better here to :

	if (!b)
		return a;

Sure, I don't mind either way. I'll send a v2 shortly.

Thanks for reviewing.
Davidlohr