Skip to content

Commit

Permalink
feat: added digital root algorithm and its recursive implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
ankana2113 authored Oct 26, 2024
1 parent 6d1849a commit a807c36
Showing 1 changed file with 18 additions and 18 deletions.
36 changes: 18 additions & 18 deletions Maths/DigitalRoot.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
export const digitalRoot = (num) => {
/**
* Calculates the digital root of a number in constant time.
* @param {number} num - The number to compute the digital root for.
* @returns {number} The digital root of the given number.
*
* @example
* digitalRoot(456) // returns 6
* digitalRoot(-999) // returns 9
* digitalRoot(0) // returns 0
*/
* Calculates the digital root of a number in constant time.
* @param {number} num - The number to compute the digital root for.
* @returns {number} The digital root of the given number.
*
* @example
* digitalRoot(456) // returns 6
* digitalRoot(-999) // returns 9
* digitalRoot(0) // returns 0
*/
if (num < 0) num = -num;
return num === 0 ? num : 1 + ((num - 1) % 9);
};
/*------------------------------------------------------------------------------------*/

export const digitalRootRecursive = (num) => {
/**
* Calculates the digital root of a number using recursion.
* @param {number} num - The number to compute the digital root for.
* @returns {number} The digital root of the given number.
*
* @example
* digitalRoot(456) // returns 6
* digitalRoot(999) // returns 9
* digitalRoot(0) // returns 0
*/
* Calculates the digital root of a number using recursion.
* @param {number} num - The number to compute the digital root for.
* @returns {number} The digital root of the given number.
*
* @example
* digitalRoot(456) // returns 6
* digitalRoot(999) // returns 9
* digitalRoot(0) // returns 0
*/
if (num < 0) num = -num; // Handle negative input by converting to positive
if (num < 10) return num; // Base case for single-digit number

Expand Down

0 comments on commit a807c36

Please sign in to comment.