Skip to content

Commit 25596e4

Browse files
authored
Merge pull request loiane#221 from os-moussao/fix-optimize/gcd
Fix & optimize gcd function
2 parents 7d33c7c + adaaaf4 commit 25596e4

File tree

2 files changed

+27
-12
lines changed

2 files changed

+27
-12
lines changed

src/ts/algorithms/math/gcd.ts

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
export const gcd = (num1: number, num2: number): number => {
2-
if (num1 === 0 || num2 === 0) {
3-
return 0;
2+
if (num1 < 0 || num2 < 0) {
3+
return gcd(Math.abs(num1), Math.abs(num2));
44
}
5-
if (num1 === num2) {
5+
if (num1 === 0) {
6+
return num2;
7+
}
8+
if (num2 === 0) {
69
return num1;
710
}
811
if (num1 > num2) {
9-
return gcd(num1 - num2, num2);
12+
return gcd(num1 % num2, num2);
1013
}
11-
return gcd(num1, num2 - num1);
14+
return gcd(num1, num2 % num1);
1215
};
1316

1417
export const gcdArray = (num: number[]) => {

test/ts/algorithms/math/gcd.spec.ts

+19-7
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,26 @@ import { expect } from 'chai';
33
import { gcd } from '../../../../src/ts/index';
44

55
describe('GCD', () => {
6+
it('returns the correct GCD for positive numbers', () => {
7+
expect(gcd(8, 12)).to.equal(4);
8+
expect(gcd(15, 25)).to.equal(5);
9+
expect(gcd(21, 28)).to.equal(7);
10+
});
11+
12+
it('returns the correct GCD for negative numbers', () => {
13+
expect(gcd(-8, 12)).to.equal(4);
14+
expect(gcd(15, -25)).to.equal(5);
15+
expect(gcd(-21, -28)).to.equal(7);
16+
});
617

7-
it('returns the gcd between two numbers', () => {
18+
it('returns the correct GCD when one of the numbers is 0', () => {
19+
expect(gcd(0, -12)).to.equal(12);
20+
expect(gcd(15, 0)).to.equal(15);
21+
});
822

9-
expect(gcd(1, 0)).to.equal(0);
10-
expect(gcd(1, 1)).to.equal(1);
11-
expect(gcd(2, 2)).to.equal(2);
12-
expect(gcd(2, 4)).to.equal(2);
13-
expect(gcd(2, 3)).to.equal(1);
14-
expect(gcd(10, 1000)).to.equal(10);
23+
it('returns 1 for co-prime numbers', () => {
24+
expect(gcd(7, 22)).to.equal(1);
25+
expect(gcd(11, 28)).to.equal(1);
26+
expect(gcd(9, 16)).to.equal(1);
1527
});
1628
});

0 commit comments

Comments
 (0)