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

Asked

Viewed 63 times

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 makes 'adition mod 2 32'.

What’s with the code? Well, I would ask for your help in creating a function that does the opposite of that function, but I have difficulties. Help me understand how I can be doing this.

To illustrate better, I have the following number, 554900798. It is '9144835390', before adding module 2³². Well, I’d like to turn '554900798' to '9144835390' again. I hope that’s clear.

What can I be doing?

Thanks in advance.

  • How does he make the "addition" of the addition definition predict two operands and one result? There only one operand is being passed

  • One would be x and the other 0. The function is equivalent to '>>> 0' of Javascript. Only I wanted to understand if I can create an inverse function (<<). I was asked to do this in the course

1 answer

4


Module (remaining split) is not a reversible operation.

Let’s consider the simplest case with the operator %:

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

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

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

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

The result is 1. But and the rest of the division 10 by 3?

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

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

You mean, there are infinite numbers that result in the same remainder for any given divisor. Cannot reverse the operation 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,
  • 1

    Got it. Thanks a lot. It helped me a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.