Search code examples
python-3.xwhile-loopinfinite-loop

Trying to calculate checksum but end up stuck in infinite loop - please explain?


I'm trying to calculate the checksum from a given card number. I know there's plenty of ready made better performing algorithms out there. What I'd like to know is why do I get stuck in an infinite loop I just don't get it.

'numbers' is a list of chars from a String e.g ("4000002345326738")

def get_checksum(numbers):
sum_ = 0
for n in numbers:
    x = int(n)
    sum_ += x
found = False
checksum = 0
while not found:
    if sum_ % 10 == 0:
        return checksum
    else:
        checksum += 1
        sum_ += checksum

Solution

  • Let us see, each iteration checksum increases by one, and sum_ increases by checksum. This means that at iteration number n, your sum_ is equal to

    sum_ = sum_initial + 1 + 2 + ... + n = sum_initial + n*(n+1)/2

    You believe that at some point sum_ will be divisible by 10. This is not true. The remainder of n(n+1)/2 modulo 10 only depends on n % 20, so it easy to see that possible values of n(n+1)/2 % 10 are:

    0, 1, 3, 6, 5, 8

    So, if the initial sum_ is 1, 3, 6, or 8 modulo 10, the sum_ will never be divisible by 2, and you get stuck in an infinite cycle.

    BTW, since found variable is not used anywhere, you could just write while True: