/* -*-apcalc-*- * * Testbed for %$\gf{2}$% poltnomial arithmetic * * (c) 2000 Straylight/Edgeware */ /*----- Licensing notice --------------------------------------------------* * * This file is part of Catacomb. * * Catacomb is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * Catacomb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with Catacomb; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ /*----- Object types ------------------------------------------------------*/ obj gf { x }; /*----- Static variables --------------------------------------------------*/ static obj gf example_gf_object; /*----- Main code ---------------------------------------------------------*/ dummy = config("lib_debug", -1); define gf(x) { local obj gf g; g.x = x; return (g); } define gfint(x) { if (istype(x, example_gf_object)) return (x.x); else return (x); } define gf_add(x, y) = gf(xor(gfint(x), gfint(y))); define gf_sub(x, y) = gf(xor(gfint(x), gfint(y))); define gf_neg(x) = x; define gf_mul(x, y) { local a = gfint(x), b = gfint(y), z = 0, i, bits = highbit(a); for (i = 0; i <= bits; i++) { if (bit(a, i)) z = xor(z, b << i); } return gf(z); } define gfx_div(rx, dx) { local r = gfint(rx), d = gfint(dx), i; local q = 0, dbits, rbits; dbits = highbit(d); rbits = highbit(r); for (i = rbits - dbits; i >= 0; i--) { if (bit(r, i + dbits)) { r = xor(r, d << i); q |= (1 << i); } } return list(q, r); } define gf_div(x, y) { local l; l = gfx_div(x, y); return gf(l[[0]]); } define gf_mod(x, y) { local l; l = gfx_div(x, y); return gf(l[[1]]); } define gf_gcd(a, 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)) { 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; a = b; b = r; } g = a; } 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 -------------------------------------------------*/