Skip to content

feat: Added digital root algorithm(also with recursion) #1754

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
34 changes: 34 additions & 0 deletions Maths/DigitalRoot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
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
* @example digitalRoot(-999) // returns 9
* @example digitalRoot(0) // returns 0
*/
if (num < 0) num = -num;
return num === 0 ? num : 1 + ((num - 1) % 9);
};
/*------------------------------------------------------------------------------------*/

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 digitalRootRecursive(456) // returns 6
* @example digitalRootrecursive(999) // returns 9
* @example digitalRootRecursive(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

// Recursive case: sum digits and continue to reduce
const sum = (num % 10) + digitalRootRecursive(Math.floor(num / 10));
return digitalRootRecursive(sum); // Call digitalRoot recursively to reduce to single digit
};

export { digitalRoot, digitalRootRecursive };
Loading