Browse Source

big: Special case `gcd(0,0)` + `lcm(0,0)`.

Jeroen van Rijn 4 years ago
parent
commit
06f5a6c785
2 changed files with 21 additions and 2 deletions
  1. 17 2
      core/math/big/basic.odin
  2. 4 0
      core/math/big/test.py

+ 17 - 2
core/math/big/basic.odin

@@ -1277,10 +1277,18 @@ int_gcd :: proc(res, a, b: ^Int) -> (err: Error) {
 	if err = clear_if_uninitialized(a, b, res);    err != .None { return err; }
 
 	/*
+		If both `a` and `b` are zero, return zero.
 		If either `a` or `b`, return the other one.
 	*/
-	if z, _ := is_zero(a); z { return abs(res, b); }
-	if z, _ := is_zero(b); z { return abs(res, a); }
+	az, _ := is_zero(a);
+	bz, _ := is_zero(b);
+	if az && bz {
+		return zero(res);
+	} else if az {
+		return abs(res, b);
+	} else if bz {
+		return abs(res, a);
+	}
 
  	/*
  		Get copies of `a` and `b` we can modify.
@@ -1366,6 +1374,13 @@ int_lcm :: proc(res, a, b: ^Int) -> (err: Error) {
 	t1, t2 := &Int{}, &Int{};
 	defer destroy(t1, t2);
 
+	/*
+		Special case: lcm(0, 0) is defined as zero.
+	*/
+	az, _ := is_zero(a);
+	bz, _ := is_zero(b);
+	if az && bz { return zero(res); }
+
 	/*
 		t1 = get the GCD of the two inputs.
 	*/

+ 4 - 0
core/math/big/test.py

@@ -432,10 +432,14 @@ TESTS = {
 	test_gcd: [
 		[ 123, 25, ],
 		[ 125, 25, ],
+		[ 125, 0,  ],
+		[   0, 0,  ],
 	],
 	test_lcm: [
 		[ 123, 25, ],
 		[ 125, 25, ],
+		[ 125, 0,  ],
+		[   0, 0,  ],
 	],
 }