Skip to content

Commit 6be6a4b

Browse files
SpiderMathactions-userappgurueu
authored
feat: Added implementation for ugly numbers (#146)
* Update DIRECTORY.md * Added ugly numbers 🧟 * Update DIRECTORY.md * 🚀 feat: use generator for ugly nums * Formatting filenames ad9848e * Update DIRECTORY.md * Test first 11 ugly numbers * fix oopsie --------- Co-authored-by: autoprettier <actions@github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
1 parent be813fb commit 6be6a4b

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@
124124
* [Hexagonal Numbers.Test](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/series/test/hexagonal_numbers.test.ts)
125125
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/sieve_of_eratosthenes.ts)
126126
* [Signum](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/signum.ts)
127+
* [Ugly Numbers](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/ugly_numbers.ts)
127128
* [Zellers Congruence](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/zellers_congruence.ts)
128129

129130
## Other

maths/test/ugly_numbers.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { UglyNumbers } from '../ugly_numbers';
2+
3+
test('Ugly Numbers', () => {
4+
const uglyNumbers = UglyNumbers();
5+
expect(Array(11).fill(undefined).map(() => uglyNumbers.next())).toEqual([1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15]);
6+
})

maths/ugly_numbers.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @generator
3+
* @description Generates ugly numbers
4+
* @summary Ugly numbers are natural numbers whose only prime factors are 2, 3 and 5.
5+
* They can be represented in the form 2^a * 3^b * 5*c. By convention, 1 is also considered to be
6+
* an ugly number.
7+
* The first few terms of the sequence are: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20...
8+
*
9+
* For the provided n, the nth ugly number shall be computed.
10+
* @see [GeeksForGeeks](https://www.geeksforgeeks.org/ugly-numbers/)
11+
*/
12+
function* UglyNumbers() {
13+
yield 1
14+
15+
let idx2 = 0, idx3 = 0, idx5 = 0
16+
const uglyNumbers = [1]
17+
18+
let nextx2: number, nextx3: number, nextx5: number, nextUglyNum: number
19+
20+
while(true) {
21+
nextx2 = uglyNumbers[idx2] * 2
22+
nextx3 = uglyNumbers[idx3] * 3
23+
nextx5 = uglyNumbers[idx5] * 5
24+
25+
nextUglyNum = Math.min(nextx2, nextx3, nextx5)
26+
yield nextUglyNum
27+
28+
if(nextx2 === nextUglyNum) idx2++
29+
if(nextx3 === nextUglyNum) idx3++
30+
if(nextx5 === nextUglyNum) idx5++
31+
32+
uglyNumbers.push(nextUglyNum)
33+
}
34+
}
35+
36+
export { UglyNumbers }

0 commit comments

Comments
 (0)