From be73ad2fde721fb8e3bfb25d1cf52a733c10392f Mon Sep 17 00:00:00 2001 From: Kacper Kruczek Date: Sun, 1 Jul 2018 11:43:24 +0200 Subject: [PATCH] 02 power --- polynomial.js | 62 ++++++++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 28 deletions(-) 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) {