diff --git a/maths/check_co_prime.ts b/maths/check_co_prime.ts new file mode 100644 index 00000000..5c868964 --- /dev/null +++ b/maths/check_co_prime.ts @@ -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 +} diff --git a/maths/test/check_co_prime.test.ts b/maths/test/check_co_prime.test.ts new file mode 100644 index 00000000..4e02e805 --- /dev/null +++ b/maths/test/check_co_prime.test.ts @@ -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) + }) +})