Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
});