Avinash
Avinash

Reputation: 13267

Sum of a square of each digits in a number

Sum of each digits in a number is defined by

1 + ((i - 1) % 9) where i is the number

Is there a formula for getting sum of the squares of its digits.

Upvotes: 0

Views: 5050

Answers (1)

Russell Zahniser
Russell Zahniser

Reputation: 16364

The formula you give is actually for a repeated sum of digits, in the sense of 384 -> 3 + 8 + 4 = 15 -> 1 + 5 = 6. This sum features in the "casting out nines" method of checking arithmetic by reducing a number to its value modulo 9. See for example the book "Mathematics Made Difficult" or this classic Square One skit:

http://www.youtube.com/watch?v=Q53GmMCqmAM

The only reason that modulus provide closed-form equivalent to repeated sum of digits is that 9 is one less than 10 and so 10, 100, 1000, etc. are all equal to 1 modulo 9. For more typical operations on the digits of a number, you actually have to iterate through the digits one by one:

for( ; number > 0; number /= 10) {
   int digit = number % 10;
   // do something with digit
}

Upvotes: 4

Related Questions