Skip to content

Commit bae1827

Browse files
committed
Added DigitalRoot in Math Module
1 parent 08d8c6b commit bae1827

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Maths/DigitalRootAlgorithm.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Digital Root of n by Recursive Approach
3+
* Time Complexity : O(1) - Mathematical Formula
4+
* Time Complexity : O(log n) - Recursive Approach
5+
* For more info: https://en.wikipedia.org/wiki/Digital_root
6+
*
7+
* Mathematical Formula: DigitalRoot(n)= 1 + (n - 1) mod 9
8+
* Recursive Formula: DigitalRoot(n)= n if n<10 else if digitalRoot(sumOfDigits)
9+
*
10+
* @param {number} n
11+
* @returns {number}- digital root of n
12+
* @description
13+
* The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.
14+
*/
15+
16+
17+
const digitalRoot = (n) => {
18+
if (n === 0) return 0;
19+
return 1 + (n - 1) % 9;
20+
};
21+
22+
const recursiveDigitalRoot = (n) => {
23+
if (n < 10) return n;
24+
let sum = 0;
25+
while (n > 0) {
26+
sum += n % 10;
27+
n = Math.floor(n / 10);
28+
}
29+
return recursiveDigitalRoot(sum);
30+
}
31+
32+
export { digitalRoot,recursiveDigitalRoot };

0 commit comments

Comments
 (0)