10 AnswersNew Answer
The easiest way I know is to convert it to a string b=str(a) and to sum them just use sum(int(i) for i in b) So to sum it all in one line: sum( int(i) for i in str(a))
Then there is the old-school way of using modulo: x = 0 while number: x += number%10 number //= 10 I have just made a performance comparison in case you're interested: https://code.sololearn.com/c3zFM5oVLiaQ/?ref=app
I modified HonFu 's code to show the effect of length on time. After about 40, the str method is consistantly quicker. https://code.sololearn.com/cEF931LPWCyf/?ref=app
Yes, first turn it into a string, slice it like a string and turn back to int
Interesting. Why is this difference? Because 'big nums' in Python are internally different to let's say a 'long long'? (I wonder how their superlarge ints work anyway.)
HonFu Louis I suspected that the part running slow was the division and shift in the C method. So i changed it from base 10 (native human) to base 16 (native binary) with following change to Louis code: while n: s += n&15 n = n>>4 and, surprise: both methods are equivalent in speed (run it many times and see the spread of performance of Sololearn server). So it has to do with the difficulty to "just" extract the last digit of a big number and "just" dislocate a comma in base 10, what in base 16 is a very fast calculation.
HonFu it is not the same thing. I'm doing the last digit sum in Hexadecimal and not in decimal. so results will never match, unless you do s += n%16 n = n//16
HonFu kinda, yes. My intention was only try to guess were the code gets much slower using long integers, not compare results one to one. if you wish to compare one to one in hex base you need to transform the decimal in hex before summing the digits, and the sum must also be in hex.
Edward, I am not so competent in bit operations so sorry if I'm wrong, but I just tried this here and to me it looks like your loop isn't doing the same thing. Can you tell me what I'm missing? for i in (123, 77, 3566): n = i s = 0 while n: s += n&15 n = n>>4 print(s) n = i s = 0 while n: s += n%10 n = n//10 print(s) print()
Edward, but aren't we comparing apples and oranges then?