Skip to content

Commit 3b5598c

Browse files
feat: add ugly number algorithm
1 parent 5c39e87 commit 3b5598c

2 files changed

Lines changed: 81 additions & 0 deletions

File tree

‎Maths/UglyNumber.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @function isUglyNumber
3+
* @description An ugly number is a positive integer whose prime factors
4+
* are limited to 2, 3, and 5.
5+
* Sequence: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
6+
* @param {number} n - A positive integer
7+
* @returns {boolean} - True if n is an ugly number, false otherwise
8+
* @see https://en.wikipedia.org/wiki/Regular_number
9+
* @example isUglyNumber(6) => true
10+
* @example isUglyNumber(8) => true
11+
* @example isUglyNumber(14) => false
12+
*/
13+
const isUglyNumber = (n) => {
14+
if (!Number.isInteger(n) || n < 1) {
15+
throw new TypeError('Input must be a positive integer')
16+
}
17+
let num = n
18+
for (const factor of [2, 3, 5]) {
19+
while (num % factor === 0) {
20+
num = Math.floor(num / factor)
21+
}
22+
}
23+
return num === 1
24+
}
25+
26+
export { isUglyNumber }

‎Maths/test/UglyNumber.test.js‎

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

0 commit comments

Comments
 (0)