Skip to content

Commit

Permalink
Merge pull request #221 from os-moussao/fix-optimize/gcd
Browse files Browse the repository at this point in the history
Fix & optimize gcd function
  • Loading branch information
loiane authored Dec 20, 2023
2 parents 7d33c7c + adaaaf4 commit 25596e4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
13 changes: 8 additions & 5 deletions src/ts/algorithms/math/gcd.ts
Original file line number Diff line number Diff line change
@@ -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[]) => {
Expand Down
26 changes: 19 additions & 7 deletions test/ts/algorithms/math/gcd.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

0 comments on commit 25596e4

Please sign in to comment.