18
\$\begingroup\$

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 , so the code with the smallest number of bytes wins.

\$\endgroup\$
  • 1
    \$\begingroup\$ Maybe a subtask of this challenge. \$\endgroup\$ – nimi Oct 27 '16 at 14:17
  • 3
    \$\begingroup\$ Very closely related to this challenge ... maybe close enough for a dupe. \$\endgroup\$ – AdmBorkBork Oct 27 '16 at 14:22
  • 8
    \$\begingroup\$ Please be more precise when saying number. In particular. must input 0 be supported? \$\endgroup\$ – Ton Hospel Oct 27 '16 at 14:28
  • 2
    \$\begingroup\$ @TimmyD I think that this one is the much cleaner challenge without adding letter to integer conversion, computing the function for two values and including the literal STALEMATE. It might be better to close the other one as a dupe of this. \$\endgroup\$ – Martin Ender Oct 27 '16 at 14:42
  • 3
    \$\begingroup\$ @MartinEnder I retracted my close vote, I think it's unfair to close a good challenge as a dupe of another more complex challenge. \$\endgroup\$ – Erik the Outgolfer Oct 27 '16 at 14:48

45 Answers 45

26
\$\begingroup\$

Pyke, 1 byte

s

Try it here!

Takes the digital root of the input

\$\endgroup\$
16
\$\begingroup\$

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)
\$\endgroup\$
13
\$\begingroup\$

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

\$\endgroup\$
6
\$\begingroup\$

MATL, 3 bytes

9X\

Try it online!

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.

\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

Python, 16 20 bytes

+4 bytes to handle edge case of zero.

lambda n:n and~-n%9+1

repl.it

\$\endgroup\$
  • 1
    \$\begingroup\$ Wow. This is so easy it can be ported to any language. You can even ~-input()%9+1 \$\endgroup\$ – Karl Napf Oct 27 '16 at 14:30
  • 1
    \$\begingroup\$ Doesn't work for 0 unfortunately. \$\endgroup\$ – Emigna Oct 27 '16 at 14:37
  • \$\begingroup\$ @KarlNapf Wouldn't that need a print? \$\endgroup\$ – Jonathan Allan Oct 27 '16 at 14:37
  • \$\begingroup\$ @JonathanAllan Ah, possibly. I just tested it in the REPL environment and that did it. \$\endgroup\$ – Karl Napf Oct 27 '16 at 14:41
  • 1
    \$\begingroup\$ @ the anonymous user who attempted an edit - it would have actually broken the code (made an input of 0 result in 9 rather than 0, which is what is catered for by the n and part of the code) furthermore it would have counted as 19 bytes not 13 (since the print and the space must be counted). \$\endgroup\$ – Jonathan Allan Oct 5 '18 at 18:21
4
\$\begingroup\$

PHP, 15 Bytes

<?=--$argn%9+1;

Previous version PHP, 55 Bytes

$n=$argn;while($n>9)$n=array_sum(Str_split($n));echo$n;
\$\endgroup\$
  • \$\begingroup\$ Exactly how I did it! \$\endgroup\$ – CT14.IT Oct 27 '16 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 Oct 27 '16 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 Oct 27 '16 at 14:35
  • 2
    \$\begingroup\$ You can add the trick of other answers <?=--$argv[1]%9+1?> \$\endgroup\$ – Crypto Oct 28 '16 at 6:37
3
\$\begingroup\$

Haskell, 35 34 bytes

until(<10)$sum.map(read.pure).show

Try it on Ideone.

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
\$\endgroup\$
3
\$\begingroup\$

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).

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

R, 72 67 29 bytes

Edit: Thanks to @rturnbull for shaving off two bytes.

n=scan();`if`(n%%9|!n,n%%9,9)
\$\endgroup\$
  • \$\begingroup\$ I recently learned that ifelse can be replaced by `if`, with identical behavior, which saves you a couple of bytes. \$\endgroup\$ – rturnbull Oct 28 '16 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 Oct 28 '16 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 Oct 28 '16 at 9:49
3
\$\begingroup\$

Retina, 7 bytes

