## Sum of digits

Q&A's, tips, howto's
cameyo
Posts: 101
Joined: Sun Mar 27, 2011 3:07 pm

### Sum of digits

Given a number n, find the sum of its digits until sum becomes single digit.

Code: Select all

``Example: n = 7865 = 7 + 8 + 6 + 5 = 26 ==> 2 + 6 = 8``

Code: Select all

``````(define (digitSum n)
(if (zero? n) 0
(if (zero? (% n 9)) 9
(% n 9))))

(digitSum 236753647864)
;-> 7``````

rickyboy
Posts: 595
Joined: Fri Apr 08, 2005 7:13 pm
Location: Front Royal, Virginia

### Re: Sum of digits

(λx. x x) (λx. x x)

cameyo
Posts: 101
Joined: Sun Mar 27, 2011 3:07 pm

### Re: Sum of digits

Yes, rickyboy. A very elegant solution.
Thanks for the italian translation :-)

TedWalther
Posts: 605
Joined: Mon Feb 05, 2007 1:04 am
Location: Abbotsford, BC
Contact:

### Re: Sum of digits

Code: Select all

``````(define (digital_root n)
(+ 1 (% (- n 1) 9))

> (digital_root 236753647864)
7
``````
I heard this referred to as Raman's forumula, but not sure if that is the proper name for it. Even Wolfram's website didn't give an origin for it that I could find. It works though. I tested it on the numbers from 0 to 100.

Update:

I can't verify this, but further web searching indicates this solution may be a special case of Ramanujan's Congruence.
Cavemen in bearskins invaded the ivory towers of Artificial Intelligence. Nine months later, they left with a baby named newLISP. The women of the ivory towers wept and wailed. "Abomination!" they cried.

cameyo
Posts: 101
Joined: Sun Mar 27, 2011 3:07 pm