Skip to content

Commit 7c75beb

Browse files
authored
added digital root algorithm
1 parent 55ff0ad commit 7c75beb

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Diff for: Maths/DigitalRoot.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
export const digitalRoot = (num: number): number => {
2+
/**
3+
* Calculates the digital root of a number in constant time.
4+
* @param {number} num - The number to compute the digital root for.
5+
* @returns {number} The digital root of the given number.
6+
*
7+
* @example
8+
* digitalRoot(456) // returns 6
9+
* digitalRoot(-999) // returns 9
10+
* digitalRoot(0) // returns 0
11+
*/
12+
if (num < 0) num = -num;
13+
return num === 0 ? num : 1 + ((num - 1) % 9);
14+
};
15+
/*------------------------------------------------------------------------------------*/
16+
17+
export const digitalRootRecursive = (num: number): number => {
18+
/**
19+
* Calculates the digital root of a number using recursion.
20+
* @param {number} num - The number to compute the digital root for.
21+
* @returns {number} The digital root of the given number.
22+
*
23+
* @example
24+
* digitalRoot(456) // returns 6
25+
* digitalRoot(999) // returns 9
26+
* digitalRoot(0) // returns 0
27+
*/
28+
if (num < 0) num = -num; // Handle negative input by converting to positive
29+
if (num < 10) return num; // Base case for single-digit number
30+
31+
// Recursive case: sum digits and continue to reduce
32+
const sum = (num % 10) + digitalRootRecursive(Math.floor(num / 10));
33+
return digitalRootRecursive(sum); // Call digitalRoot recursively to reduce to single digit
34+
};

0 commit comments

Comments
 (0)