Friday, June 7, 2013

Python Code Snippets: To get the sum of digits of a number

Sum of digits of number '123' is 1 + 2 + 3 = 6
What could the sum of digits of factorial of 100 which has 158 digits?
Either, you can calculate 100! and sum up the digits using a calculator, or use this simple python function:

"

import math
def sum_digits(n):
   import math
   total = 0
   for i in range(int(math.log10(n)) + 1):
      total += n % 10
      n //= 10
   return total
#taking the input
n = input()
print sum_digits(n)

"

More snippets to come soon...

No comments:

Post a Comment