Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added function to check co-prime #269

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
29 changes: 29 additions & 0 deletions maths/check_co_prime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { greatestCommonFactor } from './greatest_common_factor'

/**
* @function areCoPrime
* @description Check if two numbers are co-prime
* @param {number} a - first number
* @param {number} b - second number
* @returns {boolean} - true if a and b are co-prime, false otherwise
* @throws {TypeError} - if inputs are not integers
* @throws {Error} - if inputs are zero
* @see https://en.wikipedia.org/wiki/Coprime_integers
* @example areCoPrime(14, 15) => true
*
*/

export const areCoPrime = (a: number, b: number): boolean => {
if (!Number.isInteger(a) || !Number.isInteger(b)) {
throw new TypeError('Inputs must be integers')
}

if (a === 0 || b === 0) {
throw new Error('Inputs must be non-zero')
}

a = Math.abs(a)
b = Math.abs(b)

return greatestCommonFactor([a, b]) === 1
}
23 changes: 23 additions & 0 deletions maths/test/check_co_prime.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { areCoPrime } from '../check_co_prime'

describe('Check if two numbers are co-prime', () => {
test('should return true if two numbers are co-prime', () => {
expect(areCoPrime(14, 15)).toBeTruthy()
expect(areCoPrime(8, 9)).toBeTruthy()
expect(areCoPrime(3, -5)).toBeTruthy()
})

test('should return false if two numbers are not co-prime', () => {
expect(areCoPrime(14, 21)).toBeFalsy()
expect(areCoPrime(8, 12)).toBeFalsy()
expect(areCoPrime(3, 6)).toBeFalsy()
})

test('should throw a TypeError if inputs are not integers', () => {
expect(() => areCoPrime(14.5, 15)).toThrow(TypeError)
})

test('should throw an Error if inputs are zero', () => {
expect(() => areCoPrime(0, 15)).toThrow(Error)
})
})