JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Computing modular multiplicative inverse in Python

Author:JIYIK Last Updated:2025/05/04 Views:

If we have two numbers aand m, then athe modular multiplicative inverse of is mmodulo xif:

a * x % m = 1

In this case, the multiplicative inverse exists only if aand mare relatively prime, that is, if the greatest common divisor of aand mis 1.

xThe value of can range from 1to m-1.


Modular multiplicative inverse using naive iterative method

Suppose we need to mfind athe multiplicative inverse of modulo . If a modular multiplicative inverse exists, its value can be from 1to m-1. Therefore, we iterate over this range and check the condition for modular multiplicative inverse. If any number in the range satisfies the condition, we take the number as modular multiplicative inverse.

def find_mod_inv(a, m):

    for x in range(1, m):
        if (a % m) * (x % m) % m == 1:
            return x
    raise Exception("The modular inverse does not exist.")


a = 13
m = 22

try:
    res = find_mod_inv(a, m)
    print("The required modular inverse is: " + str(res))

except:
    print("The modular inverse does not exist.")

Output:

The required modular inverse is: 17

Here we have a find_mod_invfunction called that takes aand mas input and returns the multiplicative inverse of mmodulo .a

If number does not have a multiplicative reciprocal modulo , it will raise a asum .maException

From the above example, we can see that the modular multiplicative inverse of 22under module is .1317


pow()Modular inverse using built-in functions

We can also use Python's built-in function pow()to calculate the modular multiplicative inverse of a number.

a = 38
m = 97
res = pow(a, m - 2, m)
print("The required modular inverse is: " + str(res))

Output:

The required modular inverse is: 23

pow()To compute a modular multiplicative inverse using the method, pow()the first argument to the method will be the number whose modular inverse you want to find, the second argument will be the modulus to subtract 2, and the last argument will be the order of the moduli.

However, for Python 3.8versions and later, we can replace the second parameter with -1.

a = 38
m = 97
res = pow(a, -1, m)
print("The required modular inverse is: " + str(res))

Output

The required modular inverse is: 23

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Enumerating a dictionary in Python

Publish Date:2025/05/05 Views:98 Category:Python

The function in Python enumerate() returns an object of enumeration type and adds a counter variable to iterate over a list or other type of collection. It makes looping over such objects easier. When we pass an enumeration object to list()

Changing dictionary values in Python

Publish Date:2025/05/05 Views:108 Category:Python

This tutorial will discuss various ways to change the value of a particular key in Python dictionary. We can do this by using the following methods. dict.update() method for cycle. Dictionary Unpacking dict.update() How to change dictionary

Finding the maximum value in a Python dictionary

Publish Date:2025/05/05 Views:60 Category:Python

This tutorial explains how to get a key with the maximum value in Python. Since the method has changed from the previous Python versions, it also lists some sample codes to clarify the concepts. Use operator.itemgetter() the method to get t

How to read input from stdin in Python

Publish Date:2025/05/05 Views:124 Category:Python

This tutorial discussed stdin the methods of reading input from in Python. You can read directly from the console or from a file name specified in the console. In Python, fileinput.input() use stdin fileinput We can use the read module in P

Maximum integer in Python

Publish Date:2025/05/05 Views:55 Category:Python

This tutorial will discuss the maximum integer value in different versions of Python and how we can get it. In Python 2, integers and long integers are different data types. The maximum value of an integer is 2 31 -1. If the value exceeds t

Get a list of time zones using Python

Publish Date:2025/05/05 Views:107 Category:Python

When developing real-world applications, software developers must ensure that the application can support users from both their own country and other parts of the world. Since most countries have different time zones and many people around

Convert NumPy array to list in Python

Publish Date:2025/05/05 Views:101 Category:Python

Lists and arrays are the two most basic and commonly used collection objects in Python. They are both mutable and are used to store a collection of elements under a common name and each element has a specific location that can be used to ac

Appending 2D Arrays in Python

Publish Date:2025/05/05 Views:64 Category:Python

In Python, we can have ND arrays. We can use NumPy module to process arrays in Python. This tutorial demonstrated the different methods you can use to append values ​​to a two-dimensional array in Python. Use append() the function to ap

Sliding average of NumPy arrays in Python

Publish Date:2025/05/05 Views:190 Category:Python

The sliding average is often used to study time series data by calculating the average of data at a specific time interval. It is used to eliminate some short-term fluctuations and study data trends. When studying stock price trends, the si

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial