g | x | w | all
Bytes Lang Time Link
015AWK250908T143721Zxrs
002Thunno 2 t230622T170456ZThe Thon
036><> Fish221104T153525Zmousetai
004Japt h210806T162654ZShaggy
075Go221103T190746Zbigyihsu
nanFig221103T204141Zsouth
009Charcoal220302T004135Zjixperso
004Vyxal220302T140502ZAlan Bag
00305AB1E220302T081936ZKevin Cr
004Husk211011T142904Zscpchick
013braingolf170530T080856ZMayube
131COBOL GNU211023T162746ZEternal
003APL Dyalog Classic211023T082117Zwasif
003Vyxal211011T222524Zemanresu
011TIBasic211010T231627ZYouserna
006Keg190917T231025Zuser8505
094MBASIC181005T173915Zwooshiny
005Ohm v2181005T155152ZThePlasm
008K ngn/k180621T133554Zngn
009K oK180619T061214Zmkst
066QBasic 1.1180619T125919ZErik the
015Hexagony180619T111942ZAdyrem
069Excel VBA180619T123316ZTaylor R
069Forth gforth180618T214548Zreffu
037JavaScript180618T203604ZOliver
037dc180411T131528Zbrhfl
007Retina180411T041315ZLeo
057Tcl170715T175505Zsergiol
009APL Dyalog170529T012322ZUriel
015PHP161027T140805ZJör
007Pyth161030T175321ZYotam Sa
008J161102T070925Zmiles
008Labyrinth161101T224410ZRobert H
020Python161027T142007ZJonathan
063Java 7161027T141626ZGeobits
003Jelly161027T140306ZJonathan
024Factor161028T120925Zcat
029R161027T140319ZBillywob
015Perl161028T095041ZTon Hosp
079C#161027T163651ZPete Ard
152Racket161028T022752Zrnso
029Perl 6161027T224851ZBrad Gil
032Element161027T224758ZPhiNotPi
012Julia161027T194251ZMartin E
034Haskell161027T172001ZLaikoni
028Perl161027T142537ZRiley
010JavaScript ES6161027T141813ZJohan Ka
013CJam161027T143358ZErik the
038JavaScript ES6161027T140908ZArnauld
015Retina161027T145929ZMartin E
011Mathematica161027T143943ZMartin E
029C161027T142102ZKarl Nap
057Groovy161027T142913ZMagic Oc
012Ruby161027T143202ZTuxCraft
00605AB1E161027T140517ZEmigna
045Python161027T142302Zxenia
003MATL161027T142109ZDJMcMayh
051Python 2161027T140556ZDaniel
009Brachylog161027T141131ZFatalize
001Pyke161027T140357ZBlue

AWK, 15 bytes

1,$0=1+($0-1)%9

Attempt This Online!

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

Attempt This Online!

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

Try it

Æ=ì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)}

Attempt This Online!

Go, Modulus solution, 29 bytes

func(n int)int{return^-n%9+1}

Attempt This Online!

Fig, \$4\log_{256}(96)\approx\$ 3.292 bytes

}%9{

Try it online!

}%9{
   {  # decrement with implicit input
 %9   # mod 9
}     # increment

Charcoal, 9 bytes

⁺﹪⁻N¹¦⁹¦¹

TryItOnline!

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

Vyxal, 4 bytes

‹9%›

Try it Online!

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

Try it online!

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)

Try it online!

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

Try it online!

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⊤⊢

Try it online!

Anonymous tacit prefix fork train.

 ⊤      ⍝ Tail of base conversion of                   
   ⊢    ⍝ right argument to
9       ⍝ base 9

Vyxal, 3 bytes

⁽∑Ẋ

Try it Online!

⁽ Ẋ # Until the result converges...
 ∑  # Sum digits

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

Try it online!

K (ngn/k), 8 bytes

(+/10\)/

Try it online!

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:

(+/.:'$)/

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

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 { ( /
> ! @ ! / 
 ) % ' .
  . . . 

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.

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 ;

Try it online!

Explanation

  1. Place sum (starting at 0) on stack
  2. Get remainder of number divided by 10
  3. Add to sum
  4. Replace number with itself divided by 10
  5. Repeat steps 2-4 until number equals 0
  6. 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

Try it online!

dc, 37 bytes

[[A~rdZ1<D]dsDx[+z1<S]dsSxdZ1<M]dsMxp

Try it online!

[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

{`.
*
.

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.

Tcl, 57 bytes

while \$v>9 {set v [expr [join [split $v ""] +]]}
puts $v

Try it online!

APL (Dyalog), 15 9 bytes bytes

××1+9|-∘1

Try it online!

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

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:

Python, 16 20 bytes

+4 bytes to handle edge case of zero.

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

repl.it

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-*+`

Try it online!

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

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

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

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

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#

Try it online!

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\

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.

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&

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.

Pyke, 1 byte

s

Try it here!

Takes the digital root of the input