Question

I am working a python assignment for my programming class. the question asks us to take some input and make it in the form a/b mod N, returning a/b mod N as an integer between 0 and n-1.if b has a multiplicative inverse mod N

here is what i did: for example, input >>> a = 3, b= 2, n = 7 take the input and evaluate 3/2, then evaluate 1.5mod7

however, this is not the answer the teacher wants. the correct answer is 5.

what i was thinking of doing was finding an integer in the range(1, n) such that a*integer == 1 mod N. which is what we want. however, out of all the test cases i was given, only the example works this way. here are the examples of input and the correct output

input1: 3,2,7
input2: 14, 67, 88
input3: 10, 3, 40

out1:5 
out2:58
out3:30

i know some answers are undefined, and I know how to get those,

i am completely lost on how to do these three and get he answers required.

Was it helpful?

Solution

In normal arithmetic, division can be performed by multiplying by the inverse. For example, the inverse of 2 is 1/2, so to divide 3 by 2 you can multiply 3 by 1/2. Note that 2 and its inverse 1/2 multiply to 1, which is always true; that's the definition of the inverse.

Modular arithmetic does not admit division, so you must multiply by the inverse. When working mod 7, the inverse of 2 is 4, because 2 * 4 = 8 = 1 (mod 7); the inverse is always that number which, when multiplied, is equal to 1, just as in normal arithmetic. So, to divide 3 by 2 (mod 7), you multiply 3 by 4 (mod 7). Now 3 * 4 = 12 = 5 (mod 7), so the result is 5, as your instructor said.

You can calculate the modular inverse of a number using the extended Euclidean algorithm. I'll leave it to you to work that out. There are lots of places where you can look up the extended Euclidean algorithm (probably including your textbook or the class notes given to you by your instructor). Or you can come back here and ask another question if you are having trouble with your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top