Print the digital root

19

1

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.

Oliver Ni

Posted 2016-10-27T13:56:38.907

Reputation: 9 650

Can we take the input as a string? – Daniel – 2016-10-27T14:02:57.220

@Dopapp Yes.... – Oliver Ni – 2016-10-27T14:05:06.707

This is called a digital root.

– James – 2016-10-27T14:05:10.107

Related. – Oliver Ni – 2016-10-27T14:07:03.320

Related. – Oliver Ni – 2016-10-27T14:07:11.527

1

Maybe a subtask of this challenge.

– nimi – 2016-10-27T14:17:38.540

3Very closely related to this challenge ... maybe close enough for a dupe. – AdmBorkBork – 2016-10-27T14:22:01.520

@nimi That's why I had the feeling I had done something like this before.. – Kevin Cruijssen – 2016-10-27T14:24:49.930

8Please be more precise when saying number. In particular. must input 0 be supported? – Ton Hospel – 2016-10-27T14:28:40.720

2@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. – Martin Ender – 2016-10-27T14:42:37.390

1

@MartinEnder Perhaps. Points out another reason why using the Sandbox is encouraged.

– AdmBorkBork – 2016-10-27T14:47:13.850

3@MartinEnder I retracted my close vote, I think it's unfair to close a good challenge as a dupe of another more complex challenge. – Erik the Outgolfer – 2016-10-27T14:48:47.743

You should add 10 as a test case. My algorithm was working fine for all your test cases, but was wrong for 10! – sergiol – 2018-04-10T14:12:33.103

Answers

26

Pyke, 1 byte

s

Try it here!

Takes the digital root of the input

Blue

Posted 2016-10-27T13:56:38.907

Reputation: 26 661

17

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)

Jonathan Allan

Posted 2016-10-27T13:56:38.907

Reputation: 67 804

13

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

Johan Karlsson

Posted 2016-10-27T13:56:38.907

Reputation: 670

6

Python, 16 20 bytes

+4 bytes to handle edge case of zero.

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

repl.it

Jonathan Allan

Posted 2016-10-27T13:56:38.907

Reputation: 67 804

1Wow. This is so easy it can be ported to any language. You can even ~-input()%9+1 – Karl Napf – 2016-10-27T14:30:26.350

1Doesn't work for 0 unfortunately. – Emigna – 2016-10-27T14:37:56.617

@KarlNapf Wouldn't that need a print? – Jonathan Allan – 2016-10-27T14:37:58.980

@JonathanAllan Ah, possibly. I just tested it in the REPL environment and that did it. – Karl Napf – 2016-10-27T14:41:05.333

@Emigna indeed it does not, it works for the natural numbers. We all know 0 is not a number. My Jelly solution works for 0. Negative numbers "work" with both - Jelly keeping the (one) sign, this dumping it. – Jonathan Allan – 2016-10-27T14:42:06.593

I know the Jelly version works (as it uses the bijective base). I've always counted 0 as a number though. Hopefully the OP can confirm if we need to support it (as I can change back to my shorter code if we can ignore 0) – Emigna – 2016-10-27T14:46:05.613

@JonathanAllan 0 is a number. It is no natural number though. The OP should clarify this. – Karl Napf – 2016-10-27T14:46:29.323

@KarlNapf Who said numbers are going to be natural? 0 <= N <= 10000, and N is just used as a variable meaning number. I would argue that it would be good to use n instead of N, though. – Erik the Outgolfer – 2016-10-29T14:22:43.357

1@ 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). – Jonathan Allan – 2018-10-05T18:21:38.093

6

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.

James

Posted 2016-10-27T13:56:38.907

Reputation: 54 537

6

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.

Martin Ender

Posted 2016-10-27T13:56:38.907

Reputation: 184 808

4

PHP, 15 Bytes

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

Previous version PHP, 55 Bytes

$n=$argn;while($n>9)$n=array_sum(Str_split($n));echo$n;

Jörg Hülsermann

Posted 2016-10-27T13:56:38.907

Reputation: 13 026

Exactly how I did it! – CT14.IT – 2016-10-27T14:19:37.567

@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 – Jörg Hülsermann – 2016-10-27T14:27:17.283

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 – CT14.IT – 2016-10-27T14:35:36.270

2You can add the trick of other answers <?=--$argv[1]%9+1?> – Crypto – 2016-10-28T06:37:17.623

4

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

Martin Ender

Posted 2016-10-27T13:56:38.907

Reputation: 184 808

3

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.

Leo

Posted 2016-10-27T13:56:38.907

Reputation: 8 482

3

R, 72 67 29 bytes

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

