sakmario
sakmario

Reputation: 43

Algorithm to sum up all digits of a number

Can you please explain to me how this loop works? What is going on after first loop and after second etc.

def sum(n):
  s = 0
  while n:
    s += n % 10
    n /= 10
  return s

>>> print sum(123)
6

Upvotes: 1

Views: 1189

Answers (3)

Amisha Sahu
Amisha Sahu

Reputation: 89

  int main()
  {
     int t;
     cin>>t;
     cout<<floor(log10(t)+1);
     return 0;
  }

Output

254
3

Upvotes: 0

oybek
oybek

Reputation: 650

def sum(n):
  s = 0
  while n:
    s += n % 10
    n /= 10
  return s

Better rewrite this way (easier to understand):

def sum(n):
  s = 0 // start with s = 0 
  while n > 0: // while our number is bigger than 0
    s += n % 10 // add the last digit to s, for example 54%10 = 4
    n /= 10 // integer division = just removing last digit, for example 54/10 = 5
  return s // return the result

n > 0 in Python can be simply written as n but I think it is bad practice for beginners

Upvotes: 1

mss
mss

Reputation: 1503

so basically, what we are doing in this algorithm is that we are taking one digit at a time from least significant digit of the number and adding that in our s (which is sum variable), and once we have added the least significant digit, we are then removing it and doing the above thing again and again till the numbers remains to be zero, so how do we know the least significant digit, well just take the remainder of the n by dividing it with 10, now how do we remove the last digit(least significant digit) , we just divide it with 10, so here you go, let me know if it is not understandable.

Upvotes: 1

Related Questions