Skip to content

Commit 8734dfc

Browse files
authored
fix: handle zeros in CoPrimeCheck (TheAlgorithms#1622)
1 parent a5945e3 commit 8734dfc

File tree

2 files changed

+8
-15
lines changed

2 files changed

+8
-15
lines changed

Maths/CoPrimeCheck.js

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,7 @@
99
is coprime with b.
1010
*/
1111

12-
// Here we use a GetEuclidGCD method as a utility.
13-
const GetEuclidGCD = (arg1, arg2) => {
14-
let less = arg1 > arg2 ? arg2 : arg1
15-
for (less; less >= 2; less--) {
16-
if (arg1 % less === 0 && arg2 % less === 0) return less
17-
}
18-
return less
19-
}
12+
import { GetEuclidGCD } from './GetEuclidGCD'
2013

2114
// CoPrimeCheck function return the boolean in respect of the given number is co-prime or not.
2215
/**
@@ -26,15 +19,11 @@ const GetEuclidGCD = (arg1, arg2) => {
2619
* @returns return correspond boolean value, if both number are co-prime return `true`, else return `false`.
2720
*/
2821
const CoPrimeCheck = (firstNumber, secondNumber) => {
29-
// firstly, check that input is a number or not.
30-
if (typeof firstNumber !== 'number' || typeof secondNumber !== 'number') {
31-
throw new TypeError('Argument is not a number.')
32-
}
3322
/*
3423
This is the most efficient algorithm for checking co-primes
3524
if the GCD of both the numbers is 1 that means they are co-primes.
3625
*/
37-
return GetEuclidGCD(Math.abs(firstNumber), Math.abs(secondNumber)) === 1
26+
return GetEuclidGCD(firstNumber, secondNumber) === 1
3827
}
3928

4029
export { CoPrimeCheck }

Maths/test/CoPrimeCheck.test.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,19 @@ describe('CoPrimeCheck', () => {
88
[1, 7],
99
[20, 21],
1010
[5, 7],
11-
[-5, -7]
11+
[-5, -7],
12+
[1, 0],
13+
[-1, 0]
1214
])('returns true for %j and %i', (inputA, inputB) => {
1315
expect(CoPrimeCheck(inputA, inputB)).toBe(true)
1416
expect(CoPrimeCheck(inputB, inputA)).toBe(true)
1517
})
1618

1719
it.each([
1820
[5, 15],
19-
[13 * 17 * 19, 17 * 23 * 29]
21+
[13 * 17 * 19, 17 * 23 * 29],
22+
[2, 0],
23+
[0, 0]
2024
])('returns false for %j and %i', (inputA, inputB) => {
2125
expect(CoPrimeCheck(inputA, inputB)).toBe(false)
2226
expect(CoPrimeCheck(inputB, inputA)).toBe(false)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy