A function that does the opposite of an addition mod 2³²

0
def mod_2to32sub1(x):
    s = 0 # the sum

    while x > 0: # get the digits
        s += x & (2**32-1)
        x >>= 32

    if s > 2**32-1:
        return mod_2to32sub1(s)
    elif s == 2**32-1:
        return 0
    else:
        return s

This function above does 'adition mod 2 ^ 32'.

Why the code? Well, I would like to ask your help to create a function that does the opposite of this function, but I have difficulties. Help me understand how I can be doing this.

To best exemplify, I have the following number, 554900798. It is '9144835390', before adding the 2³² module. Well, I would like to turn the '554900798' to '9144835390' again. I hope it has become clear.

What can I be doing?

Thank you in advance.

    
asked by anonymous 03.12.2018 / 21:33

1 answer

4

Module (remainder of division) is not a reversible operation.

Consider the simplest case with the % operator:

In [1]: 9144835390 % 2**32
Out[1]: 554900798

Here we note that the operation is the same, based on your example.

To visualize the question better, imagine the following example: We want the remainder of the division by 7 by 3.

In [2]: 7 % 3
Out[2]: 1

The result is 1. But what about the remainder of the 10 by 3 division?

In [3]: 10 % 3
Out[3]: 1

It's also 1. The same goes for 13, 16, etc.

That is, there are infinite numbers that result in the same remainder for any given divider. The operation can not be rolled back, because information is lost in the process.

If you want numbers that fit this profile, you can find them:

def gerar_nums(resto, divisor):
    i = 1
    while True:
        yield i * divisor + resto
        i += 1

gerador = gerar_nums(1, 3)
for i, num in enumerate(gerador):
    print(num, end=', ')
    if i == 5:
        break

# 4, 7, 10, 13, 16, 19,
    
03.12.2018 / 23:30