classification
Title: Long integer arithmetic
Type: behavior Stage: resolved
Components: Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: David Srebnick, remi.lapeyre
Priority: normal Keywords:

Created on 2020-07-03 12:26 by David Srebnick, last changed 2020-07-03 12:42 by christian.heimes. This issue is now closed.

Messages (2)
msg372925 - (view) Author: David Srebnick (David Srebnick) Date: 2020-07-03 12:26
The following program is one way of computing the sum of digits in a number.  It works properly for the first case, but fails for the second one.

def digitsum(num):
    digsum = 0
    tnum = num
    while tnum > 0:
        print("tnum = %d, digsum = %d" % (tnum,digsum))        
        digsum += (tnum % 10)
        tnum = int((tnum - (tnum % 10)) / 10)
    return digsum

print(digitsum(9999999999999999))
print(digitsum(99999999999999999))
msg372929 - (view) Author: RĂ©mi Lapeyre (remi.lapeyre) * Date: 2020-07-03 12:40
This is because you used the floating point division operator `/` instead of the integer division `//`:


def digitsum(num):
    digsum = 0
    tnum = num
    while tnum > 0:
        print("tnum = %d, digsum = %d" % (tnum,digsum))        
        digsum += (tnum % 10)
        tnum = int((tnum - (tnum % 10)) // 10)
    return digsum

gives the result you expect.


Please ask for help on StackOverflow or the python-help mailing list first as this bug tracker is for reporting bugs in the Python interpreter itself and not for general help with Python programming.

The various numeric operator are documented at https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex
History
Date User Action Args
2020-07-03 12:42:30christian.heimessetstatus: open -> closed
resolution: not a bug
stage: resolved
2020-07-03 12:40:48remi.lapeyresetnosy: + remi.lapeyre
messages: + msg372929
2020-07-03 12:26:22David Srebnickcreate