Additive Persistence

20

3

The shortest code to pass all possibilities wins.

In mathematics, the persistence of a number measures how many times a certain operation must be applied to its digits until some certain fixed condition is reached. You can determine the additive persistence of a positive integer by adding the digits of the integer and repeating. You would keep adding the digits of the sum until a single digit number is found. The number of repetitions it took to reach that single digit number is the additive persistence of that number.

Example using 84523:

84523
8 + 4 + 5 + 2 + 3 = 22
2 + 2 = 4

It took two repetitions to find the single digit number.
So the additive persistence of 84523 is 2.

You will be given a sequence of positive integers that you have to calculate the additive persistence of. Each line will contain a different integer to process. Input may be in any standard I/O methods.

For each integer, you must output the integer, followed by a single space, followed by its additive persistence. Each integer processed must be on its own line.

Test Cases


Input Output

99999999999 3
10 1
8 0
19999999999999999999999 4
6234 2
74621 2
39 2
2677889 3
0 0

Kevin Brown

Posted 2011-03-25T23:18:31.437

Reputation: 5 756

1Your test cases include some values which are over 2^64, and your spec says that the program only has to handle values up to 2^32. Might be worth clearing that up. – Peter Taylor – 2011-03-25T23:40:22.240

@Peter Taylor, forgot to remove those limits. If a program can handle the input I have provided, it shouldn't have an issue with limits. – Kevin Brown – 2011-03-25T23:49:16.497

5Isn't 999999999999's persistence 2 instead of 3? – Eelvex – 2011-03-26T02:13:19.727

@Evelex, that was an incorrect last minute change I guess. Fixed. – Kevin Brown – 2011-03-26T21:45:41.493

