Calculate the digital root of a number
Posted
by Gregory Higley
on Stack Overflow
See other posts from Stack Overflow
or by Gregory Higley
Published on 2008-10-15T12:17:05Z
Indexed on
2010/05/19
8:50 UTC
Read the original article
Hit count: 304
A digital root, according to Wikipedia, is "the number obtained by adding all the digits, then adding the digits of that number, and then continuing until a single-digit number is reached."
For instance, the digital root of 99 is 9, because 9 + 9 = 18 and 1 + 8 = 9.
My Haskell solution -- and I'm no expert -- is as follows.
digitalRoot n
| n < 10 = n
| otherwise = digitalRoot . sum . map (\c -> read [c]) . show $ n
As a language junky, I'm interested in seeing solutions in as many languages as possible, both to learn about those languages and possibly to learn new ways of using languages I already know. (And I know at least a bit of quite a few.) I'm particularly interested in the tightest, most elegant solutions in Haskell and REBOL, my two principal "hobby" languages, but any ol' language will do. (I pay the bills with unrelated projects in Objective C and C#.)
Here's my (verbose) REBOL solution:
digital-root: func [n [integer!] /local added expanded] [
either n < 10 [
n
][
expanded: copy []
foreach c to-string n [
append expanded to-integer to-string c
]
added: 0
foreach e expanded [
added: added + e
]
digital-root added
]
]
EDIT:
As some have pointed out either directly or indirectly, there's a quick one-line expression that can calculate this. You can find it in several of the answers below and in the linked Wikipedia page. (I've awarded Varun the answer, as the first to point it out.) Wish I'd known about that before, but we can still bend our brains with this question by avoiding solutions that involve that expression, if you're so inclined. If not, Crackoverflow has no shortage of questions to answer. :)
© Stack Overflow or respective owner