← 输入框|github.com|刷新
Skip to content
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
21 changes: 21 additions & 0 deletions Maths/PronicNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @function isPronicNumber
* @description A pronic number (also known as an oblong number) is a
* number that is the product of two consecutive integers.
* Examples: 0, 2, 6, 12, 20, 30, 42...
* @param {number} n - A non-negative integer
* @returns {boolean} - True if n is a pronic number, false otherwise
* @see https://en.wikipedia.org/wiki/Pronic_number
* @example isPronicNumber(6) => true
* @example isPronicNumber(12) => true
* @example isPronicNumber(10) => false
*/
const isPronicNumber = (n) => {
if (!Number.isInteger(n) || n < 0) {
throw new TypeError('Input must be a non-negative integer')
}
const sqrt = Math.floor(Math.sqrt(n))
return sqrt * (sqrt + 1) === n
}

export { isPronicNumber }
51 changes: 51 additions & 0 deletions Maths/test/PronicNumber.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { isPronicNumber } from '../PronicNumber.js'

describe('isPronicNumber', () => {
test('0 is a pronic number (0 x 1)', () => {
expect(isPronicNumber(0)).toBe(true)
})

test('2 is a pronic number (1 x 2)', () => {
expect(isPronicNumber(2)).toBe(true)
})

test('6 is a pronic number (2 x 3)', () => {
expect(isPronicNumber(6)).toBe(true)
})

test('12 is a pronic number (3 x 4)', () => {
expect(isPronicNumber(12)).toBe(true)
})

test('20 is a pronic number (4 x 5)', () => {
expect(isPronicNumber(20)).toBe(true)
})

test('30 is a pronic number (5 x 6)', () => {
expect(isPronicNumber(30)).toBe(true)
})

test('42 is a pronic number (6 x 7)', () => {
expect(isPronicNumber(42)).toBe(true)
})

test('1 is NOT a pronic number', () => {
expect(isPronicNumber(1)).toBe(false)
})

test('10 is NOT a pronic number', () => {
expect(isPronicNumber(10)).toBe(false)
})

test('15 is NOT a pronic number', () => {
expect(isPronicNumber(15)).toBe(false)
})

test('throws TypeError for negative input', () => {
expect(() => isPronicNumber(-1)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => isPronicNumber(6.5)).toThrow(TypeError)
})
})
Loading