summary |
shortlog |
log |
commit | commitdiff |
tree
raw |
patch |
inline | side by side (from parent 1:
50c4627)
* Implement a GCD algorithm in calc/gfx.cal (partly to help with
testing the Python bindings).
* Clean up the MP and GF implementations: expunge incorrect commentary
and redundant code.
- local g, x, y, X, Y, u, v, t, q, r;
- x = gf(1); X = gf(0);
- y = gf(0); Y = gf(1);
-
- if (b == gf(0)) { g = a; } else if (a == gf(0)) { g = b; }
+ local swap = 0;
+ local g, x = 1, X = 0, y = 0, Y = 1, q, r, t;
+ if (a.x < b.x) {
+ t = a; a = b; b = t;
+ swap = 1;
+ }
+ if (b == gf(0))
+ g = a;
else {
while (b != gf(0)) {
else {
while (b != gf(0)) {
- q = gf_div(b, a); r = gf_mod(b, a);
+ q = gf_div(a, b); r = gf_mod(a, b);
t = X * q + x; x = X; X = t;
t = Y * q + y; y = Y; Y = t;
t = X * q + x; x = X; X = t;
t = Y * q + y; y = Y; Y = t;
- if (g != gf(1)) quit "not coprime in gf_inv";
- return Y;
+ if (swap) {
+ t = x; x = y; y = t;
+ }
+ return list(g, x, y);
+}
+
+define gf_inv(a, b)
+{
+ local l = gf_gcd(b, a);
+ if (l[[0]] != gf(1)) quit "not coprime in gf_inv";
+ return l[[2]];
}
/*----- That's all, folks -------------------------------------------------*/
}
/*----- That's all, folks -------------------------------------------------*/
- /* --- Take a reference to the arguments --- */
-
- a = MP_COPY(a);
- b = MP_COPY(b);
-
- /* --- Make sure @a@ and @b@ are not both even --- */
-
- MP_SPLIT(a); a->f &= ~MP_NEG;
- MP_SPLIT(b); b->f &= ~MP_NEG;
+ /* --- Main extended Euclidean algorithm --- */
u = MP_COPY(a);
v = MP_COPY(b);
u = MP_COPY(a);
v = MP_COPY(b);
gf_div(&q, &u, u, v);
if (f & f_ext) {
t = gf_mul(MP_NEW, X, q);
gf_div(&q, &u, u, v);
if (f & f_ext) {
t = gf_mul(MP_NEW, X, q);
MP_DROP(x); x = X; X = t;
t = gf_mul(MP_NEW, Y, q);
MP_DROP(x); x = X; X = t;
t = gf_mul(MP_NEW, Y, q);
MP_DROP(y); y = Y; Y = t;
}
t = u; u = v; v = t;
MP_DROP(y); y = Y; Y = t;
}
t = u; u = v; v = t;
MP_DROP(v);
MP_DROP(X); MP_DROP(Y);
MP_DROP(v);
MP_DROP(X); MP_DROP(Y);
- MP_DROP(a); MP_DROP(b);
}
/* -- @gf_modinv@ --- *
}
/* -- @gf_modinv@ --- *
- /* --- Take a reference to the arguments --- */
+ /* --- Force the signs on the arguments and take copies --- */
a = MP_COPY(a);
b = MP_COPY(b);
a = MP_COPY(a);
b = MP_COPY(b);
- /* --- Make sure @a@ and @b@ are not both even --- */
-
MP_SPLIT(a); a->f &= ~MP_NEG;
MP_SPLIT(b); b->f &= ~MP_NEG;
u = MP_COPY(a);
v = MP_COPY(b);
MP_SPLIT(a); a->f &= ~MP_NEG;
MP_SPLIT(b); b->f &= ~MP_NEG;
u = MP_COPY(a);
v = MP_COPY(b);
+ /* --- Main extended Euclidean algorithm --- */
+
while (!MP_ZEROP(v)) {
mp *t;
mp_div(&q, &u, u, v);
while (!MP_ZEROP(v)) {
mp *t;
mp_div(&q, &u, u, v);