{`.
*
.

Try it online!

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.

\$\endgroup\$
2
\$\begingroup\$

Brachylog, 9 bytes

#0|@e+:0&

Try it online!

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

:I:{@e+}i#0

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.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

CJam, 19 13 bytes

r{:~:+_s\9>}g

Interpreter

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
\$\endgroup\$
  • \$\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 a g loop instead of a w loop. \$\endgroup\$ – Martin Ender Oct 27 '16 at 14:48
  • \$\begingroup\$ @MartinEnder r{_,1>}{:~:+`}w works, but I don't know how on earth am I supposed to use g here. \$\endgroup\$ – Erik the Outgolfer Oct 27 '16 at 15:01
  • \$\begingroup\$ E.g. like this: r{:~:+_s\9>}g (of course the closed form solution ri(9%) is much shorter. \$\endgroup\$ – Martin Ender Oct 27 '16 at 15:04
  • \$\begingroup\$ @MartinEnder Oh gawd, for real now, I'm such a beginner... \$\endgroup\$ – Erik the Outgolfer Oct 27 '16 at 15:08
  • \$\begingroup\$ The second one doesn't work on multiples of 9 \$\endgroup\$ – ThePlasmaRailgun Oct 5 '18 at 15:48
2
\$\begingroup\$

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;}
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ You can change while len(i)>1 to while~-len(i) to save one byte. \$\endgroup\$ – Oliver Ni Oct 27 '16 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 Oct 27 '16 at 14:12
  • \$\begingroup\$ @KarlNapf I don't think you can do this when the input is an integer. \$\endgroup\$ – Erik the Outgolfer Oct 27 '16 at 14:15
  • \$\begingroup\$ @EriktheGolfer, the op said that the input can be taken as a string \$\endgroup\$ – Daniel Oct 27 '16 at 14:16
1
\$\begingroup\$

Python, 45 bytes

f=lambda x:x[1:]and f(`sum(map(int,x))`)or x

Takes the argument as a string.

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 6 bytes

[SODg#

Try it online!

Explanation

[        # infinite loop
 S       # split into digits
  O      # sum digits
   Dg#   # if length == 1: break
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
}
\$\endgroup\$
1
\$\begingroup\$

Factor, 24

Smart, mathy answer.

[ neg bitnot 9 mod 1 + ]

63 for dumb iterative solution:

[ [ dup 9 > ] [ number>string >array [ 48 - ] map sum ] while ]
\$\endgroup\$
1
\$\begingroup\$

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 stack
  • 9 push 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
\$\endgroup\$
1
\$\begingroup\$

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 it here

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!

\$\endgroup\$
  • \$\begingroup\$ Your 4-byte version fails test case 45. \$\endgroup\$ – Dennis Nov 2 '16 at 5:03
  • \$\begingroup\$ Won't this give 0 for multiples of 9? \$\endgroup\$ – xnor Nov 2 '16 at 5:04
  • \$\begingroup\$ Yeah, I just noticed it. Will do some fixing there. Apparently, jQ9 doesn't act like Jelly's ḃ9 :-P \$\endgroup\$ – Yotam Salmon Nov 2 '16 at 5:19
1
\$\begingroup\$

APL (Dyalog), 15 9 bytes bytes

××1+9|-∘1

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Hexagony, 19 15 bytes

.?<9{(/>!@!/)%' 

More Readable:

  . ? < 
 9 { ( /
> ! @ ! / 
 ) % ' .
  . . . 

Try it online!

-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.

\$\endgroup\$
1
\$\begingroup\$

K (oK), 9 bytes

Solution:

(+/.:'$)/

Try it online!

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
\$\endgroup\$
  • 1
    \$\begingroup\$ In my implementation of k I made x\y encode y in base x with as many digits as necessary, so it's slightly shorter: (+/10\)/ \$\endgroup\$ – ngn Jun 21 '18 at 0:22
  • \$\begingroup\$ Nice. In the newer versions of kdb+ (I think from 3.4 and up) you can do 10\:.. but not in oK - and .:'$ is the same number of bytes - so I went with that :) \$\endgroup\$ – streetster Jun 21 '18 at 5:42
  • \$\begingroup\$ oK uses \ and requires a list on the left: `(,10)` \$\endgroup\$ – ngn Jun 21 '18 at 6:11
  • \$\begingroup\$ Indeed, your implementation adds "as many digits as necessary", which is what you get from \: in kdb+ (3.4+), but for oK I'd need to know how many 10s to put in my list. \$\endgroup\$ – streetster Jun 21 '18 at 8:31
0
\$\begingroup\$

Ruby, 12 bytes

->n{~-n%9+1}
\$\endgroup\$
  • \$\begingroup\$ 19 ? Shouldn't that be 9 ? \$\endgroup\$ – Ton Hospel Oct 27 '16 at 14:33
  • \$\begingroup\$ @TonHospel Yes, stupid error :P \$\endgroup\$ – TuxCrafting Oct 27 '16 at 14:36
0
\$\begingroup\$

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))}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.