From 93b5a3f63a837691d244cf534254bf82d2021f7a Mon Sep 17 00:00:00 2001 From: Hugo Saint-Vignes Date: Thu, 22 Oct 2020 10:54:33 +0200 Subject: [PATCH] [poincare] Handle equal negative numbers in GCD LCM Change-Id: Ia46966270418a339f8a37e8a1971a7f7dd046034 --- poincare/src/arithmetic.cpp | 23 +++++++++++++---------- poincare/test/simplification.cpp | 2 ++ 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/poincare/src/arithmetic.cpp b/poincare/src/arithmetic.cpp index 673195469..e65879385 100644 --- a/poincare/src/arithmetic.cpp +++ b/poincare/src/arithmetic.cpp @@ -9,13 +9,13 @@ Integer Arithmetic::GCD(const Integer & a, const Integer & b) { if (a.isOverflow() || b.isOverflow()) { return Integer::Overflow(false); } - if (a.isEqualTo(b)) { - return a; - } Integer i = a; Integer j = b; i.setNegative(false); j.setNegative(false); + if (i.isEqualTo(j)) { + return i; + } do { if (i.isZero()) { return j; @@ -35,14 +35,17 @@ Integer Arithmetic::LCM(const Integer & a, const Integer & b) { if (a.isZero() || b.isZero()) { return Integer(0); } - if (a.isEqualTo(b)) { - return a; + Integer i = a; + Integer j = b; + i.setNegative(false); + j.setNegative(false); + if (i.isEqualTo(j)) { + return i; } - /* Using LCM(a,b) = a*(b/GCD(a,b)). Knowing that GCD(a, b) divides b, - * division is performed before multiplication to be more efficient. */ - Integer signResult = Integer::Multiplication(a, Integer::Division(b, GCD(a, b)).quotient); - signResult.setNegative(false); - return signResult; + /* Using LCM(i,j) = i*(j/GCD(i,j)). Knowing that GCD(i, j) divides j, and that + * GCD(i,j) = 0 if and only if i == j == 0, which would have been escaped + * before. Division is performed before multiplication to be more efficient.*/ + return Integer::Multiplication(i, Integer::Division(j, GCD(i, j)).quotient); } int Arithmetic::GCD(int a, int b) { diff --git a/poincare/test/simplification.cpp b/poincare/test/simplification.cpp index fda691e27..28a406092 100644 --- a/poincare/test/simplification.cpp +++ b/poincare/test/simplification.cpp @@ -727,10 +727,12 @@ QUIZ_CASE(poincare_simplification_function) { assert_parsed_expression_simplify_to("gcd(123,278)", "1"); assert_parsed_expression_simplify_to("gcd(11,121)", "11"); assert_parsed_expression_simplify_to("gcd(56,112,28,91)", "7"); + assert_parsed_expression_simplify_to("gcd(-32,-32)", "32"); assert_parsed_expression_simplify_to("im(1+5×𝐢)", "5"); assert_parsed_expression_simplify_to("lcm(123,278)", "34194"); assert_parsed_expression_simplify_to("lcm(11,121)", "121"); assert_parsed_expression_simplify_to("lcm(11,121, 3)", "363"); + assert_parsed_expression_simplify_to("lcm(-32,-32)", "32"); assert_parsed_expression_simplify_to("√(4)", "2"); assert_parsed_expression_simplify_to("re(1+5×𝐢)", "1"); assert_parsed_expression_simplify_to("root(4,3)", "root(4,3)");