Skip to content

Commit ee52fb6

Browse files
feat: add pronic number algorithm
1 parent 5c39e87 commit ee52fb6

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎Maths/PronicNumber.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @function isPronicNumber
3+
* @description A pronic number (also known as an oblong number) is a
4+
* number that is the product of two consecutive integers.
5+
* Examples: 0, 2, 6, 12, 20, 30, 42...
6+
* @param {number} n - A non-negative integer
7+
* @returns {boolean} - True if n is a pronic number, false otherwise
8+
* @see https://en.wikipedia.org/wiki/Pronic_number
9+
* @example isPronicNumber(6) => true
10+
* @example isPronicNumber(12) => true
11+
* @example isPronicNumber(10) => false
12+
*/
13+
const isPronicNumber = (n) => {
14+
if (!Number.isInteger(n) || n < 0) {
15+
throw new TypeError('Input must be a non-negative integer')
16+
}
17+
const sqrt = Math.floor(Math.sqrt(n))
18+
return sqrt * (sqrt + 1) === n
19+
}
20+
21+
export { isPronicNumber }

‎Maths/test/PronicNumber.test.js‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { isPronicNumber } from '../PronicNumber.js'
2+
3+
describe('isPronicNumber', () => {
4+
test('0 is a pronic number (0 x 1)', () => {
5+
expect(isPronicNumber(0)).toBe(true)
6+
})
7+
8+
test('2 is a pronic number (1 x 2)', () => {
9+
expect(isPronicNumber(2)).toBe(true)
10+
})
11+
12+
test('6 is a pronic number (2 x 3)', () => {
13+
expect(isPronicNumber(6)).toBe(true)
14+
})
15+
16+
test('12 is a pronic number (3 x 4)', () => {
17+
expect(isPronicNumber(12)).toBe(true)
18+
})
19+
20+
test('20 is a pronic number (4 x 5)', () => {
21+
expect(isPronicNumber(20)).toBe(true)
22+
})
23+
24+
test('30 is a pronic number (5 x 6)', () => {
25+
expect(isPronicNumber(30)).toBe(true)
26+
})
27+
28+
test('42 is a pronic number (6 x 7)', () => {
29+
expect(isPronicNumber(42)).toBe(true)
30+
})
31+
32+
test('1 is NOT a pronic number', () => {
33+
expect(isPronicNumber(1)).toBe(false)
34+
})
35+
36+
test('10 is NOT a pronic number', () => {
37+
expect(isPronicNumber(10)).toBe(false)
38+
})
39+
40+
test('15 is NOT a pronic number', () => {
41+
expect(isPronicNumber(15)).toBe(false)
42+
})
43+
44+
test('throws TypeError for negative input', () => {
45+
expect(() => isPronicNumber(-1)).toThrow(TypeError)
46+
})
47+
48+
test('throws TypeError for float input', () => {
49+
expect(() => isPronicNumber(6.5)).toThrow(TypeError)
50+
})
51+
})

0 commit comments

Comments
 (0)