From eef66c91d347ee17ac5c935627ffa4029cdf3559 Mon Sep 17 00:00:00 2001 From: Oussama Moussaoui Date: Sat, 9 Dec 2023 14:51:29 +0100 Subject: [PATCH 1/2] fix & optimize gcd function - handle gcd of negative numbers - fix the case when one of the numbers is equal to zero, gcd(0, x) = absolute value of x - optimize using modulo instead of repeated subtractions --- src/ts/algorithms/math/gcd.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/ts/algorithms/math/gcd.ts b/src/ts/algorithms/math/gcd.ts index 35818deb..02a6fbbc 100644 --- a/src/ts/algorithms/math/gcd.ts +++ b/src/ts/algorithms/math/gcd.ts @@ -1,14 +1,17 @@ export const gcd = (num1: number, num2: number): number => { - if (num1 === 0 || num2 === 0) { - return 0; + if (num1 < 0 || num2 < 0) { + return gcd(Math.abs(num1), Math.abs(num2)); } - if (num1 === num2) { + if (num1 === 0) { + return num2; + } + if (num2 === 0) { return num1; } if (num1 > num2) { - return gcd(num1 - num2, num2); + return gcd(num1 % num2, num2); } - return gcd(num1, num2 - num1); + return gcd(num1, num2 % num1); }; export const gcdArray = (num: number[]) => { From adaaaf4122a891c3b26f670e09cb593d7491eecd Mon Sep 17 00:00:00 2001 From: Oussama Moussaoui Date: Sat, 9 Dec 2023 15:02:56 +0100 Subject: [PATCH 2/2] update unit tests for gcd function - add more tests to cover edge cases and different scenarios - delete incorrect test (gcd(1, 0) = 0) --- test/ts/algorithms/math/gcd.spec.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/test/ts/algorithms/math/gcd.spec.ts b/test/ts/algorithms/math/gcd.spec.ts index fd565a33..75a66ae6 100644 --- a/test/ts/algorithms/math/gcd.spec.ts +++ b/test/ts/algorithms/math/gcd.spec.ts @@ -3,14 +3,26 @@ import { expect } from 'chai'; import { gcd } from '../../../../src/ts/index'; describe('GCD', () => { + it('returns the correct GCD for positive numbers', () => { + expect(gcd(8, 12)).to.equal(4); + expect(gcd(15, 25)).to.equal(5); + expect(gcd(21, 28)).to.equal(7); + }); + + it('returns the correct GCD for negative numbers', () => { + expect(gcd(-8, 12)).to.equal(4); + expect(gcd(15, -25)).to.equal(5); + expect(gcd(-21, -28)).to.equal(7); + }); - it('returns the gcd between two numbers', () => { + it('returns the correct GCD when one of the numbers is 0', () => { + expect(gcd(0, -12)).to.equal(12); + expect(gcd(15, 0)).to.equal(15); + }); - expect(gcd(1, 0)).to.equal(0); - expect(gcd(1, 1)).to.equal(1); - expect(gcd(2, 2)).to.equal(2); - expect(gcd(2, 4)).to.equal(2); - expect(gcd(2, 3)).to.equal(1); - expect(gcd(10, 1000)).to.equal(10); + it('returns 1 for co-prime numbers', () => { + expect(gcd(7, 22)).to.equal(1); + expect(gcd(11, 28)).to.equal(1); + expect(gcd(9, 16)).to.equal(1); }); });