Bobbi Towers / May 13 2019
Adding and subtracting polynomials
Add.
Your answer should be a polynomial in standard form.
0.1s
Clojure
(defn zero-pad [poly1 poly2] (cond (> (count poly1) (count poly2)) (recur poly1 (cons 0 poly2)) (> (count poly2) (count poly1)) (recur (cons 0 poly1) poly2) :else [poly1 poly2])) (defn add-poly [poly1 poly2] (apply map + (zero-pad poly1 poly2))) (defn sub-poly [poly1 poly2] (apply map + (zero-pad poly1 (map - poly2)))) (defn print-poly [poly] (loop [n (dec (count poly)) p poly s ""] (if (empty? p) s (recur (dec n) (rest p) (if (= 0 (first p)) (str s " ") (str s (first p) (if (= 0 n) " " (if (= 1 n) "x " (str "x^" n " "))))))))) (print-poly (sub-poly [-9 0 0 0 8] [-9 2 5 0 0]))
" -2x^3 -5x^2 8 "