12
\$\begingroup\$

This question already has an answer here:

Your Task:

Write a program or function that, when given a number, outputs its persistence. The persistence of a number is the number of times you can add its digits before arriving at a one-digit number. All one digit numbers have a persistence of 0. Note that this is different from questions about finding the digital root, as those questions ask for the end result of this process, whereas this question wants the number of steps required to get there.

Input:

An integer.

Output:

The persistence of the inputted integer.

Examples:

1-->0 (1=1)
12-->1 (1+2=3)
99-->2  (9+9=18, 1+8=9)
9999-->2 (9+9+9+9=36, 3+6=9)

Scoring:

This is , lowest score in bytes wins.

\$\endgroup\$

marked as duplicate by Digital Trauma code-golf Jun 15 '17 at 15:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    \$\begingroup\$ Relevant OEIS entry \$\endgroup\$ – Shaggy Jun 15 '17 at 12:18
  • 1
    \$\begingroup\$ Highest score in bytes wins? \$\endgroup\$ – scatter Jun 15 '17 at 12:19
  • 8
    \$\begingroup\$ Looks like a duplicate of this. \$\endgroup\$ – Emigna Jun 15 '17 at 12:22
  • 4
    \$\begingroup\$ @Okx: The 2 challenges are exactly the same. The only difference is that you could check the persistence of more than 1 number at once in the other challenge. It may be better to close that challenge as a duplicate, but I would argue that they are the same. \$\endgroup\$ – Emigna Jun 15 '17 at 12:29
  • 2
    \$\begingroup\$ No, you can't dup an old question to a new question. That would set an awful precedent \$\endgroup\$ – Digital Trauma Jun 15 '17 at 15:33

20 Answers 20

4
\$\begingroup\$

Jelly, 7 bytes

DS$ÐĿL’

Try it online!

How it works

DS$ÐĿL’
DS$      digital sum
   ÐĿ    apply until results not unique, collect all intermediate results
     L   length of the collection
      ’  minus 1
\$\endgroup\$
6
\$\begingroup\$

Python 2, 50 39 bytes

-10 thanks to @JonathanAllan

f=lambda x:x>9and-~f(sum(map(int,`x`)))

Try it online!

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

Brachylog, 10 bytes

;.{ẹ+}ⁱ⁾Ḋ∧

Try it online!

Explanation

;.{  }ⁱ⁾     Iterate Output times on the Input…
        Ḋ∧   …so that the result is a single digit:
   ẹ+          Sum the elements
\$\endgroup\$
  • 1
    \$\begingroup\$ 10/10 declarative much. \$\endgroup\$ – Leaky Nun Jun 15 '17 at 12:41
5
\$\begingroup\$

Prolog (SWI), 91 90 bytes

s(A,B):-A=0,B=0;divmod(A,10,Q,R),s(Q,T),B is T+R.
p(A,B):-A<10,B=0;s(A,S),p(S,T),B is T+1.

Try it online!

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

C (gcc), 58 bytes

1 byte thanks to Felipe Nardi Batista and Kritixi Lithos who discovered the same golf independently.

a,m;f(n){for(m=n,a=0;m;m/=10)a+=m%10;return n>9?1+f(a):0;}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ n>9?1+f(a):0; for 1 byte \$\endgroup\$ – Felipe Nardi Batista Jun 15 '17 at 13:02
  • \$\begingroup\$ On gcc, a,m;f(n){for(m=n,a=0;m;m/=10)a+=m%10;n=n>9?1+f(a):0;} works. \$\endgroup\$ – Steadybox Jun 15 '17 at 13:13
  • 3
    \$\begingroup\$ @Steadybox No, you can't convince me to write a function without the return statement. \$\endgroup\$ – Leaky Nun Jun 15 '17 at 13:19
  • 2
    \$\begingroup\$ @LeakyNun I guess your persistence fits the spirit of the challenge. \$\endgroup\$ – Steadybox Jun 15 '17 at 13:33
3
\$\begingroup\$

Mathematica, 48 bytes

