Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modular addition in python

I want to add a number y to x, but have x wrap around to remain between zero and 48. Note y could be negative but will never have a magnitude greater than 48. Is there a better way of doing this than:

x = x + y
if x >= 48:
    x = x - 48
elif x < 0:
    x = x + 48

?

like image 565
Double AA Avatar asked Jul 13 '11 20:07

Double AA


People also ask

What is modular function in Python?

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem. The modulo operator is considered an arithmetic operation, along with + , - , / , * , ** , // . The basic syntax is: a % b.

What is modulo addition?

Now here we are going to discuss a new type of addition, which is known as “addition modulo m” and written in the form a+mb, where a and b belong to an integer and m is any fixed positive integer. By definition we have. a+mb=r,for0⩽r<m.

How do I install modulus in Python?

The Python modulo operator calculates the remainder of dividing two values. This operator is represented by the percentage sign (%). The syntax for the modulo operator is: number1 % number2. The first number is divided by the second then the remainder is returned.


1 Answers

Wouldn't just (x+ y)% 48 be suitable for you. See more on modulo here.

like image 98
eat Avatar answered Oct 30 '22 13:10

eat