Skip to content

Positive mod in Python

  • by

The modulus operator (%) in Python does not provide a positive modulo when the dividend is negative. However, you can use a simple formula to ensure a positive remainder:

def positive_modulo(dividend, divisor):
    return (dividend % divisor + divisor) % divisor

Example

dividend = -17
divisor = 5

positive_modulo = (dividend % divisor + divisor) % divisor
print(positive_modulo)  # Output: 3

In the code snippet above, we calculate (dividend % divisor + divisor) % divisor to obtain the positive modulo. This formula works by adding the divisor to the result of dividend % divisor and then taking the modulus of the sum with the divisor again.

This guarantees a positive remainder regardless of the signs of the dividend and divisor. In this case, the positive modulo of -17 divided by 5 is 3.

Positive mod in Python example

Here’s an example that demonstrates how to calculate the positive modulo of a negative dividend in Python:

def positive_modulo(dividend, divisor):
    return (dividend % divisor + divisor) % divisor

dividend = -17
divisor = 5

positive_modulo_result = positive_modulo(dividend, divisor)
print(positive_modulo_result) 

Output:

Positive mod in Python

In the example above, we define a function called positive_modulo that implements the formula (dividend % divisor + divisor) % divisor to calculate the positive modulo. We pass the negative dividend -17 and divisor 5 to the function, and it returns the positive modulo 3.

Do comment if you have any doubts or suggestions on this Python topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading