1

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
sakmario
  • 43
  • 4
  • on each iteration we take the remainder from division of n by 10 (`123 % 10 = 3`, `12 % 10 = 2`, `1 % 10 = 1`) - this gives us the last digit of `n` as single number. we add it to the sum and so on – Random Guy Dec 25 '19 at 21:46
  • 1
    If you debug, or add some print statements inside the loop, you should be able to monitor what is happening... Certainly when you call `sum` with a huge number. Did you try? – trincot Dec 25 '19 at 21:54
  • Also n /= 10 is integer devision, so 123 / 10 = 12 and not 12.3 – maraca Dec 25 '19 at 22:20
  • I am not experienced in defining the functions yet. That is what confuses me. I made it the way I can without a function in Ruby and it looks like this: sum = 0 n = 123 while n > 0 s = 0 s += n % 10 n /= 10 sum += s end puts sum – Is the "sum+= s" same as "return s" ? Thank You – sakmario Dec 26 '19 at 01:09
  • Does this answer your question? [Sum of all digits of a number](https://stackoverflow.com/questions/43770124/sum-of-all-digits-of-a-number) – Vishwa Ratna Dec 26 '19 at 08:38
  • (With loops, going through one once is called an *iteration*.) – greybeard Dec 26 '19 at 09:24

3 Answers3

1

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.

mss
  • 1,423
  • 2
  • 9
  • 18
1
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

oybek
  • 630
  • 4
  • 14
0
  int main()
  {
     int t;
     cin>>t;
     cout<<floor(log10(t)+1);
     return 0;
  }

Output

254
3