[Tutor] Converting integers into digit sum (Python 3.3.0)

Dave Angel davea at davea.name
Mon Dec 9 23:28:37 CET 2013


On Mon, 09 Dec 2013 20:27:38 +0000, Alan Gauld 
<alan.gauld at btinternet.com> wrote:
> Incidentally, I just remembered another completely different
> way to do it, although I can't recall how it works! Maybe one
> of the math gurus can explain it, and how to extend it. This
> version only works for 2 digit numbers... and has a huge gotcha!


> To get the sum for a two digit number X using 17 as example...


> subtract X from 100   	17->83
> Sum the digits of that number 	83->11
> Subract that number from 19 	11->8
> That's the sum of the digits of X

> popped into my brain. It seems to work reliably but I've no

Unfortunately it doesn't work for 10, 20, ...
This is related to a technique called casting out nines (and nine is 
magic because it's one less than the base we work in).

When you cast out nines you get the remainder, modulo 9. But to cast 
out nines you keep adding up the digits till you get a one digit 
result. So:

149 == 14 == 5.

There's more but it's probably more fruitful to read the Wikipedia 
post.

-- 
DaveA



More information about the Tutor mailing list