Skip to content

Commit 851169f

Browse files
committed
python
1 parent 55b7edc commit 851169f

1 file changed

Lines changed: 21 additions & 25 deletions

File tree

Mathematics/README.md

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -70,31 +70,27 @@ To divide $a$ by $b$ modulo $m$, find the modular inverse of $b$ (i.e., $b^{-1}$
7070

7171
### Methods to Find Modular Inverse
7272

73-
#### a) Extended Euclidean Algorithm (C++ Example)
74-
75-
```cpp
76-
int mod_inv(int a, int m) {
77-
int m0 = m, t, q;
78-
int x0 = 0, x1 = 1;
79-
if (m == 1) return 0;
80-
while (a > 1) {
81-
q = a / m;
82-
t = m;
83-
m = a % m, a = t;
84-
t = x0;
85-
x0 = x1 - q * x0;
86-
x1 = t;
87-
}
88-
if (x1 < 0) x1 += m0;
89-
return x1;
90-
}
91-
92-
int mod_div(int a, int b, int m) {
93-
a %= m;
94-
int inv = mod_inv(b, m);
95-
if (inv == -1) return -1; // Modular inverse doesn't exist
96-
return (a * inv) % m;
97-
}
73+
#### a) Extended Euclidean Algorithm (Python Example)
74+
75+
```python
76+
def mod_inv(a, m):
77+
m0, x0, x1 = m, 0, 1
78+
if m == 1:
79+
return 0
80+
while a > 1:
81+
q = a // m
82+
a, m = m, a % m
83+
x0, x1 = x1 - q * x0, x0
84+
if x1 < 0:
85+
x1 += m0
86+
return x1
87+
88+
def mod_div(a, b, m):
89+
a %= m
90+
inv = mod_inv(b, m)
91+
if inv == -1:
92+
return -1 # Modular inverse doesn't exist
93+
return (a * inv) % m
9894
```
9995

10096
#### b) Fermat's Little Theorem (when $m$ is prime)

0 commit comments

Comments
 (0)