Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Fix & optimize gcd function#221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
loiane merged 2 commits intoloiane:mainfromos-moussao:fix-optimize/gcd
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes fromall 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 deletionssrc/ts/algorithms/math/gcd.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
export const gcd = (num1: number, num2: number): number => {
if (num1=== 0 || num2=== 0) {
return0;
if (num1< 0 || num2< 0) {
returngcd(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 deletionstest/ts/algorithms/math/gcd.spec.ts
View file
Open in desktop
Original file line numberDiff line numberDiff 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);
});
});

[8]ページ先頭

©2009-2025 Movatter.jp