How to resolve the algorithm Polynomial long division step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Polynomial long division step by step in the Wren programming language

Table of Contents

Problem Statement

Let us suppose a polynomial is represented by a vector,

x

{\displaystyle x}

(i.e., an ordered collection of coefficients) so that the

i

{\displaystyle i}

th element keeps the coefficient of

x

i

{\displaystyle x^{i}}

, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.

Example for clarification

This example is from Wikipedia, but changed to show how the given pseudocode works.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Polynomial long division step by step in the Wren programming language

Source code in the wren programming language

import "/dynamic" for Tuple

var Solution = Tuple.create("Solution", ["quotient", "remainder"])

var polyDegree = Fn.new { |p|
    for (i in p.count-1..0) if (p[i] != 0) return i
    return -2.pow(31)
}

var polyShiftRight = Fn.new { |p, places|
    if (places <= 0) return p
    var pd = polyDegree.call(p)
    if (pd + places >= p.count) {
        Fiber.abort("The number of places to be shifted is too large.")
    }
    var d = p.toList
    for (i in pd..0) {
        d[i + places] = d[i]
        d[i] = 0
    }
    return d
}

var polyMultiply = Fn.new { |p, m|
    for (i in 0...p.count) p[i] = p[i] * m
}

var polySubtract = Fn.new { |p, s|
    for (i in 0...p.count) p[i] = p[i] - s[i]
}

var polyLongDiv = Fn.new { |n, d|
    if (n.count != d.count) {
        Fiber.abort("Numerator and denominator vectors must have the same size")
    }
    var nd = polyDegree.call(n)
    var dd = polyDegree.call(d)
    if (dd < 0) {
        Fiber.abort("Divisor must have at least one one-zero coefficient")
    }
    if (nd < dd) {
        Fiber.abort("The degree of the divisor cannot exceed that of the numerator")
    }
    var n2 = n.toList
    var q = List.filled(n.count, 0)
    while (nd >= dd) {
        var d2 = polyShiftRight.call(d, nd - dd)
        q[nd - dd] = n2[nd] / d2[nd]
        polyMultiply.call(d2, q[nd - dd])
        polySubtract.call(n2, d2)
        nd = polyDegree.call(n2)
    }
    return Solution.new(q, n2)
}

var polyShow = Fn.new { |p|
    var pd = polyDegree.call(p)
    for (i in pd..0) {
        var coeff = p[i]
        if (coeff != 0) {
            System.write(
                (coeff ==  1) ? ((i < pd) ? " + " :  "") :
                (coeff == -1) ? ((i < pd) ? " - " : "-") :
                (coeff <   0) ? ((i < pd) ? " - %(-coeff)" : "%(coeff)") :
                                ((i < pd) ? " + %( coeff)" : "%(coeff)")
            )
            if (i > 1) {
                System.write("x^%(i)")
            } else if (i == 1) {
                System.write("x")
            }
        }
    }
    System.print()
}

var n = [-42, 0, -12, 1]
var d = [ -3, 1,   0, 0]
System.write("Numerator   : ")
polyShow.call(n)
System.write("Denominator : ")
polyShow.call(d)
System.print("-------------------------------------")
var sol = polyLongDiv.call(n, d)
System.write("Quotient    : ")
polyShow.call(sol.quotient)
System.write("Remainder   : ")
polyShow.call(sol.remainder)

class Polynom {
    construct new(factors) {
        _factors = factors.toList
    }

    factors { _factors.toList }

    /(divisor) {
        var curr = canonical().factors
        var right = divisor.canonical().factors
        var result = []
        var base = curr.count - right.count
        while (base >= 0) {
            var res = curr[-1] / right[-1]
            result.add(res)
            curr = curr[0...-1]
            for (i in 0...right.count-1) {
                curr[base + i] = curr[base + i] - res * right[i]
            }
            base = base - 1
        }
        var quot = Polynom.new(result[-1..0])
        var rem = Polynom.new(curr).canonical()
        return [quot, rem]
    }

    canonical() {
        if (_factors[-1] != 0) return this
        var newLen = factors.count
        while (newLen > 0) {
            if (_factors[newLen-1] != 0) return Polynom.new(_factors[0...newLen])
            newLen = newLen - 1
        }
        return Polynom.new(_factors[0..0])
    }

    toString { "Polynomial(%(_factors.join(", ")))" }
}

var num = Polynom.new([-42, 0, -12, 1])
var den = Polynom.new([-3, 1, 0, 0])
var res = num / den
var quot = res[0]
var rem = res[1]
System.print("%(num) / %(den) = %(quot) remainder %(rem)")

  

You may also check:How to resolve the algorithm Sorting algorithms/Stooge sort step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Remove lines from a file step by step in the Go programming language
You may also check:How to resolve the algorithm Department numbers step by step in the Mercury programming language
You may also check:How to resolve the algorithm Text processing/Max licenses in use step by step in the R programming language
You may also check:How to resolve the algorithm Hofstadter Q sequence step by step in the Quackery programming language