Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
ankana2113 wants to merge5 commits intoTheAlgorithms:master
base:master
Choose a base branch
Loading
fromankana2113:digital-root
Open
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletionsMaths/DigitalRoot.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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

[8]ページ先頭

©2009-2025 Movatter.jp