| Bytes | Lang | Time | Link |
|---|---|---|---|
| 015 | AWK | 250908T143721Z | xrs |
| 002 | Thunno 2 t | 230622T170456Z | The Thon |
| 036 | ><> Fish | 221104T153525Z | mousetai |
| 004 | Japt h | 210806T162654Z | Shaggy |
| 075 | Go | 221103T190746Z | bigyihsu |
| nan | Fig | 221103T204141Z | south |
| 009 | Charcoal | 220302T004135Z | jixperso |
| 004 | Vyxal | 220302T140502Z | Alan Bag |
| 003 | 05AB1E | 220302T081936Z | Kevin Cr |
| 004 | Husk | 211011T142904Z | scpchick |
| 013 | braingolf | 170530T080856Z | Mayube |
| 131 | COBOL GNU | 211023T162746Z | Eternal |
| 003 | APL Dyalog Classic | 211023T082117Z | wasif |
| 003 | Vyxal | 211011T222524Z | emanresu |
| 011 | TIBasic | 211010T231627Z | Youserna |
| 006 | Keg | 190917T231025Z | user8505 |
| 094 | MBASIC | 181005T173915Z | wooshiny |
| 005 | Ohm v2 | 181005T155152Z | ThePlasm |
| 008 | K ngn/k | 180621T133554Z | ngn |
| 009 | K oK | 180619T061214Z | mkst |
| 066 | QBasic 1.1 | 180619T125919Z | Erik the |
| 015 | Hexagony | 180619T111942Z | Adyrem |
| 069 | Excel VBA | 180619T123316Z | Taylor R |
| 069 | Forth gforth | 180618T214548Z | reffu |
| 037 | JavaScript | 180618T203604Z | Oliver |
| 037 | dc | 180411T131528Z | brhfl |
| 007 | Retina | 180411T041315Z | Leo |
| 057 | Tcl | 170715T175505Z | sergiol |
| 009 | APL Dyalog | 170529T012322Z | Uriel |
| 015 | PHP | 161027T140805Z | Jör |
| 007 | Pyth | 161030T175321Z | Yotam Sa |
| 008 | J | 161102T070925Z | miles |
| 008 | Labyrinth | 161101T224410Z | Robert H |
| 020 | Python | 161027T142007Z | Jonathan |
| 063 | Java 7 | 161027T141626Z | Geobits |
| 003 | Jelly | 161027T140306Z | Jonathan |
| 024 | Factor | 161028T120925Z | cat |
| 029 | R | 161027T140319Z | Billywob |
| 015 | Perl | 161028T095041Z | Ton Hosp |
| 079 | C# | 161027T163651Z | Pete Ard |
| 152 | Racket | 161028T022752Z | rnso |
| 029 | Perl 6 | 161027T224851Z | Brad Gil |
| 032 | Element | 161027T224758Z | PhiNotPi |
| 012 | Julia | 161027T194251Z | Martin E |
| 034 | Haskell | 161027T172001Z | Laikoni |
| 028 | Perl | 161027T142537Z | Riley |
| 010 | JavaScript ES6 | 161027T141813Z | Johan Ka |
| 013 | CJam | 161027T143358Z | Erik the |
| 038 | JavaScript ES6 | 161027T140908Z | Arnauld |
| 015 | Retina | 161027T145929Z | Martin E |
| 011 | Mathematica | 161027T143943Z | Martin E |
| 029 | C | 161027T142102Z | Karl Nap |
| 057 | Groovy | 161027T142913Z | Magic Oc |
| 012 | Ruby | 161027T143202Z | TuxCraft |
| 006 | 05AB1E | 161027T140517Z | Emigna |
| 045 | Python | 161027T142302Z | xenia |
| 003 | MATL | 161027T142109Z | DJMcMayh |
| 051 | Python 2 | 161027T140556Z | Daniel |
| 009 | Brachylog | 161027T141131Z | Fatalize |
| 001 | Pyke | 161027T140357Z | Blue |
AWK, 15 bytes
1,$0=1+($0-1)%9
Or the hard way (51):
{for(;$0>9;$0=s)for(s=0;$0;$0=int($0/10))s+=$0%10}1
Thunno 2 t, 2 bytes
9B
Port of Jonathan Allan's Jelly answer.
Explanation
9B # Implicit input
B # Convert the input to a
9 # list of digits in base 9
# Implicit output of last item
><> (Fish), 36 bytes
>0$:1(?v:&a%+&a,:1%-20.
^v?(a:~<
n<;
Try it online! - Interactive Version
Expects input as a number pushed onto the stack in advance.
Explanation
There are 2 basic loops, one for summing the digits and one for checking if the number is less than 10 yet.
:1(?v
Checks if the number is less than 1, if not all the digits are summed.
:&a%+&a,:1%
Add the modulo to the accumulator, and then push the division again. We subtract the number %1 to make it a integer.
20.
Skip the first 3 letters of the bottom row.
^v?(a:~<
n<;
If the number is less than 10 (a is 10 in fish, it uses hexadecimal), print it and exit. Otherwise, go back to the start of the program with the number pushed to the stack.
>0$
Push the accumulator to the second from first spot on the stack.
Japt -h, 6 4 bytes
Æ=ìx
Æ=ìx :Implicit input of integer U
Æ :Map the range [0,U)
= : Reassign to U
ì : Convert to digit array
x : Reduce by addition
:Implicit output of last element
Go, 75 bytes
func f(n int)int{if n<10{return n}
k:=0
for;n>0;n/=10{k+=n%10}
return f(k)}
Go, Modulus solution, 29 bytes
func(n int)int{return^-n%9+1}
Fig, \$4\log_{256}(96)\approx\$ 3.292 bytes
}%9{
}%9{
{ # decrement with implicit input
%9 # mod 9
} # increment
Charcoal, 9 bytes
⁺﹪⁻N¹¦⁹¦¹
Explanation:
⁻N¹ - take a integer input and subtract one from it
﹪ - modulo function
⁺ - addition function which given to it n-1%9 and 1
⁹ - number 9 which is like 10-1
¦ - just a argument separator
PS: You could have reduced the argument separator by writing it in this order:
⁺¹﹪⁻¹N⁹ but 7 is not a cool length to have, Also you could put a I before the whole thing to cast the result to printable integer value but since the numbers are represented as - characters in charcoal i ignored that.
05AB1E, 3 bytes
ΔSO
Try it online or verify all test cases.
Or a minor alternative:
Δ1ö
Try it online or verify all test cases.
Explanation:
Δ # Loop until the result no longer changes,
# using the (implicit) input-integer in the first iteration
S # Convert it to a list of digits
O # Sum those together
# (after which the resulting digit is output implicitly)
Δ # Loop until the result no longer changes,
# using the (implicit) input-integer in the first iteration
1ö # Convert it from base-10 to base-1
# (which is a non-vectorizing way to sum an integer's digits in 05AB1E)
# (after which the resulting digit is output implicitly)
Husk, 4 bytes
Recursive method (4 bytes) (Credit to @ovs)
ωoΣd
# implicit parameter ⁰ (refers to the last parameter)
d # list of digits in base 10
Σd # sum of list
oΣd # compose the two functions
ωoΣd # repeat until the function returns the same result as the previous one
Modulus method (4 bytes)
→%9←
# implicit parameter ⁰ (refers to the last parameter)
← # previous number (n - 1)
%9← # modulus by 9
→%9← # next number (n + 1)
braingolf, 20 13 bytes
[Rdl1-M&+v>]R
Try it online!
Links to the braingolf JS interpreter in TIO
Explanation
[Rdl1-M&+v>]R Implicit input from command-line args to stack
[..........]R Loop. Always runs once, will continue to run as long as the bottom value on the active stack is > 0
R Return to main stack, does nothing if already on main stack
d Pop top of stack, split into digits, push digits
l Push length of stack
1- Decrement top of stack
M Pop top of stack and push to next stack
&+ Sum entire stack (all digits of input)
v Switch active stack to next stack
> Move top of stack to bottom
Decrementing the stack length, moving it to the second stack, and switching to the second stack before the end of the loop serves to use the decremented length as the loop counter. ie when the length is 1 (decremented to 0) the loop terminates.
COBOL (GNU), 131 bytes
PROGRAM-ID.A.DATA DIVISION.
WORKING-STORAGE SECTION.
01 N PIC 9(9).
PROCEDURE DIVISION.ACCEPT N.COMPUTE N=FUNCTION REM(N- 1,9)+ 1
Explanation :
PROGRAM-ID.A.DATA DIVISION.
* The first line is necessary and can't be removed
WORKING-STORAGE SECTION.
* sadly so is this (accept input / output)
01 N PIC 9(9).
* This accepts input N that is upto 999,999,999 (output is via same)
PROCEDURE DIVISION.
* Time to start working on program itself.
ACCEPT N.
* Accepts the input from stdin.
COMPUTE N = FUNCTION REM(N - 1, 9) + 1
* compute n such that it is mod of n - 1 and 9 and then add one (standard forumla of --N%9+1
Output is via display N.
APL (Dyalog Classic), 3 bytes
9⊤⊢
Anonymous tacit prefix fork train.
⊤ ⍝ Tail of base conversion of
⊢ ⍝ right argument to
9 ⍝ base 9
TI-Basic, 11 bytes
1+9fPart((Ans-1)/9
Takes input in Ans.
Keg, 6 bytes(SBCS on Keg wiki)
¿;9%1+
Explanation:
¿# Take implicit input
;9%1+# Digital Root Formula
# Implicit output
MBASIC, 105 94 bytes
1 INPUT N
2 A$=STR$(N):N=0:FOR I=1 TO LEN(A$):N=N+VAL(MID$(A$,I,1)):NEXT:IF N>9 THEN 2
3 PRINT N
Output:
? 495106
7
? 59613
6
? 6801
6
Explanation:
Convert input to a string, then walk the string, adding each digit to a total. If the resulting total has more than 1 digit, repeat the process. Otherwise, print the total.
Okay, so it's not APL. But it will run on an 8-bit CP/M system. :-)
Ohm v2, 5 bytes
ì‹9%›
Explanation:
ì‹9%›
ì Takes input as integer
‹ Decrements
9% Modulus 9
› Increment
K (ngn/k), 8 bytes
(+/10\)/
this is based on @streetster's oK answer but uses a feature specific to ngn/k: 10\x is the list of digits of x
K (oK), 9 bytes
Solution:
(+/.:'$)/
Explanation:
Super straightforward. Break number into digits and sum up - do this until the result converges:
(+/.:'$)/ / the solution
( )/ / do this until result converges
$ / string, 1234 => "1234"
.:' / value each, "1234" => 1 2 3 4
+/ / sum over, 1 2 3 4 => 10
QBasic 1.1, 66 bytes
INPUT N
WHILE N>9
M=N
N=0
WHILE M
N=N+M MOD 10
M=M\10
WEND
WEND
?N
Hexagony, 19 15 bytes
.?<9{(/>!@!/)%'
More Readable:
. ? <
9 { ( /
> ! @ ! /
) % ' .
. . .
-3 bytes by taking a different approach, making the 0 edge case trivial.
-1 byte by fixing 0 edge case bug
Using the formula ((n-1) mod 9) + 1 like a lot of other solutions aswell.
Excel VBA, 69 bytes
An anonymous VBE immediate window function that takes input from range [A1] and outputs to the console.
n=[A1]:While n>9:s=0:For i=1To Len(n):s=s+Mid(n,i,1):Next:n=s:Wend:?n
Test Function
For each x in Array(1,45,341,6801,59613,495106):[A1]=x:n=[A1]:While n>9:s=0:For i=1To Len(n):s=s+Mid(n,i,1):Next:n=s:Wend:?x"->"n:Next
1 -> 1
45 -> 9
341 -> 8
6801 -> 6
59613 -> 6
495106 -> 7
Forth (gforth), 69 bytes
: f begin 0 swap begin 10 /mod >r + r> ?dup 0= until dup 10 < until ;
Explanation
- Place sum (starting at 0) on stack
- Get remainder of number divided by 10
- Add to sum
- Replace number with itself divided by 10
- Repeat steps 2-4 until number equals 0
- Using sum as new starting number, repeat steps 1-5 until result is less than 10
Code Explanation
begin \ start outer loop
0 swap \ place sum variable and move it down the stack
begin \ start inner loop
10 /mod \ get quotient and remainder of number/10
>r + \ temporarily "hide" quotient on return stack and add remainder to sum
r> ?dup \ retrieve quotient from return stack and duplicate if != 0
0= until \ end inner loop if sum is equal to 0
dup 10 < \ duplicate current "root" and check if less than 10
until \ end outer loop if < 10
JavaScript, 37 bytes
Input is taken as a string.
f=n=>n>9?f(eval([...n].join`+`)+""):n
dc, 37 bytes
[[A~rdZ1<D]dsDx[+z1<S]dsSxdZ1<M]dsMxp
[A~rdZ1<D]dsDx decompose. Divide by 10 leaving quotient & remainder on stack until the value on the top of the stack is a single digit.
[+z1<S]dsSx sum. Add two topmost stack values until stack depth is one.
Macro M contains both of those, and dZ1<M to keep running itself until the final result is a single digit. p to print.
Retina, 7 bytes
{`.
*
.
I see lots of mathematical solutions, but in Retina the straightforward approach seems to be the best one.
Explanation
{` makes the whole program run in a loop until the string doesn't change anymore. The loop consists of two stages:
.
*
Convert each digit to unary.
.
Count the number of characters (=convert the unary number to decimal).
This works because converting each digit to unary with no separator between digits creates a single unary number which is equal to the sum of all digits.
PHP, 15 Bytes
<?=--$argn%9+1;
Previous version PHP, 55 Bytes
$n=$argn;while($n>9)$n=array_sum(Str_split($n));echo$n;
Pyth - 7 4 6 7 bytes
Not the best one, but still beats a decent amount of answers:
|ejQ9 9
Like the previous version, but handling also cases of multiples of 9, using logical or.
This version fails the 45 testcase:
ejQ9
Explanation:
jQ9 -> converting the input to base 9
e -> taking the last digit
Try the previous version here!
Previous solutions:
&Qh%tQ9
Explanation:
tQ -> tail: Q-1
%tQ9 -> Modulo: (Q-1)%9
h%tQ9 -> head: (Q-1)%9+1
&Qh%tQ9 -> Logical 'and' - takes the first null value. If Q is 0 - returns zero, otherwise returns the (Q-1)%9+1 expression result
You're invited to try it here!
J, 8 bytes
**1+9|<:
Uses the formula d(n) = ((n-1) mod 9) + 1 with the case d(0) = 0.
Usage
f =: **1+9|<:
(,.f"0) 0 1 45 341 6801 59613 495106
0 0
1 1
45 9
341 8
6801 6
59613 6
495106 7
Explanation
**1+9|<: Input: integer n
<: Decrement n
9| Take it modulo 9
1+ Add 1 to it
* Sign(n) = 0 if n = 0, else 1
* Multiply and return
Labyrinth, 8 bytes
?(_9%)!@
using the equation (n-1)%9+1:
?reads the input as decimal and pushes it to the stack(decrements the top of the stack_pushes a zero onto the top of the stack9push the top of the stack popped times 10 the digit (in this case, 9)%pops y, pops x, pushes x%y)increments the top of the stack!pops the top of the stack and out puts it as a decimal string@terminates the program
Java 7, 63 bytes
int f(int n){int s=0;for(;n>0;n/=10)s+=n%10;return s>9?f(s):s;}
Recursive function which just gets digits with mod/div. Nothing fancy.
Cheap port
of Jonathan Allan's would be a measly 28 bytes:
int f(int n){return~-n%9+1;}
Jelly, 7 5 4 3 bytes
ḃ9Ṫ
TryItOnline! or all test cases
How?
The digital root is known to obey the formula (n-1)%9+1.
This is the same as the last digit in bijective base 9
(and due to implementation that 0ḃ9=[] and []Ṫ=0 this handles the edge-case of zero).
ḃ9Ṫ - Main link: n
ḃ9 - convert to bijective base 9 digits (a list)
Ṫ - tail (get the last digit)
Factor, 24
Smart, mathy answer.
[ neg bitnot 9 mod 1 + ]
63 for dumb iterative solution:
[ [ dup 9 > ] [ number>string >array [ 48 - ] map sum ] while ]
R, 72 67 29 bytes
Edit: Thanks to @rturnbull for shaving off two bytes.
n=scan();`if`(n%%9|!n,n%%9,9)
Perl, 15 bytes
Includes +2 for -lp
Give input on STDIN
root.pl <<< 123
root.pl
#!/usr/bin/perl -lp
$_&&=~-$_%9+1
This is the boring solution that has already been given in many languages, but at least this version supports 0 too
More interesting doing real repeated additions (though in another order) is in fact only 1 byte longer:
#!/usr/bin/perl -p
s%%$_+=chop%reg
C#, 79 Bytes
Golfed:
string R(string i){while(i.Length>1){i=i.Sum(o=>int.Parse(o+""))+"";}return i;}
Ungolfed:
string R(string i)
{
while (i.Length > 1)
{
i = i.Sum(o => int.Parse(o + ""))+"";
}
return i;
}
Testing:
var printTheDigitalRoot = new PrintTheDigitalRoot();
Console.WriteLine(printTheDigitalRoot.S("1")); //1
Console.WriteLine(printTheDigitalRoot.S("45")); //9
Console.WriteLine(printTheDigitalRoot.S("341")); //8
Console.WriteLine(printTheDigitalRoot.S("6801")); //6
Console.WriteLine(printTheDigitalRoot.S("59613")); //6
Console.WriteLine(printTheDigitalRoot.S("495106")); //7
Racket 152 bytes
(let p((ol'())(n n))(let*-values(((q r)(quotient/remainder n 10))((l)(cons r ol)))
(if(= q 0)(begin(let((s(apply + l)))(if(< s 10)s(p'()s))))(p l q)))))
Ungolfed:
(define (f n)
(let loop ((ol '())
(n n))
(let*-values (((q r) (quotient/remainder n 10))
((l) (cons r ol)))
(if (= q 0)
(begin
(let ((s (apply + l)))
(if (< s 10)
s
(loop '() s))))
(loop l q))
)))
Simpler version:
(define (f1 N)
(define (getDigitList n) ; sub-fn to get digits
(let loop ((ol '())
(n n))
(let-values (((q r) (quotient/remainder n 10)))
(if (= q 0) (cons r ol)
(loop (cons r ol) q)))))
(let loop2 ((n N)) ; actual fn
(define s (apply + (getDigitList n))) ; get sum of digits
(if (< s 10)
s
(loop2 s))))
Testing:
(f 1)
(f 45)
(f 341)
(f 6801)
(f 59613)
(f 495106)
Output:
1
9
8
6
6
7
Perl 6, 29 bytes
{($_,*.comb.sum...10>*)[*-1]}
Expanded:
{ # bare block lambda with implicit parameter 「$_」
( # generate a sequence
$_, # starting with the input
*.comb.sum # Whatever lambda that splits into digits, and finds sum
... # keep doing that
10 > * # until it is less than 10
)[ * - 1 ] # get the last value
}
Element, 32 bytes
_2:1-+9/3:0<!{1-+2:0<!}1+-+9-*+`
This is using the typical closed-form formula, although it is noticeably more painful since Element lacks any rounding functionality.
_2:1-+9/3:0<!{1-+2:0<!}1+-+9-*+`
_2: make two copies of input
1-+9/ for one copy, subtract 1 and divide by 9
3:0<!{1-+2:0<!}1+-+ floor it
9-* multiply by -9
+` add to the original input value, then output
Julia, 12 bytes
!n=mod1(n,9)
or
n->mod1(n,9)
mod1 is an alternative to mod which maps to the range [1, n] instead of [0, n).
Haskell, 35 34 bytes
until(<10)$sum.map(read.pure).show
Explanation:
until(<10)$sum.map(read.pure).show
show -- convert int to string
map( ). -- turn each char (digit) into
pure -- a string
read. -- and then a number
sum. -- sum up the list of numbers
until(<10)$ -- repeat until the result is < 10
Perl 34 28 bytes
Includes +1 for -p
s/./+$&/g,$_=eval while/../
Uses the method described in the question.
Example:
$ echo -n 495106 | perl -p DigitalRoot.pl
7
JavaScript (ES6), 16 10 bytes
n=>--n%9+1
Test cases
let f =
n=>--n%9+1
console.log(f(1)); // -> 1
console.log(f(45)); // -> 9
console.log(f(341)); // -> 8
console.log(f(6801)); // -> 6
console.log(f(59613)); // -> 6
console.log(f(495106)); // -> 7
CJam, 19 13 bytes
r{:~:+_s\9>}g
Explanation:
r{:~:+_s\9>}g Code
r Get token
{:~:+_s\9>} Block: :~:+_s\9>
~ Eval
: Map
+ Add
: Map
_ Duplicate
s Convert to string
\ Swap
9 9
> Greater than
g Do while (pop)
Thanks to 8478 (Martin Ender) for -6 bytes.
CJam, 6 bytes
ri(9%)
Suggested by 8478 (Martin Ender). Interpreter
I was thinking about it, but Martin just got it before me. Explanation:
ri(9%) Code
r Get token
i Convert to integer
( Decrement
9 9
% Modulo
) Increment
JavaScript (ES6), 41 38 bytes
Saved 3 bytes, thanks to Bassdrop Cumberwubwubwub
Takes and returns a string.
f=s=>s[1]?f(''+eval([...s].join`+`)):s
Test cases
f=s=>s[1]?f(''+eval([...s].join`+`)):s
console.log(f("1")); // -> 1
console.log(f("45")); // -> 9
console.log(f("341")); // -> 8
console.log(f("6801")); // -> 6
console.log(f("59613")); // -> 6
console.log(f("495106")); // -> 7
Retina, 15 bytes
.+
$*
1{9}\B
1
Try it online! (The first line enables a linefeed-separated test suite.)
Explanation
.+
$*
Convert input to unary.
(1{9})*\B
Take 1-based modulo by removing nines that have at least one more character after them.
1
Count the remaining number of 1s to convert back to decimal.
Mathematica, 27 11 bytes
Mod[#,9,1]&
Mathematica's Mod takes a third parameter as an offset of the resulting range of the modulo. This avoids decrementing the input and incrementing the output.
C, 64 29 bytes
C port from Jonathan Allan's answer (with special case 0).
f(i){return i>0?~-i%9+1:0;}
Previous 64 byte code:
q(i){return i>9?i%10+q(i/10):i;}
f(i){i=q(i);return i>9?f(i):i;}
q takes the cross sum and f repeats taking the cross sum until a single digit.
Groovy, 57 Bytes
{n->for(;(n=(""+n).collect{(int)it-48}.sum())/10>1;){};n}
Repeatedly converts to string, sums the ascii conversion of the digits and continues while the resultant integer divided by 10 is greater than 1. Then it returns the mutated input.
Tried recursion too, cost more bytes though:
x={i->i?i%10+x(i.intdiv(10)):0};y={i->x(i)/10<1?x(i):y(x(i))}
Ruby, 12 bytes
->n{~-n%9+1}
05AB1E, 6 bytes
[SODg#
Explanation
[ # infinite loop
S # split into digits
O # sum digits
Dg# # if length == 1: break
Python, 45 bytes
f=lambda x:x[1:]and f(`sum(map(int,x))`)or x
Takes the argument as a string.
MATL, 3 bytes
9X\
A lot of (now deleted answers) tried using modulo 9 to get the result. This is a great shortcut, but unfortunately does not work for multiples of 9. MATL has a function for modulo on the interval [1, n]. Using this modulo, we have 1 % 3 == 1, 2 % 3 == 2, 3 % 3 == 3, 4 % 3 == 1, etc. This answer simply takes the input modulo nine using this custom modulo.
Python 2, 54 51 bytes
i=input()
while~-len(i):i=`sum(map(int,i))`
print i
Thanks to Oliver and Karl Napf for helping me save 3 bytes
Brachylog, 9 bytes
#0|@e+:0&
Explanation
#0 Input = Output = a digit
| OR
@e Split the input into a list of digits
+ Sum
:0& Call this predicate recursively
Alternative approach, 11 bytes
This one uses the meta-predicate i - Iterate to call I times the predicate {@e+} on the input. This will try values of I from 0 to infinity until one makes it so that the output of i is a single digit which makes #0 true.