Page 1 of 1

Sum of digits

Posted: Mon Jun 03, 2019 7:55 am
by cameyo
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

Re: Sum of digits

Posted: Mon Jun 03, 2019 10:35 am
by rickyboy

Re: Sum of digits

Posted: Mon Jun 03, 2019 10:49 am
by cameyo
Yes, rickyboy. A very elegant solution.
Thanks for the italian translation :-)

Re: Sum of digits

Posted: Mon Jun 03, 2019 8:17 pm
by TedWalther

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.

Re: Sum of digits

Posted: Tue Jun 04, 2019 6:19 pm
by cameyo