diff --git a/polynomial.js b/polynomial.js index ad2a899..8f9fc44 100644 --- a/polynomial.js +++ b/polynomial.js @@ -8,13 +8,17 @@ class Polynomial { exports.Class = Polynomial; -function add(p1, p2) { +function get_mod(p1, p2) { let n; if (p1.mod !== p2.mod) { throw "different modulo" } else { - n = p1.mod; + return p1.mod; } +} + +function prepare(p1, p2) { + let n = get_mod(p1, p2); let len_p1 = p1.coefficients.length; let len_p2 = p2.coefficients.length; result = new Array(Math.max(len_p1, len_p2)).fill(0); @@ -23,6 +27,19 @@ function add(p1, p2) { } else { for (let x = 0; x < len_p2 - len_p1; x++) p1.coefficients.push(0); } + return { + result, + n + }; + +} + +function add(p1, p2) { + + let { + result, + n + } = prepare(p1, p2); for (let i = 0; i < result.length; i++) { result[i] = (p1.coefficients[i] + p2.coefficients[i]) % n; } @@ -31,20 +48,10 @@ function add(p1, p2) { exports.add = add; function sub(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); - } + let { + result, + n + } = prepare(p1, p2); for (let i = 0; i < result.length; i++) { result[i] = (p1.coefficients[i] - p2.coefficients[i]) % n; } @@ -53,12 +60,7 @@ function sub(p1, p2) { exports.sub = sub; function sub(p1, p2) { - let n; - if (p1.mod !== p2.mod) { - throw "different modulo" - } else { - n = p1.mod; - } + let n = get_mod(p1, p2); let len_p1 = p1.coefficients.length; let len_p2 = p2.coefficients.length; result = new Array(Math.max(len_p1, len_p2)).fill(0); @@ -75,12 +77,7 @@ function sub(p1, p2) { exports.add = add; function multiply(p1, p2) { - let n; - if (p1.mod !== p2.mod) { - throw "different modulo" - } else { - n = p1.mod; - } + let n = get_mod(p1, p2); let f = p1.coefficients; let g = p2.coefficients; result = new Array(f.length + g.length - 1).fill(0); @@ -95,6 +92,15 @@ function multiply(p1, p2) { } exports.multiply = multiply; +function power(p1, pow) { + let result = p1; + for (let i = 1; i < pow; i++) { + result = multiply(result, p1); + } + return result; +} +exports.power = power; + function divide(p1, p2) { let n; if (p1.mod !== p2.mod) {