Several answers here aren't doing output on stdout but rather use J's "interactive" output by returning results after taking command line input. (This includes 2 other J answers and, I'm guessing, the K answer.) Is this considered legit? Because I can shed 18-ish characters if so. – Jesse Millikan – 2011-03-27T01:29:55.447

@Jesse Millikan, the problem doesn't state it must output to stdout. – Kevin Brown – 2011-03-27T01:42:18.293

It does state "followed by a single space," and, "on it's own line", which seems to imply at least some kind of string output. Also, interactive J doesn't format them as stated if there are inputs of different lengths. – Jesse Millikan – 2011-03-27T01:47:05.610

"Also, interactive J doesn't format them as stated if there are inputs of different lengths." What do you mean by that? – Kevin Brown – 2011-03-27T02:01:21.253

I meant outputs of different lenghts, though it's irrelevant... I was hallucinating or something. Both of the J answers are doing the output as given. – Jesse Millikan – 2011-03-27T02:21:51.523

@Jesse Millikan, The K answer outputs a formatted string to stdout and not to the interactive prompt. – isawdrones – 2011-03-27T06:31:43.150

Answers

6

K - 29 Chars

Input is a filename passed as an argument, 29 chars not including filename.

`0:{5:x,-1+#(+/10_vs)\x}'.:'0:"file"
  • 35 -> 31: Remove outside function.
  • 31 -> 29: Remove parens.

isawdrones

Posted 2011-03-25T23:18:31.437

Reputation: 236

1-1+# => #1_ – streetster – 2019-08-06T11:24:33.053

4

Husk, 10 15 bytes

+5 bytes for horrible I/O requirement

m(wΓ·,LU¡oΣdr)¶

Try it online!

Explanation

To support multiple inputs, we need to use m(₁r)¶ (where is the function doing the interesting computation):

m(₁r)¶  -- expects newline-separated inputs: "x₁␤x₂␤…␤xₙ"
     ¶  -- split on newlines: ["x₁","x₂",…,"xₙ"]
m(  )   -- map over each string
 ( r)   -- | read integer: [x₁,x₂,…,xₙ]
 (₁ )   -- | apply the function described below

The function does the following:

wΓ·,LU¡(Σd)  -- input is an integer, eg: 1234
      ¡(  )  -- iterate the following forever and collect results in list:
       ( d)  -- | digits: [1,2,3,4]
       (Σ )  -- | sum: 10
             -- : [1234,10,1,1,1,…
     U       -- keep longest prefix until repetition: [1234,10,1]
 Γ           -- pattern match (x = first element (1234), xs = tail ([10,1])) with:
  · L        -- | length of xs: 2
   ,         -- | construct tuple: (1234,2)
w            -- join with space: "1234 2"

ბიმო

Posted 2011-03-25T23:18:31.437

Reputation: 15 345

4

Python 84 Chars

while 1:
 m=n=int(raw_input());c=0
 while n>9:c+=1;n=sum(map(int,str(n)))
 print m,c

fR0DDY

Posted 2011-03-25T23:18:31.437

Reputation: 4 337

Challenge case:06234 .. result successful challenge :-) – Quixotic – 2011-03-26T06:01:10.433

@Debanjan Thanks. Corrected. – fR0DDY – 2011-03-26T10:08:17.097

4

Python (93 bytes)

f=lambda n,c:n>9and f(sum(map(int,str(n))),c+1)or c
while 1:n=int(raw_input());print n,f(n,0)

Quixotic

Posted 2011-03-25T23:18:31.437

Reputation: 2 199

i think you can remove the space between 9 and err...and – st0le – 2011-03-26T08:52:01.437

@st0le:Thanks :-) – Quixotic – 2011-03-28T06:17:10.017

and input() instead of int(raw_input()).... – st0le – 2011-03-28T06:48:42.860

@st0le:Try this input with that modification:06234. – Quixotic – 2011-03-28T07:12:25.827

4

Haskell, 100 characters

p[d]=0
p d=1+(p.show.sum$map((-48+).fromEnum)d)
f n=n++' ':shows(p n)"\n"
main=interact$(f=<<).lines

MtnViewMark

Posted 2011-03-25T23:18:31.437

Reputation: 4 779

You can save 6 bytes by using read.pure instead of (-48+).fromEnum, try it online!

– ბიმო – 2018-04-25T15:17:17.610

3

bash, 105 chars

while read x
do
for((i=0,z=x;x>9;i++))do
for((y=0;x>0;y+=x%10,x/=10))do :
done
x=$y
done
echo $z $i
done

Hardly any golfing actually involved, but I can't see how to improve it.

Peter Taylor

Posted 2011-03-25T23:18:31.437

Reputation: 41 901

3

Haskell - 114

s t n|n>9=s(t+1)$sum$map(read.(:[]))$show n|1>0=show t
f n=show n++" "++s 0n++"\n"
main=interact$(f.read=<<).lines

Joey Adams

Posted 2011-03-25T23:18:31.437

Reputation: 9 929

You can save 4 bytes by using pure over (:[]) and defining an operator instead of s, try it online!

– ბიმო – 2018-04-25T15:22:05.653

3

Ruby, 85 Chars

puts $<.map{|n|v=n.chop!;c=0;[c+=1,n="#{n.sum-n.size*48}"] while n[1];[v,c]*' '}*"\n"

I had to borrow the "sum-size*48" idea from Alex, because it's just too neat to miss (in Ruby at least).

Ezran

Posted 2011-03-25T23:18:31.437

Reputation: 161

3

Golfscript, 40 chars

n%{.:${;${48-}%{+}*`:$,}%.,1>\1?+' '\n}%

YOU

Posted 2011-03-25T23:18:31.437

Reputation: 4 321

3

J - 45 Chars

Reads from stdin

