Monday, September 7, 2009

Today, I was speaking with my Internet Programming lecturer, Mr. Gupta. He was sharing his experience on teaching C to the first year mechanical class. He said, he couldn't explain the logic of adding sum of n digits to a student. He employed the usual strategy of leaving out the nines in the number. (The student didn't know that simple logic it seems!)

That's when this idea struck me. If you have a number, say x.
It shall be represented as (9*n)+y.

If we identify y then that's the sum of digits.

Say the number is 103

It's simple 99+4, (9*11)+4 hence 4.

y is nothing but (9+9+9+9....11 times) +4
So we skip all those nines and take the 4 alone.

In simpler words if x is the number then (x modulus 9) is the sum of the digits.
So in a programmer's perspective its just x%9.