n=scan();`if`(n%%9|!n,n%%9,9)

Billywob

Posted 2016-10-27T13:56:38.907

Reputation: 3 363

I recently learned that ifelse can be replaced by \if``, with identical behavior, which saves you a couple of bytes. – rturnbull – 2016-10-28T09:37:46.073

@rturnbull I was always wondering how if worked. Could you give an example or maybe add it to Tips for golfing in ?

– Billywob – 2016-10-28T09:41:54.817

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. – rturnbull – 2016-10-28T09:49:47.037

3

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

Laikoni

Posted 2016-10-27T13:56:38.907

Reputation: 23 676

3

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

Ton Hospel

Posted 2016-10-27T13:56:38.907

Reputation: 14 114

2

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

Arnauld

Posted 2016-10-27T13:56:38.907

Reputation: 111 334

4You can change s.split\`` to [...s] – Bassdrop Cumberwubwubwub – 2016-10-27T14:59:36.830

2

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.

Fatalize

Posted 2016-10-27T13:56:38.907

Reputation: 32 976

2

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;}

Geobits

Posted 2016-10-27T13:56:38.907

Reputation: 19 061

2

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

Erik the Outgolfer

Posted 2016-10-27T13:56:38.907

Reputation: 38 134

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. – Martin Ender – 2016-10-27T14:48:35.333

@MartinEnder r{_,1>}{:~:+\}wworks, but I don't know how on earth am I supposed to useg` here. – Erik the Outgolfer – 2016-10-27T15:01:03.987

E.g. like this: r{:~:+_s\9>}g (of course the closed form solution ri(9%) is much shorter. – Martin Ender – 2016-10-27T15:04:11.120

@MartinEnder Oh gawd, for real now, I'm such a beginner... – Erik the Outgolfer – 2016-10-27T15:08:05.810

The second one doesn't work on multiples of 9 – ThePlasmaRailgun – 2018-10-05T15:48:01.303

1

APL (Dyalog), 15 9 bytes bytes

××1+9|-∘1

Try it online!

Uriel

Posted 2016-10-27T13:56:38.907

Reputation: 11 708

1

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

streetster

Posted 2016-10-27T13:56:38.907

Reputation: 3 635

1

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\)/

– ngn – 2018-06-21T00:22:35.570

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 :) – streetster – 2018-06-21T05:42:12.793

oK uses \ and requires a list on the left: (,10)\ – ngn – 2018-06-21T06:11:42.577

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. – streetster – 2018-06-21T08:31:03.540

1

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.

Adyrem

Posted 2016-10-27T13:56:38.907

Reputation: 521

1

Keg, 6 bytes(SBCS on Keg wiki)

¿;9%1+

Explanation:

¿#      Take implicit input
 ;9%1+# Digital Root Formula
# Implicit output

user85052

Posted 2016-10-27T13:56:38.907

Reputation:

1

05AB1E, 6 bytes

[SODg#

Try it online!

Explanation

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

Emigna

Posted 2016-10-27T13:56:38.907

Reputation: 50 798

1

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

Daniel

Posted 2016-10-27T13:56:38.907

Reputation: 6 425

You can change while len(i)>1 to while~-len(i) to save one byte. – Oliver Ni – 2016-10-27T14:11:13.673

I think you can omit the ticks around input() and force the input the be enclosed in quotes to save 2 bytes. – Karl Napf – 2016-10-27T14:12:08.107

@KarlNapf I don't think you can do this when the input is an integer. – Erik the Outgolfer – 2016-10-27T14:15:28.927

@EriktheGolfer, the op said that the input can be taken as a string – Daniel – 2016-10-27T14:16:12.877

1

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.

Karl Napf

Posted 2016-10-27T13:56:38.907

Reputation: 4 131

1

Python, 45 bytes

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

Takes the argument as a string.

Loovjo

Posted 2016-10-27T13:56:38.907

Reputation: 7 357

1

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.

Martin Ender

Posted 2016-10-27T13:56:38.907

Reputation: 184 808

1

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
}

Brad Gilbert b2gills

Posted 2016-10-27T13:56:38.907

Reputation: 12 713

1

Factor, 24

Smart, mathy answer.

[ neg bitnot 9 mod 1 + ]

63 for dumb iterative solution:

[ [ dup 9 > ] [ number>string >array [ 48 - ] map sum ] while ]

cat

Posted 2016-10-27T13:56:38.907

Reputation: 4 989

1

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!

Yotam Salmon

Posted 2016-10-27T13:56:38.907

Reputation: 201

Your 4-byte version fails test case 45. – Dennis – 2016-11-02T05:03:00.280

