A small kernel of code for playing with Galois fields of arbitrary characteristic
Revision | 54f6125563fe5afee1c2a9ce87ec10c7c972baa1 (tree) |
---|---|
Time | 2021-03-29 07:42:16 |
Author | Eric Hopper <hopper@omni...> |
Commiter | Eric Hopper |
Add Python 3.9 type annotations to numtheory_utils.
@@ -1,4 +1,11 @@ | ||
1 | -def extended_gcd(x, y): | |
1 | +from collections.abc import Collection | |
2 | +from typing import Any, Callable, TypeVar | |
3 | + | |
4 | +__all__ = [ | |
5 | + 'extended_gcd', 'print_group_table', 'mult_inverse', 'print_mult_inverses' | |
6 | +] | |
7 | + | |
8 | +def extended_gcd(x: int, y: int): | |
2 | 9 | """Return a tuple 't' with three elements such that: |
3 | 10 | t[0) * x + t[1] * y == t[2] |
4 | 11 |
@@ -50,8 +57,11 @@ | ||
50 | 57 | # (1 * 23 - 1 * 16) - 3 * (3 * 16 - 2 * 23) = 7 * 23 - 10 * 16 = 1 |
51 | 58 | # 13 * 16 - 9 * 23 = 1 |
52 | 59 | |
53 | - | |
54 | -def print_group_table(elements, op): | |
60 | +T = TypeVar('T') | |
61 | +def print_group_table( | |
62 | + elements: Collection[T], | |
63 | + op: Callable[[T, T], T] | |
64 | +): | |
55 | 65 | width = max(len(str(x)) for x in elements) |
56 | 66 | print(f'{" ":{width}} |', end='') |
57 | 67 | for a in elements: |
@@ -65,7 +75,16 @@ | ||
65 | 75 | print() |
66 | 76 | |
67 | 77 | |
68 | -def print_mult_inverses(a, b): | |
78 | +def mult_inverse(a: int, b: int): | |
79 | + """If possible, return a number n such that a * n mod b == 1, otherwise | |
80 | + raise an exception.""" | |
81 | + am, bm, g = extended_gcd(a, b) | |
82 | + if g == 0: | |
83 | + raise ValueError(f"{a} and {b} are not relatively prime.") | |
84 | + return am if am > 0 else b + am | |
85 | + | |
86 | + | |
87 | +def print_mult_inverses(a: int, b: int): | |
69 | 88 | """Prints out the multiplicative inverse of a (mod b) and the multiplicative |
70 | 89 | inverse of b (mod a). |
71 | 90 | """ |