(n=#;t=0;While[n>9,n=Tr@IntegerDigits@n;t++];t)&

but alephalpha golfed it down to...

Mathematica, 41 bytes

(t=-1;#//.n_:>Tr[t++;IntegerDigits@n];t)&
\$\endgroup\$
  • \$\begingroup\$ (t=-1;#//.n_:>Tr[t++;IntegerDigits@n];t)& \$\endgroup\$ – alephalpha Jun 15 '17 at 13:09
  • \$\begingroup\$ very nice. posted! \$\endgroup\$ – J42161217 Jun 15 '17 at 13:15
2
\$\begingroup\$

05AB1E, 9 bytes

[DgiNq}SO

Explanation:

[          Start infinite loop
 D         Duplicate
  g        Length
   i       If equal to one:
    N        Push iteration number
     q       Terminate program
      }    Else:
       S     Get the characters
        O    Sum

Try it online!

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

Java 8, 67 bytes

n->{int r=0,s;for(;n>9;n=s,r++)for(s=0;n>0;n/=10)s+=n%10;return r;}

Explanation:

Try it here.

n->{            // Method with integer parameter and integer return-type
  int r=0,      //  Result-count
      s;        //  Digit-sum
  for(;n>9      //  Loop as long as `n` contains more than 1 digit
      ;         //    After every iteration:
      n=s,      //     Replace the `n` with the sum of digits 
      r++)      //     and increase the result-count
    for(s=0;    //   Reset the sum to 0
        n>0;    //    Inner loop (2) as long as n is larger than 0
        n/=10)  //     Divide n by 10 every iteration
      s+=n%10;  //    And increase the sum with the trailing digit
                //   End of inner loop (2) (implicit / single-line body)
                //  End of loop (1) (implicit / single-line body)
  return r;     //  Return the result-count
}               // End of method
\$\endgroup\$
2
\$\begingroup\$

Lua 125

function r(n,c,t,m)n=tostring(n)t,c=0,c or 0;for m=1,#n do t=t+n:sub(m,m)end return #n==1 and(print(c)or true)or r(t, c+1)end

you call it simply using r({yourNumber})

\$\endgroup\$
  • \$\begingroup\$ why the 3rd and 4th parameters? \$\endgroup\$ – Felipe Nardi Batista Jun 15 '17 at 14:11
  • \$\begingroup\$ print(c)or true to not print(c) \$\endgroup\$ – Felipe Nardi Batista Jun 15 '17 at 14:17
2
\$\begingroup\$

Perl 5, 32 bytes

31 bytes of code + -p flag.

$_=eval,$\++while 1<s/./+$&/g}{

Try it online!

Short explanations:
s/./+$&/g adds a + before each digit and returns the number of digits. While this number is greater than 1, we set $_ to the value of the evaluation of this string, and increment the number of set ($\++). At the end, $\ is implicitly printed thanks to -p and }{.

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

MATL, 13 bytes

t:"tFYAs]v9>s

Try it online!

Explanation

t        % Implicit input. Duplicate
:"       % Do the following that many times
  t      %   Duplicate
  FYA    %   Convert to base 10: array of decimal digits
  s      %   Sum of array
]        % End
v        % Concatenate stack vertically
9>       % Greater than 9? element-wise
s        % Sum. Implicit display
\$\endgroup\$
2
\$\begingroup\$

Javascript, 47 bytes

f=x=>x>9?f([...x+""].reduce((a,b)=>+a+ +b))+1:0

f=x=>x>9?f([...x+""].reduce((a,b)=>+a+ +b))+1:0

console.log('1 -> ' + f(1));
console.log('12 -> ' + f(12));
console.log('99 -> ' + f(99));
console.log('9999 -> ' + f(9999));

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

Haskell, 46 45 bytes

g n|m<-sum$read.pure<$>show n,m<n=1+g m|1<3=0

Try it online!

read.pure<$>show n converts an integer n to a list of digits, applying sum to this list yields the digital sum m. If m is smaller than n then n was not yet a single digit, so we recursively call g m and add one. Otherwise 0 is returned.

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

PHP, 58 bytes

for(;9<$a=&$argn;$a=array_sum(str_split($a)))$p++;echo+$p;

Try it online!

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

Swift 4, 89 bytes

func p(i:Int)->Int{return"\(i)".count==1 ?i :p(i:"\(i)".map{Int("\($0)")!}.reduce(0,+))}

Swift 4 is still in beta, so you can't run it online. If you have Xcode 9 Beta, it will work.

Un-golfed:

func p(i: Int) -> Int {
    return "\(i)".count==1 ? i : p(i: "\(i)".map{Int("\($0)")!}.reduce(0,+))
}

Here we check to see how many digits are in the number. If it is only one, we return the number. If not, we turn it into a string, change each character back into an int, get the total sum of all the digits, and run that back through the original function.

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

Clojure, 88 bytes

#(loop[v(str %)i 0](if(=(count v)1)i(recur(str(apply +(for[c v](-(int c)48))))(inc i))))

Oddly long...

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

Dyalog APL, 27 bytes

{⍵≤9:0⋄1+∇+/⍵⊤⍨10⍴⍨⌈10⍟1+⍵}
\$\endgroup\$
1
\$\begingroup\$

Lua, 82 80 bytes

x=~~...c=0while x>9 do
c=c+1z=0while x>0 do
z=z+x%10x=x//10
end
x=z
end
print(c)

Try it online!

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

Braingolf, 28 bytes

V0R1>[dl2-?<1+M&+vm1+R>:v_|]

Try it online!

Explanation

V0R1>[dl2-?<1+M&+vm1+R>:v_|]  Implicit input of commandline args
V0R                           Create stack2, push 0, return to stack1
   1>                         Push 1 to bottom of stack1
     [.....................]  While loop, will run while bottom item on stack1 is not 0
      d                       Split top of stack into digits
       l2-?                   If length of stack <= 2..
           <1+                ..Move BoS to stop and increment
              M               ..Move item to stack2
               &+             ..Sum entire stack
                 vm           ..Move item back from stack2
                   1+         ..Increment top item on stack2
                     R>       ..Return to stack1 and move ToS to bottom
                       :      Else
                        v_    ..Switch to stack2 and print last item
                          |   Endif
\$\endgroup\$
1
\$\begingroup\$

Retina, 26 bytes

1`\d.
#$&
\d
$*
}`1+
$.&
#

Try it online! Explanation: The first stage counts the persistence: if there are at least two digits, the persistence (represented here by # signs) is incremented. The second stage converts each digit individually to unary, effectively adding them, while the third stage converts back to decimal, looping until a single digit is obtained. It then remains to count the # signs.

\$\endgroup\$

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