5
$\begingroup$

I want to iteratively calculate the sum of a number's digits, until the result contains only one digit. For example, when $n=67946$ we get:

$$6+7+9+4+6=32\space\to\space3+2=5\tag1$$

So, when $n=67946$ I must get $5$.

When $n=649134976$

$$6+4+9+1+3+4+9+7+6=49\space\to\space4+9=13\space\to\space1+3=4\tag2$$

So, when $n=649134976$ I must get $4$.

I wrote:

Total[IntegerDigits[n]]

But this only gives the first iteration of the sum of digits.

$\endgroup$
1
  • $\begingroup$ @infinitezero I stand corrected (and deleted the comment). Thanks! I think Mod[n,9,1] does the trick. $\endgroup$
    – Rabbit
    Dec 27, 2021 at 3:19

1 Answer 1

11
$\begingroup$
Clear[s, t, n]

t[n_] := NestWhileList[Total[IntegerDigits[#]] & , n, # > 10 &]

Test:

t[649134976]

{649134976, 49, 13, 4}

If you don't want the interim values, use NestWhile.


A slight variation:

s[n_] := FixedPointList[Total[IntegerDigits[#]] & , n]

Test:

s[649134976]

{649134976, 49, 13, 4, 4}

If you don't want the interim values, use FixedPoint.

$\endgroup$
1
  • $\begingroup$ Nice solution. I think the FixedPoint version is a bit neater $\endgroup$
    – Joe
    Dec 26, 2021 at 19:23

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.