Digital root calculator

From Esolang
Jump to: navigation, search

A digital root calculator reads digits as input, calculates the digital root, and finally outputs the digital root digit (preferably with a UNIX newline). The digital root of a number is the reduction of the number to a single digit through repeated summing.

Writing a program to calculate digital root is useful for testing an esoteric programming language's overall performance and speed, as well as its functionality in input/output, memory, looping, and other things.

A digital root calculator is often quite easy to program, as well.

Simple calculation

Here's how the digital root is calculated for base 10:

Take any non-negative integer (can be zero as well). Add all of its digits together. If the result is bigger than 9, add all the digits of the result together to get another result. Continue this until the result has only one digit (0-9).

Efficient calculation

The digit root of n is equal to 1+(n-1)%9 (where % is the modulo operator). From this we can see that the digit root of a number can be calculated one digit at a time, by maintaining the digital root of the digits read so far. This is especially useful in languages without any built-in mathematical operators, such as Thue and Gravity.


Digital root of 34758 is 9:

Simple         Efficient
------         ---------
34758          1+(3-1)%9   = 3
3+4+7+5+8      1+(3+4-1)%9 = 7
7+7+5+8        1+(7+7-1)%9 = 5
14+5+8         1+(5+5-1)%9 = 1
1+4+5+8        1+(1+8-1)%9 = 9
5+5+8          9

See Also

External resources