Won't this give 0 for multiples of 9? – xnor – 2016-11-02T05:04:04.993

Yeah, I just noticed it. Will do some fixing there. Apparently, jQ9 doesn't act like Jelly's ḃ9 :-P – Yotam Salmon – 2016-11-02T05:19:43.923

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

Robert Hickman

Posted 2016-10-27T13:56:38.907

Reputation: 661

0

Braingolf, 20 bytes [non-competing]

VR1>[<$_dl1-M&+vmR>]

Explanation:

VR1>[<$_dl1-M&+vmR>]  Implicit input to stack
VR                    Create new stack, then return to main stack
  1>                  Push 1 and move to beginning of stack
    [..............]  Loop, will always run once, will repeat if first item is > 0 at ]
     <$_              Silently pop first item from stack
        d             Split last item on stack into digits
         l1-          Push amount of digits minus 1
            M         Move last item (amount of digits) to next stack
             &+       Sum entire stack, pop everything, push total sum
               vmR    Move to next stack, move last item to prev stack, return to main stack
                  >   Move last item on stack to the beginning of stack

Skidsdev

Posted 2016-10-27T13:56:38.907

Reputation: 9 656

0

Tcl, 57 bytes

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

Try it online!

sergiol

Posted 2016-10-27T13:56:38.907

Reputation: 3 055

0

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.

brhfl

Posted 2016-10-27T13:56:38.907

Reputation: 1 291

0

JavaScript, 37 bytes

Input is taken as a string.

f=n=>n>9?f(eval([...n].join`+`)+""):n

Try it online!

Oliver

Posted 2016-10-27T13:56:38.907

Reputation: 7 160

0

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 

reffu

Posted 2016-10-27T13:56:38.907

Reputation: 1 361

0

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

Taylor Scott

Posted 2016-10-27T13:56:38.907

Reputation: 6 709

0

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

Erik the Outgolfer

Posted 2016-10-27T13:56:38.907

Reputation: 38 134

0

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

ngn

Posted 2016-10-27T13:56:38.907

Reputation: 11 449

0

Ohm v2, 5 bytes

ì‹9%›

Explanation:

ì‹9%›
ì     Takes input as integer
 ‹    Decrements
  9%  Modulus 9
    › Increment

Try it online!

ThePlasmaRailgun

Posted 2016-10-27T13:56:38.907

Reputation: 383

0

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

wooshinyobject

Posted 2016-10-27T13:56:38.907

Reputation: 171

0

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

Riley

Posted 2016-10-27T13:56:38.907

Reputation: 11 345

You need to count -p in your bytecount. (in that case, it will count for 3 bytes, but if you replaces the '' with "" then it's only 1 byte). And you can golf it further : the same approach can be written like s/./+$&/g,$_=eval while/../. Or you could do s/(.)(.)/$1+$2/e&&redo which is even shorter. And a shorter code (the approach is totally different) : $_=--$_%9+1. – Dada – 2016-10-27T17:19:07.203

@Dada I was trying to figure out why it wouldn't run on the command line for so long that I must have forgotten to add the extra bytes when I gave up (I don't use perl much). – Riley – 2016-10-27T17:29:04.923

@Dada s/(.)(.)/$1+$2/e&&redo doesn't exactly follow the method given in the question either. – Riley – 2016-10-27T17:29:33.113

perl -lpe 's%%s/\B/+/g;$_=eval%egr' – Ton Hospel – 2016-10-27T22:31:19.933

0

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

Magic Octopus Urn

Posted 2016-10-27T13:56:38.907

Reputation: 19 422

0

Ruby, 12 bytes

->n{~-n%9+1}

TuxCrafting

Posted 2016-10-27T13:56:38.907

Reputation: 4 547

19 ? Shouldn't that be 9 ? – Ton Hospel – 2016-10-27T14:33:40.797

@TonHospel Yes, stupid error :P – TuxCrafting – 2016-10-27T14:36:21.627

0

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

Pete Arden

Posted 2016-10-27T13:56:38.907

Reputation: 1 151

string is already IEnumerable<char> so you don't need to ToCharArray() before calling Sum() on it. o-48 is a shorter than int.Parse(o+""). Having said these, the mod 9 trick will be much shorter than actually summing the digits. – milk – 2016-10-27T21:06:35.700

0

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

PhiNotPi

Posted 2016-10-27T13:56:38.907

Reputation: 26 739

0

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

rnso

Posted 2016-10-27T13:56:38.907

Reputation: 1 635

0

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

miles

Posted 2016-10-27T13:56:38.907

Reputation: 15 654