(,' ',[:":@<:@#+/&.:("."0)^:a:)&><;._2(1!:1)3

isawdrones

Posted 2011-03-25T23:18:31.437

Reputation: 236

I was trying to use ^:a: myself but I couldn't find some proper documentation... any hints? – Eelvex – 2011-03-26T16:12:02.163

1

The dictionary entry for u^:n has info on its usage but it is a bit dense. ^:a: is like any other call to power but it collects the results and ends when the argument to consecutive calls is the same(converges).

– isawdrones – 2011-03-26T17:21:56.120

1

@Eelvex FWIW I discovered a: through the ^:a: trick in the J Reference Card[PDF]

– J B – 2011-03-27T00:55:26.837

@JB: That's the only reference on ^:a: that I knew :D – Eelvex – 2011-03-27T00:59:18.690

@Eelvex Oh. I had the opposite experience then. I discovered the functionality in the dictionary, and used it as some variant of ^:(<'') at first (probably for Kaprekar), until I spotted it in the card, and learned about a: for the occasion. – J B – 2011-03-27T10:43:50.280

3

c -- 519

(or 137 if you credit me for the framework...)

Rather than solving just this one operation, I decided to produce a framework for solving all persistence problems.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char*(*O)(char*);
char*b(char*s){long long int v=0,i,l=0;char*t=0;l=strlen(s);t=malloc(l+2);
for(i=0;i<l;i++)v+=s[i]-'0';snprintf(t,l+2,"%lld",v);return t;}
int a(char**s,O o){int r;char*n;n=o(*s);r=!strcmp(*s,n);free(*s);
*s=n;return r;}
int main(int c, char**v){size_t l, m=0;char *d,*n=0;O o=b;FILE*f=stdin;
while(((l=getline(&n,&m,f))>1)&&!feof(f)){int i=0;n=strsep(&n,"\n");
d=strdup(n);while(!a(&n,o))i++;printf("%s %d\n",d,i);free(d);free(n);n=0;m=0;}}

Only the two lines starting from char*b are unique to this problem.

It treats the input as strings, meaning that leading "0"s are not strip before the output stage.

The above has had comments, error checking and reporting, and file reading (input must come from the standard input) striped out of:

/* persistence.c
 *
 * A general framework for finding the "persistence" of input strings
 * on opperations.
 *
 * Persistence is defined as the number of times we must apply
 *
 *    value_n+1 <-- Opperation(value_n)
 *
 * before we first reach a fixed point.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../getline.h"

/* A function pointer type for operations */
typedef char*(op_func)(char*);
typedef op_func* op_ptr;
/* Op functions must
 * + Accept the signature above
 * + return a point to a newly allocated buffer containing the updated str
 */

char* addop(char*s){
  int i,l=0;
  long long int v=0;
  char *t=NULL;
  /* protect against bad input */
  if (NULL==s) return s;
  /* allocate the new buffer */
  l = strlen(s);
  t = malloc(l+2);
  if (NULL==t) return t;
  /* walk the characters of the original adding as we go */
  for (i=0; i<l; i++) v += s[i]-'0';
  //fprintf(stderr,"   '%s' (%d) yields %lld\n",s,l,v);
  snprintf(t,l+2,"%lld",v);
  //fprintf(stderr,"   %lld is converted to '%s'\n",v,t);
  return t;
}

/* Apply op(str), return true if the argument is a fixed point fo
 * falsse otherwise,
 */ 
int apply(char**str, op_ptr op){ 
  int r;
  char*nstr;
  /* protect against bad input */
  if ( NULL==op ) exit(1); 
  if ( NULL==*str ) exit(4); 
  /* apply */
  nstr = op(*str); 
  /* test for bad output */
  if ( NULL==nstr ) exit(2); 
  r = !strcmp(*str,nstr); 
  /* free previous buffer, and reasign the new one */
  free(*str); 
  *str = nstr; 
  return r; 
}

int main(int argc, char**argv){
  size_t len, llen=0;
  char *c,*line=NULL;
  op_ptr op=addop;
  FILE *f=stdin;
  if (argc > 1) f = fopen(argv[1],"r");
  while( ((len=getline(&line,&llen,f))>1) && line!=NULL && !feof(f) ){
    int i=0;
    line=strsep(&line,"\n"); // Strip the ending newline
    /* keep a copy for later */
    c = strdup(line);
    /* count necessary applications */
    while(!apply(&line,op)) i++;
    printf("%s %d\n",c,i);
    /* memory management */
    free(c);
    free(line);
    line=NULL;
    llen=0;
  }
}

A little more could be saved if we were willing to leak memory like a sieve. Likewise by #defineing return and the like, but at this point I don't care to make it any uglier.

dmckee --- ex-moderator kitten

Posted 2011-03-25T23:18:31.437

Reputation: 2 726

273 bytes – ceilingcat – 2019-08-16T17:30:02.863

2

J, 74 chars

i=:<;._2(1!:1)3
i&((],' ',":@(0 i.~9<[:".([:":[:+/"."0)^:(i.9)))@>@{~)i.#i

Edits

  • (86 → 83) Some Caps [: to Ats @
  • (83 → 79) Unneeded parentheses
  • (79 → 75) Changing 0". to ". simplifies things
  • (75 → 74) Better Cutting

E.g

i=:<;._2(1!:1)3
74621
39
2677889
0
i&((],' ',":@(0 i.~9<[:".([:":[:+/"."0)^:(i.9)))@>@{~)i.#i
74621 2  
39 2     
2677889 3
0 0  

Eelvex

Posted 2011-03-25T23:18:31.437

Reputation: 5 204

Output is formatted wrong for multiple inputs. See "single space" – Jesse Millikan – 2011-03-27T01:54:12.660

@Jesse: I see nothing wrong. Could you write an example please? – Eelvex – 2011-03-27T02:09:18.897

I have no idea, I'm seeing things I guess. – Jesse Millikan – 2011-03-27T02:18:22.633

1

JavaScript, 57 47 bytes

-10 bytes thanks to @l4m2!

f=(s,c=0)=>s>9?f(eval([...s+""].join`+`),++c):c

Try it online!

Oliver

Posted 2011-03-25T23:18:31.437

Reputation: 7 160

f=(s,c=0)=>s>9?f([...s+""].reduce((x,y)=>x*1+y*1),++c):c – l4m2 – 2018-05-05T11:10:42.193

f=(s,c=0)=>s>9?f([...s+""].reduce((x,y)=>x- -y),++c):c – l4m2 – 2018-05-05T11:11:20.203

1f=(s,c=0)=>s>9?f(eval([...s+""].join`+`)),++c):c – l4m2 – 2018-05-05T11:11:49.927

@l4m2 Thanks! s>9 and eval were great ideas. I think you had an extra paren in there, making it a total of 10 bytes you saved me :-) – Oliver – 2018-05-07T00:35:29.573

Note the strict I/O ;) – Shaggy – 2018-05-14T14:28:51.353

1

I think this is about the best I can come up with.

Ruby 101 Chars

f=->(n){n.sum-n.size*48}
$<.each{|l|i=0;i+=1 while(i+=1;n=f[(n||l.chop!).to_s])>10
puts "#{l} #{i}"}

Alex Bartlow

Posted 2011-03-25T23:18:31.437

Reputation: 11

Actually, chop! instead of chomp! gives me a one character savings. 97 chars. – Alex Bartlow – 2011-03-26T02:20:11.960

Just did some more golfing at it - 91 chars. – Alex Bartlow – 2011-03-26T02:26:48.183

1

PARI/GP 101 Chars

s(n)=r=0;while(n>0,r+=n%10;n\=10);r
f(n)=c=0;while(n>9,c++;n=s(n));c
while(n=input(),print(n," ",f(n)))

Unfortunately, there's no input function for GP, so i guess this lacks the IO part. :( Fixed: Thanks Eelvex! :)

st0le

Posted 2011-03-25T23:18:31.437

Reputation: 2 002

Sure there is: input() :) – Eelvex – 2011-03-26T05:23:47.173

@Eelvex, done. :) – st0le – 2011-03-26T05:53:46.150

1

Javascript - 95

i=prompt();while(i>9){i=''+i;t=0;for(j=0;j<i.length;j++)t+=parseInt(i.charAt(j));i=t;}alert(t);

EDIT: Whoops does'nt do the multi-lines

t123

Posted 2011-03-25T23:18:31.437

Reputation: 111

1Just noticed this doesn't output it correctly. – Kevin Brown – 2011-03-30T19:04:46.053

1

J, 78

f=:[:+/"."0&":
r=:>:@$:@f`0:@.(=f)
(4(1!:2)~LF,~[:":@([,r)".@,&'x');._2(1!:1)3

Recursive solution. Reads from stdin. Writes to stdout, so cut me some slack - it does take an extra 18-ish characters.

Jesse Millikan

Posted 2011-03-25T23:18:31.437

Reputation: 1 438

1

Perl - 77 characters

sub'_{split//,shift;@_<2?0:1+_(eval join'+',@_)}chop,print$_,$",(_$_),$/for<>

jho

Posted 2011-03-25T23:18:31.437

Reputation: 241

1

05AB1E, 13 bytes

ε.µΔSO¼}¾}<ø»

Input as a list of integers.

Try it online.

Explanation:

ε     # Map each integer in the (implicit) input to:
 .µ   #  Reset the counter variable to 0
 Δ    #  Loop until the integer no longer changes:
  S   #   Convert it to a list of digits
   O  #   And take the sum of those
  ¼   #   Increase the counter variable by 1
 }¾   #  After the inner loop: Push the counter variable
}<    # After the map: decrease each value by 1
  ø   # Zip/transpose it with the (implicit) input to create a paired list
   »  # Join each pair by a space, and then each string by newlines
      # (after which the result is output implicitly)

Kevin Cruijssen

Posted 2011-03-25T23:18:31.437

Reputation: 67 575

1

MathGolf, 11 bytes

hÅ_Σ]▀£(k ?

Try it online!

Incredibly inefficient, but we don't care about that. Basically, using the fact that the additive persistence of a number is smaller than or equal to the number itself.

Uses the fact that the additive persistence is less than or equal to the number of digits of the number. Passes all test cases with ease now.

The input format, while suboptimal for some languages, is actually the standard method of taking multiple test cases as input in MathGolf. Each line of the input is processed as its own program execution, and output is separated by a single newline for each execution.

Explanation (using n = 6234)

h             push length of number without popping (6234, 4)
 Å            loop 4 times using next 2 operators
  _           duplicate TOS
   Σ          get the digit sum
    ]         wrap stack in array
              this gives the array [6234, 15, 6, 6, 6]
     ▀        unique elements of string/list ([6234, 15, 6])
      £       length of array/string with pop (3)
       (      decrement (2)
        k ?   push input, space, and rotate top 3 elements to produce output (6234 2)

maxb

Posted 2011-03-25T23:18:31.437

Reputation: 5 754

1

K (ngn/k), 16 bytes

Solution:

{x,#1_(+/10\)\x} 

Try it online!

Explanation:

{x,#1_(+/10\)\x} / the solution
{              } / lambda taking implicit x
      (     )\x  / iterate until convergence
         10\     / split into base-10 (123 => 1 2 3)
       +/        / sum
    1_           / drop first result (iterate returns input as first result)
   #             / count length of result
 x,              / prepend x (original input)

streetster

Posted 2011-03-25T23:18:31.437

Reputation: 3 635

1

Stax, 8 11 bytes

ªwæMε∞ö?îm⌐

Run and debug it

+3 bytes thanks to @Khuldraeseth (the first answer didn't have compliant output)

recursive

Posted 2011-03-25T23:18:31.437

Reputation: 8 616

1

I reached the same solution, but with i in place of u. Adhering to the draconian IO specifications, this becomes 11 bytes.

– Khuldraeseth na'Barya – 2019-08-06T14:58:07.947

Oops. I guess I didn't read the IO requirements very well. I'll update my answer. – recursive – 2019-08-06T15:04:33.890

0

Tcl, 95 bytes

proc P {v n\ 0} {set V $v
while \$v>9 {set v [expr [join [split $v ""] +]]
incr n}
puts $V\ $n}

Try it online!

sergiol

Posted 2011-03-25T23:18:31.437

Reputation: 3 055

3Because the next newest answer is a full 6 years old, which i think is before TIO existed – fəˈnɛtɪk – 2018-04-15T00:35:28.133

0

C (gcc), 87 85 bytes

  • Saved two bytes thanks to ceilingcat; pulling the t=s assignment forward and using (t=s)[1] ~ *((t=s)+1) ~ *(1+(t=s)) ~ 1[t=s].
f(n,p){char*t,s[99];for(p=0;sprintf(s,"%d",n),1[t=s];p++)for(n=0;*t;n+=*t++-48);n=p;}

Try it online!

Jonathan Frech

Posted 2011-03-25T23:18:31.437

Reputation: 6 681

@ceilingcat That is quite neat. – Jonathan Frech – 2018-06-25T21:33:30.097

0

Perl 5, 65 bytes

$b=0;$q=s/\n//r;$_=eval s/./+$&/gr while y///c>1&&++$b;say"$q $b"

Try it online!

Xcali

Posted 2011-03-25T23:18:31.437

Reputation: 7 671

0

Java (OpenJDK 8), 79 bytes

a->{int d=0;while(a/10>0){int c=0;d++;while(a>0){c+=a%10;a/=10;}a=c;}return d;}

Try it online!

There's probable potential to golf it further, but I'll look into that in the future, but for now, I'm pretty happy with this little result.

X1M4L

Posted 2011-03-25T23:18:31.437

Reputation: 1 586

170 bytes. – Jonathan Frech – 2018-04-15T18:46:15.300

Building on @JonathanFrech 67 bytes

– ceilingcat – 2019-12-08T18:36:39.987

0

Python 3, 82 bytes

while 1:f=lambda n:n//10and 1+f(sum(map(int,str(n))));i=input();print(i,f(int(i)))

PieCot

Posted 2011-03-25T23:18:31.437

Reputation: 1 039

0

Japt, 28 bytes

Ë+S+(@D=X©A<D©ì x ªD D<AÃa÷
Ë                            // Map over the inputs and return each, followed by
 +S+                         // a space, followed by the number's persistence.
      D=     ©ì x            // To find it, fold the number up
        X©A<D     ªD         // if we can (handles unfoldable cases),
    (@               D<AÃa   // until it can't be folded up any further.
                          ÷ // Then, join everything up with newlines.

Try it online!

Nit

Posted 2011-03-25T23:18:31.437

Reputation: 2 667

0

PHP, 72+1 bytes

+1 for -R flag.

for($i=0,$a=$argn;$a>9;$i++)$a=array_sum(str_split($a));echo"$argn $i
";

Run as pipe with -R.

  • running PHP as pipe will execute the code once for every input line
  • but it does not unset variables inbetween; so $i must be initialized.
    (Also, it would print nothing instead of 0 for single digits without the initialization.)

Titus

Posted 2011-03-25T23:18:31.437

Reputation: 13 814

0

Bash+coreutils, 83 bytes

[ $1 -le 9 ]&&exit $2
let x=$2+1
for z in `fold -w1<<<$1`
do let y+=$z
done
a $y $x

Try it online!

Should be saved to a script called a and placed in the system's PATH, as it calls itself recursively. Takes input from command line, like a 1999. Returns by exit code.

TIO has some limitations on what you can do with a script, so there's some boilerplate code to make this run in the header.

Prints an error to stderr for input larger than bash integers can handle, but since the actual computation is done with strings, it still gives the right result anyway.

Chris

Posted 2011-03-25T23:18:31.437

Reputation: 1 313

0

Japt -R, 21 19 bytes

Ë+S+(DsÊÉ ÆD=ìxÃâ Ê

Try it

Shaggy

Posted 2011-03-25T23:18:31.437

Reputation: 24 623

0

Python 3, 76 bytes

def f(n,i=0,p=0):p=p or n;f(sum(map(int,str(n))),i+1,p)if n>9else print(p,i)

Try it online!


Without I/O restrictions:

Python 3, 54 bytes

f=lambda n,i=0:f(sum(map(int,str(n))),i+1)if n>9else i

Try it online!

Jitse

Posted 2011-03-25T23:18:31.437

Reputation: 3 566

0

Julia, 92 (29) bytes

f(n)=n>9&&(f∘sum∘digits)(n)+1

Edit: With correct printing it's 92:

f(n)=n>9&&(f∘sum∘digits)(n)+1
while(n=parse(Int128,readline()))≢π
println("$n ",f(n)%Int)end

user3263164

Posted 2011-03-25T23:18:31.437

Reputation: 381

0

Swift 5, 106 bytes

func a(_ s:S,_ i:I)->(S,I){if s.count<=1{return(s,i)};return a(S(s.compactMap{I(S($0))}.reduce(0,+)),i+1)}

Try it online!

Tiziano Coroneo

Posted 2011-03-25T23:18:31.437

Reputation: 141

0

Python 2, 62 bytes

f=lambda x,i=0:f(`sum(int(i)for i in x)`,i+1)if len(x)>1else i

Henry T

Posted 2011-03-25T23:18:31.437

Reputation: 381

0

Python 3, 50 bytes

f=lambda n:0if n<10else-~f(eval('+'.join(str(n))))

Recursive function. Takes an integer, returns an integer.

Explanation:

# create a lambda function which takes one argument, and assign it to f
f=lambda n:\
    # if n is 0-9, it's persistence 0
    0if n<10\
        # otherwise, add one to the running total and recursively call f
        # ( ~ will invert the returned number, equivalent to -n-1)
        # (negating that gives you -(-n-1) = n+1)
        else-~f(
            # convert integet to string, join each character with a '+'
            # gives a string like '1+2+3+4+...+n'
            # evaluate the string as an expression, giving a new integer
            # pass that integer back into f
            eval('+'.join(str(n)))
        )

Triggernometry

Posted 2011-03-25T23:18:31.437

Reputation: 765

0

Pyth, 17 bytes

FG.Qs[Gdtl.usjNTG

Try it online!

If I can instead of values on different lines, take a list of numbers (in the format [9999999999, 10, 8, etc.]), then -1 byte by replacing .Q with Q

F                  # For
 G.Q               #   G in the complete input (split by newlines)
    s[             #     join the list as string, create list from the following values:
      Gd           #       G, " " (for output formatting),
        tl         #       decrement length of
          .u    G  #          List of all intermediate results until there's a returning result, with starting value G
            s      #            reduce on + (add all list elements) the list:
             j     #              convert to integer as list:
              N    #                The current value (implicit input to .u)
               T   #                in base 10 (T=10)

ar4093

Posted 2011-03-25T23:18:31.437

Reputation: 531

0

scala 173:

def s(n:BigInt):BigInt=if(n<=9)n else n%10+s(n/10)
def d(n:BigInt):Int=if(n<10)0 else 1+d(s(n))
Iterator.continually(readInt).takeWhile(_>0).foreach(i=>println(i+" "+d(i)))

user unknown

Posted 2011-03-25T23:18:31.437

Reputation: 4 210