This is different from My Word can beat up your Word as it is less complex and only requires you to calculate it, and not compare them.
To find the digital root, take all of the digits of a number, add them, and repeat until you get a one-digit number. For example, if the number was 12345, you would add 1, 2, 3, 4, and 5, getting 15. You would then add 1 and 5, giving you 6.
Your task
Given an integer N (0 <= N <= 10000) through STDIN, print the digital root of N.
Test cases
1 -> 1
45 -> 9
341 -> 8
6801 -> 6
59613 -> 6
495106 -> 7
Remember, this is code-golf, so the code with the smallest number of bytes wins.
60 Answers 60
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)
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
Python, (削除) 16 (削除ここまで) 20 bytes
+4 bytes to handle edge case of zero.
lambda n:n and~-n%9+1
-
1\$\begingroup\$ Wow. This is so easy it can be ported to any language. You can even
~-input()%9+1\$\endgroup\$Karl Napf– Karl Napf2016年10月27日 14:30:26 +00:00Commented Oct 27, 2016 at 14:30 -
1\$\begingroup\$ Doesn't work for 0 unfortunately. \$\endgroup\$Emigna– Emigna2016年10月27日 14:37:56 +00:00Commented Oct 27, 2016 at 14:37
-
\$\begingroup\$ @KarlNapf Wouldn't that need a
print? \$\endgroup\$Jonathan Allan– Jonathan Allan2016年10月27日 14:37:58 +00:00Commented Oct 27, 2016 at 14:37 -
\$\begingroup\$ @JonathanAllan Ah, possibly. I just tested it in the REPL environment and that did it. \$\endgroup\$Karl Napf– Karl Napf2016年10月27日 14:41:05 +00:00Commented Oct 27, 2016 at 14:41
-
1\$\begingroup\$ @ the anonymous user who attempted an edit - it would have actually broken the code (made an input of
0result in9rather than0, which is what is catered for by then andpart of the code) furthermore it would have counted as 19 bytes not 13 (since theprintand the space must be counted). \$\endgroup\$Jonathan Allan– Jonathan Allan2018年10月05日 18:21:38 +00:00Commented Oct 5, 2018 at 18:21
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.
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.
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).
PHP, 15 Bytes
<?=--$argn%9+1;
Previous version PHP, 55 Bytes
$n=$argn;while($n>9)$n=array_sum(Str_split($n));echo$n;
-
\$\begingroup\$ Exactly how I did it! \$\endgroup\$CT14.IT– CT14.IT2016年10月27日 14:19:37 +00:00Commented Oct 27, 2016 at 14:19
-
\$\begingroup\$ @CT14.IT I can delete this post if you wish. Your deleted post ws 1 minute earlier and you have only forgot the while loop \$\endgroup\$Jörg Hülsermann– Jörg Hülsermann2016年10月27日 14:27:17 +00:00Commented Oct 27, 2016 at 14:27
-
\$\begingroup\$ Nah the deleted answer was wrong because I didn't read the question properly to start with, I didnt attempt to sum the generated number \$\endgroup\$CT14.IT– CT14.IT2016年10月27日 14:35:36 +00:00Commented Oct 27, 2016 at 14:35
-
2\$\begingroup\$ You can add the trick of other answers
<?=--$argv[1]%9+1?>\$\endgroup\$Crypto– Crypto2016年10月28日 06:37:17 +00:00Commented Oct 28, 2016 at 6:37
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.
R, (削除) 72 67 (削除ここまで) 29 bytes
Edit: Thanks to @rturnbull for shaving off two bytes.
n=scan();`if`(n%%9|!n,n%%9,9)
-
\$\begingroup\$ I recently learned that
ifelsecan be replaced by`if`, with identical behavior, which saves you a couple of bytes. \$\endgroup\$rturnbull– rturnbull2016年10月28日 09:37:46 +00:00Commented Oct 28, 2016 at 9:37 -
\$\begingroup\$ @rturnbull I was always wondering how `
if` worked. Could you give an example or maybe add it to Tips for golfing in ? \$\endgroup\$Billywob– Billywob2016年10月28日 09:41:54 +00:00Commented Oct 28, 2016 at 9:41 -
\$\begingroup\$ The simplest way to understand it is that it's a non-vectorized
ifelse. In this case,`if`(n%%9|!n,n%%9,9)provides identical behavior to the code you've posted. As far as I can tell, this behavior is undocumented! I'll add a comment to the tips thread. \$\endgroup\$rturnbull– rturnbull2016年10月28日 09:49:47 +00:00Commented Oct 28, 2016 at 9:49
Husk, 4 bytes
Recursive method (4 bytes) (Credit to @ovs)
ωoΣd
# implicit parameter 0 (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 0 (refers to the last parameter)
← # previous number (n - 1)
%9← # modulus by 9
→%9← # next number (n + 1)
-
-
\$\begingroup\$ cool ill change it soon \$\endgroup\$scpchicken– scpchicken2021年10月31日 17:32:38 +00:00Commented Oct 31, 2021 at 17:32
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, 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
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;}
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
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.
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
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.
Ruby, 12 bytes
->n{~-n%9+1}
-
\$\begingroup\$
19? Shouldn't that be9? \$\endgroup\$Ton Hospel– Ton Hospel2016年10月27日 14:33:40 +00:00Commented Oct 27, 2016 at 14:33 -
\$\begingroup\$ @TonHospel Yes, stupid error :P \$\endgroup\$TuxCrafting– TuxCrafting2016年10月27日 14:36:21 +00:00Commented Oct 27, 2016 at 14:36
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
-
4\$\begingroup\$ You can change
s.split``to[...s]\$\endgroup\$Bassdrop Cumberwubwubwub– Bassdrop Cumberwubwubwub2016年10月27日 14:59:36 +00:00Commented Oct 27, 2016 at 14:59
CJam, (削除) 19 (削除ここまで) 13 bytes
r{:~:+_s9円>}g
Explanation:
r{:~:+_s9円>}g Code
r Get token
{:~:+_s9円>} Block: :~:+_s9円>
~ 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
-
\$\begingroup\$ Single-command map and reduce can both be written with prefix
:, so you can do:~:+. It also doesn't hurt to run the block at least once so you can use agloop instead of awloop. \$\endgroup\$Martin Ender– Martin Ender2016年10月27日 14:48:35 +00:00Commented Oct 27, 2016 at 14:48 -
\$\begingroup\$ @MartinEnder
r{_,1>}{:~:+`}wworks, but I don't know how on earth am I supposed to useghere. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2016年10月27日 15:01:03 +00:00Commented Oct 27, 2016 at 15:01 -
\$\begingroup\$ E.g. like this:
r{:~:+_s9円>}g(of course the closed form solutionri(9%)is much shorter. \$\endgroup\$Martin Ender– Martin Ender2016年10月27日 15:04:11 +00:00Commented Oct 27, 2016 at 15:04 -
\$\begingroup\$ @MartinEnder Oh gawd, for real now, I'm such a beginner... \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2016年10月27日 15:08:05 +00:00Commented Oct 27, 2016 at 15:08
-
\$\begingroup\$ The second one doesn't work on multiples of 9 \$\endgroup\$ThePlasmaRailgun– ThePlasmaRailgun2018年10月05日 15:48:01 +00:00Commented Oct 5, 2018 at 15:48
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
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!
-
\$\begingroup\$ Your 4-byte version fails test case 45. \$\endgroup\$Dennis– Dennis2016年11月02日 05:03:00 +00:00Commented Nov 2, 2016 at 5:03
-
\$\begingroup\$ Won't this give 0 for multiples of 9? \$\endgroup\$xnor– xnor2016年11月02日 05:04:04 +00:00Commented Nov 2, 2016 at 5:04
-
\$\begingroup\$ Yeah, I just noticed it. Will do some fixing there. Apparently,
jQ9doesn't act like Jelly'sḃ9:-P \$\endgroup\$Yotam Salmon– Yotam Salmon2016年11月02日 05:19:43 +00:00Commented Nov 2, 2016 at 5:19 -
\$\begingroup\$ Does this give the correct answer when input is
0? \$\endgroup\$Toby Speight– Toby Speight2025年09月08日 15:39:03 +00:00Commented Sep 8 at 15:39 -
\$\begingroup\$ The original solution does. And darn, I was 15, where did you come from now :P \$\endgroup\$Yotam Salmon– Yotam Salmon2025年09月09日 17:01:00 +00:00Commented Sep 9 at 17:01
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.
-
\$\begingroup\$ Suggest
LOCAL-STORAGEinstead ofWORKING-STORAGE\$\endgroup\$ceilingcat– ceilingcat2024年05月27日 20:40:35 +00:00Commented May 27, 2024 at 20:40
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)
><> (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.
-
1\$\begingroup\$ You can save 20 bytes by performing the operations on the input and erroring out:
:a(?n:a%$a,:1%-+\$\endgroup\$Emigna– Emigna2022年12月06日 12:30:16 +00:00Commented Dec 6, 2022 at 12:30
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
-
\$\begingroup\$ You can change
while len(i)>1towhile~-len(i)to save one byte. \$\endgroup\$Oliver Ni– Oliver Ni2016年10月27日 14:11:13 +00:00Commented Oct 27, 2016 at 14:11 -
\$\begingroup\$ I think you can omit the ticks around
input()and force the input the be enclosed in quotes to save 2 bytes. \$\endgroup\$Karl Napf– Karl Napf2016年10月27日 14:12:08 +00:00Commented Oct 27, 2016 at 14:12 -
\$\begingroup\$ @KarlNapf I don't think you can do this when the input is an integer. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2016年10月27日 14:15:28 +00:00Commented Oct 27, 2016 at 14:15
-
\$\begingroup\$ @EriktheGolfer, the op said that the input can be taken as a string \$\endgroup\$Daniel– Daniel2016年10月27日 14:16:12 +00:00Commented Oct 27, 2016 at 14:16
number. In particular. must input0be supported? \$\endgroup\$STALEMATE. It might be better to close the other one as a dupe of this. \$\endgroup\$