diff --git a/DIRECTORY.md b/DIRECTORY.md index 6ad6b372..731d3433 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -26,6 +26,7 @@ * [Is Odd](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_odd.ts) * [Lowest Common Multiple](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/lowest_common_multiple.ts) * [Perfect Square](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/perfect_square.ts) + * [Pronic Number](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/pronic_number.ts) * [Radians To Degrees](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/radians_to_degrees.ts) * Series * [Hexagonal Numbers](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/series/hexagonal_numbers.ts) diff --git a/maths/pronic_number.ts b/maths/pronic_number.ts new file mode 100644 index 00000000..3709c6b5 --- /dev/null +++ b/maths/pronic_number.ts @@ -0,0 +1,24 @@ +/** + * @function PronicNumber + * @description Checks whether a given number is a pronic number or not + * @summary Pronic numbers, or oblong numbers as they are often referred to as, + * are numbers which are the product of two consecutive integers. That is, + * they are numbers of the form n*(n+1) + * + * For example, 20 is a pronic number since 20 = 4 * 5 + * @param num The number to check for being pronic + * @returns {boolean} Whether the number is pronic or not + * @see [Wikipedia](https://en.wikipedia.org/wiki/Pronic_number) + * @example PronicNumber(20) = true + * @example PronicNumber(30) = true + * @example PronicNumber(49) = false + */ +const PronicNumber = (n: number) => { + if (isNaN(n)) throw new Error('The input needs to be a number') + if (!Number.isInteger(n) || n < 0) throw new Error('The input needs to be a non-negative integer') + if (n === 0) return true + + return !Number.isInteger(Math.sqrt(n)) && Math.floor(Math.sqrt(n)) * Math.ceil(Math.sqrt(n)) === n +} + +export { PronicNumber } diff --git a/maths/test/pronic_number.test.ts b/maths/test/pronic_number.test.ts new file mode 100644 index 00000000..80b5a1fc --- /dev/null +++ b/maths/test/pronic_number.test.ts @@ -0,0 +1,5 @@ +import { PronicNumber } from '../pronic_number' + +test.each([[0, true], [10, false], [30, true], [69, false], [420, true]])('Pronic Number', (number, result) => { + expect(PronicNumber(number)).toBe(result) +})