Skip to content

algorithm: pronic number #82

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

Merged
merged 2 commits into from
Dec 13, 2022
Merged
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
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
24 changes: 24 additions & 0 deletions maths/pronic_number.ts
Original file line number Diff line number Diff line change
@@ -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 }
5 changes: 5 additions & 0 deletions maths/test/pronic_number.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})