zad 02,03 #37

Closed
s426159 wants to merge 14 commits from s426159/DALGLI0:master into master
Showing only changes of commit 809ceae806 - Show all commits

View File

@ -1,14 +1,42 @@
class Polynomial {
constructor(coefArray) {
this.degree = coefArray.length - 1;
constructor(mod, coefArray) {
this.mod = mod;
this.degree = (coefArray.length - 1);
this.coefficients = coefArray;
}
}
exports.Class = Polynomial;
function multiply(p1, p2, n) {
function add(p1, p2) {
let n;
if (p1.mod !== p2.mod) {
throw "different modulo"
} else {
n = p1.mod;
}
let len_p1 = p1.coefficients.length;
let len_p2 = p2.coefficients.length;
result = new Array(Math.max(len_p1, len_p2)).fill(0);
if (len_p1 > len_p2) {
for (let x = 0; x < len_p1 - len_p2; x++) p2.coefficients.push(0);
} else {
for (let x = 0; x < len_p2 - len_p1; x++) p1.coefficients.push(0);
}
for (let i = 0; i < result.length; i++) {
result[i] = (p1.coefficients[i] + p2.coefficients[i]) % n;
}
return new Polynomial(n, result);
}
exports.add = add;
function multiply(p1, p2) {
let n;
if (p1.mod !== p2.mod) {
throw "different modulo"
} else {
n = p1.mod;
}
let f = p1.coefficients;
let g = p2.coefficients;
result = new Array(f.length + g.length - 1).fill(0);
@ -19,11 +47,17 @@ function multiply(p1, p2, n) {
result[i + j] += f[i] * g[j];
}
}
return new Polynomial(result.map(x => (x % n) + (x < 0 ? n : 0)));
return new Polynomial(n, result.map(x => (x % n) + (x < 0 ? n : 0)));
}
exports.multiply = multiply;
function divide(p1, p2, n) {
function divide(p1, p2) {
let n;
if (p1.mod !== p2.mod) {
throw "different modulo"
} else {
n = p1.mod;
}
let inverse = (x) => {
for (let i = 1; i < 2; i++) {
let r = (i * x) % 2;
@ -51,7 +85,7 @@ function divide(p1, p2, n) {
tmp.push(0);
}
tmp.push(tmp_coef);
tmp_poly = new Polynomial(tmp);
tmp_poly = new Polynomial(n, tmp);
let sub = multiply(p2, tmp_poly, n);
let tmp_f = [];
for (let i = 0; i < f.length; i++) {
@ -66,16 +100,17 @@ function divide(p1, p2, n) {
f.pop();
}
return new Polynomial(f);
return new Polynomial(n, f);
}
function gcd(p1, p2, n) {
exports.divide = divide;
function gcd(p1, p2) {
if (p2.coefficients.length === 0) {
return p1;
}
return gcd(p2, divide(p1, p2, n), n);
return gcd(p2, divide(p1, p2));
}
exports.multiply = multiply;
exports.divide = divide;
exports.gcd = gcd;