Skip to content

Commit c570405

Browse files
feat: add digital root algorithm
1 parent 5c39e87 commit c570405

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎Maths/DigitalRoot.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @function digitalRoot
3+
* @description The digital root is the single digit obtained by repeatedly
4+
* summing the digits of a number until a single digit is reached.
5+
* For example, 493: 4+9+3=16, 1+6=7 — digital root is 7.
6+
* @param {number} n - A non-negative integer
7+
* @returns {number} - The digital root of n
8+
* @see https://en.wikipedia.org/wiki/Digital_root
9+
* @example digitalRoot(493) => 7
10+
* @example digitalRoot(999) => 9
11+
* @example digitalRoot(0) => 0
12+
*/
13+
const digitalRoot = (n) => {
14+
if (!Number.isInteger(n) || n < 0) {
15+
throw new TypeError('Input must be a non-negative integer')
16+
}
17+
if (n === 0) return 0
18+
return n % 9 === 0 ? 9 : n % 9
19+
}
20+
21+
export { digitalRoot }

‎Maths/test/DigitalRoot.test.js‎

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

0 commit comments

Comments
 (0)