A Go implementation of the digital root algorithm that repeatedly sums the digits of a number until a single digit is obtained.
The digital root (also called the repeated digit sum) of a non-negative integer is the single digit obtained by an iterative process of summing digits:
- Sum all digits of the number
- If the result has more than one digit, repeat step 1
- Continue until you get a single digit
- 467 → 4 + 6 + 7 = 17 → 1 + 7 = 8
- 21 → 2 + 1 = 3
- 1000 → 1 + 0 + 0 + 0 = 1
- 1 → 1 (already single digit)
- -36 → 36 → 3 + 6 = 9 (handles negatives by taking absolute value)
✨ Simple & Efficient - Clean recursive implementation
✨ Handles Negatives - Converts to absolute value
✨ Well-Tested - Includes multiple test cases in main()
package main
import (
"fmt"
)
func main() {
result := singleDigit(467)
fmt.Println(result) // Output: 8
}func singleDigit(n int) intParameters:
n(int) - The number to calculate the digital root for
Returns:
- (int) - The single digit digital root
The singleDigit() function:
- Converts negative numbers to their absolute value
- Returns immediately if the number is already single-digit (< 10)
- Sums all digits by converting to string and iterating through characters
- Recursively calls itself on the sum if it's greater than 9
- Returns the final single digit
go run main.goOutput:
8
3
1
1
9
- Time Complexity: O(log n) where n is the input number
- Space Complexity: O(log n) due to recursion depth
The digital root has a mathematical property: For any positive integer n, the digital root equals:
(n - 1) % 9 + 1(when n ≠ 0)
This could be used for a more efficient O(1) implementation, but the current approach is more intuitive.
This project is open source and available under the MIT License.
Created by Israel-light