Polynomial synthetic division: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|REXX}}: add alternate output)
No edit summary
Line 1: Line 1:
{{draft task|Classic CS problems and programs}}{{Wikipedia}}
{{draft task|Classic CS problems and programs}}{{Wikipedia}}
:<cite>In algebra, [[wp:Synthetic division|polynomial synthetic division]] is an algorithm for dividing a polynomial by another polynomial of the same or lower degree in an efficient way using a clever trick involving clever manipulations of coefficients, which results in a lot less complexity than than [[polynomial long division]].</cite>
:<cite>In algebra, [[wp:Synthetic division|polynomial synthetic division]] is an algorithm for dividing a polynomial by another polynomial of the same or lower degree in an efficient way using a trick involving clever manipulations of coefficients, which results in a lower time complexity than [[polynomial long division]].</cite>


__TOC__
__TOC__

Revision as of 09:49, 18 August 2016

Polynomial synthetic division is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
This page uses content from Wikipedia. The original article was at Polynomial synthetic division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial synthetic division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree in an efficient way using a trick involving clever manipulations of coefficients, which results in a lower time complexity than polynomial long division.

J

Solving this the easy way:

<lang J> psd=: [:(}. ;{.) ([ (] -/@,:&}. (* {:)) ] , %&{.~)^:(>:@-~&#)~</lang>

Task example:

<lang J> (1, (-12), 0, -42) psd (1, -3) ┌────────┬────┐ │1 _9 _27│_123│ └────────┴────┘ </lang>

Java

Translation of: Python

<lang java>import java.util.Arrays;

public class Test {

   public static void main(String[] args) {
       int[] N = {1, -12, 0, -42};
       int[] D = {1, -3};
       System.out.printf("%s / %s = %s",
               Arrays.toString(N),
               Arrays.toString(D),
               Arrays.deepToString(extendedSyntheticDivision(N, D)));
   }
   static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
       int[] out = dividend.clone();
       int normalizer = divisor[0];
       for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
           out[i] /= normalizer;
           int coef = out[i];
           if (coef != 0) {
               for (int j = 1; j < divisor.length; j++)
                   out[i + j] += -divisor[j] * coef;
           }
       }
       int separator = out.length - (divisor.length - 1);
       return new int[][]{
           Arrays.copyOfRange(out, 0, separator),
           Arrays.copyOfRange(out, separator, out.length)
       };
   }

}</lang>

[1, -12, 0, -42] / [1, -3] = [[1, -9, -27], [-123]]

Python

Here is an extended synthetic division algorithm, which means that it supports a divisor polynomial (instead of a monomial or a binomial). It also supports non-monic polynomials (polynomials which first coefficient is different than 1). Polynomials are represented by lists of coefficients with decreasing degree (left-most is the major degree , right-most is the constant).

Works with: Python 2.x

<lang python># -*- coding: utf-8 -*-

def extended_synthetic_division(dividend, divisor):

   Fast polynomial division by using Extended Synthetic Division. Also works with non-monic polynomials.
   # dividend and divisor are both polynomials, which are here simply lists of coefficients. Eg: x^2 + 3x + 5 will be represented as [1, 3, 5]
   out = list(dividend) # Copy the dividend
   normalizer = divisor[0]
   for i in xrange(len(dividend)-(len(divisor)-1)):
       out[i] /= normalizer # for general polynomial division (when polynomials are non-monic),
                                # we need to normalize by dividing the coefficient with the divisor's first coefficient
       coef = out[i]
       if coef != 0: # useless to multiply if coef is 0
           for j in xrange(1, len(divisor)): # in synthetic division, we always skip the first coefficient of the divisior,
                                             # because it's only used to normalize the dividend coefficients
               out[i + j] += -divisor[j] * coef
   # The resulting out contains both the quotient and the remainder, the remainder being the size of the divisor (the remainder
   # has necessarily the same degree as the divisor since it's what we couldn't divide from the dividend), so we compute the index
   # where this separation is, and return the quotient and remainder.
   separator = -(len(divisor)-1)
   return out[:separator], out[separator:] # return quotient, remainder.

if __name__ == '__main__':

   print "POLYNOMIAL SYNTHETIC DIVISION"
   N = [1, -12, 0, -42]
   D = [1, -3]
   print "  %s / %s =" % (N,D),
   print " %s remainder %s" % extended_synthetic_division(N, D)

</lang>

Sample output:

POLYNOMIAL SYNTHETIC DIVISION
  [1, -12, 0, -42] / [1, -3] =  [1, -9, -27] remainder [-123]

Racket

Translation of: Python

<lang racket>#lang racket/base (require racket/list)

dividend and divisor are both polynomials, which are here simply lists of coefficients.
Eg
x^2 + 3x + 5 will be represented as (list 1 3 5)

(define (extended-synthetic-division dividend divisor)

 (define out (list->vector dividend)) ; Copy the dividend
 ;; for general polynomial division (when polynomials are non-monic), we need to normalize by
 ;; dividing the coefficient with the divisor's first coefficient
 (define normaliser (car divisor))
 (define divisor-length (length divisor)) ; } we use these often enough
 (define out-length (vector-length out))  ; }
 
 (for ((i (in-range 0 (- out-length divisor-length -1))))
   (vector-set! out i (quotient (vector-ref out i) normaliser))
   (define coef (vector-ref out i))
   (unless (zero? coef) ; useless to multiply if coef is 0
     (for ((i+j (in-range (+ i 1)                ; in synthetic division, we always skip the first
                          (+ i divisor-length))) ; coefficient of the divisior, because it's
           (divisor_j (in-list (cdr divisor))))  ;  only used to normalize the dividend coefficients
       (vector-set! out i+j (+ (vector-ref out i+j) (* coef divisor_j -1))))))
 ;; The resulting out contains both the quotient and the remainder, the remainder being the size of
 ;; the divisor (the remainder has necessarily the same degree as the divisor since it's what we
 ;; couldn't divide from the dividend), so we compute the index where this separation is, and return
 ;; the quotient and remainder.
 ;; return quotient, remainder (conveniently like quotient/remainder)
 (split-at (vector->list out) (- out-length (sub1 divisor-length))))

(module+ main

 (displayln "POLYNOMIAL SYNTHETIC DIVISION")
 (define N '(1 -12 0 -42))
 (define D '(1 -3))
 (define-values (Q R) (extended-synthetic-division N D))
 (printf "~a / ~a = ~a remainder ~a~%" N D Q R))</lang>
Output:
POLYNOMIAL SYNTHETIC DIVISION
(1 -12 0 -42) / (1 -3) = (1 -9 -27) remainder (-123)

REXX

<lang rexx>/* REXX Polynomial Division */ /* extended to support order of divisor >1 */ call set_dd '1 0 0 0 -1' Call set_dr '1 1 1 1' Call set_dd '1 -12 0 -42' Call set_dr '1 -3' q.0=0 Say list_dd '/' list_dr do While dd.0>=dr.0

 q=dd.1/dr.1
 Do j=1 To dr.0
   dd.j=dd.j-q*dr.j
   End
 Call set_q q
 Call shift_dd
 End

say 'Quotient:' mk_list_q() 'Remainder:' mk_list_dd() Exit

set_dd: Parse Arg list list_dd='[' Do i=1 To words(list)

 dd.i=word(list,i)
 list_dd=list_dd||dd.i','
 End

dd.0=i-1 list_dd=left(list_dd,length(list_dd)-1)']' Return

set_dr: Parse Arg list list_dr='[' Do i=1 To words(list)

 dr.i=word(list,i)
 list_dr=list_dr||dr.i','
 End

dr.0=i-1 list_dr=left(list_dr,length(list_dr)-1)']' Return

set_q: z=q.0+1 q.z=arg(1) q.0=z Return

shift_dd: Do i=2 To dd.0

 ia=i-1
 dd.ia=dd.i
 End

dd.0=dd.0-1 Return

mk_list_q: list='['q.1 Do i=2 To q.0

 list=list','q.i
 End

Return list']'

mk_list_dd: list='['dd.1 Do i=2 To dd.0

 list=list','dd.i
 End

Return list']'

</lang>

Output:
[1,-12,0,-42] / [1,-3]
Quotient: [1,-9,-27] Remainder: -123

[1,0,0,0,-2] / [1,1,1,1]
Quotient: [1,-1] Remainder: [0,0,-1]

Tcl

Translation of: Python

This uses a common utility proc range, and a less common one called lincr, which increments elements of lists. The routine for polynomial division is placed in a namespace ensemble, such that it can be conveniently shared with other commands for polynomial arithmetic (eg polynomial multiply).

<lang Tcl># range ?start? end+1

  1. start defaults to 0: [range 5] = {0 1 2 3 4}

proc range {a {b ""}} {

   if {$b eq ""} {
       set b $a
       set a 0
   }
   for {set r {}} {$a<$b} {incr a} {
       lappend r $a
   }
   return $r

}

  1. lincr list idx ?...? increment
  2. By analogy with [lset] and [incr]:
  3. Adds incr to the item at [lindex list idx ?...?]. incr may be a float.

proc lincr {_ls args} {

   upvar 1 $_ls ls
   set incr [lindex $args end]
   set idxs [lrange $args 0 end-1]
   lset ls {*}$idxs [expr {$incr + [lindex $ls {*}$idxs]}]

}

namespace eval polynomial {

   # polynomial division, returns [list $dividend $remainder]
   proc divide {top btm} {
       set out $top
       set norm [lindex $btm 0]
       foreach i [range [expr {[llength $top] - [llength $btm] + 1}]] {
           lset out $i [set coef [expr {[lindex $out $i] * 1.0 / $norm}]]
           if {$coef != 0} {
               foreach j [range 1 [llength $btm]] {
                   lincr out [expr {$i+$j}] [expr {-[lindex $btm $j] * $coef}]
               }
           }
       }
       set terms [expr {[llength $btm]-1}]
       list [lrange $out 0 end-$terms] [lrange $out end-[incr terms -1] end]
   }
   namespace export *
   namespace ensemble create

}

proc test {} {

   set top {1 -12 0 -42}
   set btm {1 -3}
   set div [polynomial divide $top $btm]
   puts "$top / $btm = $div"

} test</lang>

Output:
1 -12 0 -42 / 1 -3 = {1.0 -9.0 -27.0} -123.0

zkl

Translation of: Python

<lang zkl>fcn extended_synthetic_division(dividend, divisor){

  1. Fast polynomial division by using Extended Synthetic Division. Also works with non-monic polynomials.
  2. dividend and divisor are both polynomials, which are here simply lists of coefficients. Eg: x^2 + 3x + 5 will be represented as [1, 3, 5]
  out,normalizer:=dividend.copy(), divisor[0];
  foreach i in (dividend.len() - (divisor.len() - 1)){
     out[i] /= normalizer; # for general polynomial division (when polynomials are non-monic),
                           # we need to normalize by dividing the coefficient with the divisor's first coefficient
     coef := out[i];
     if(coef != 0){  # useless to multiply if coef is 0

foreach j in ([1..divisor.len() - 1]){ # in synthetic division, we always skip the first coefficient of the divisior, out[i + j] += -divisor[j] * coef; # because it's only used to normalize the dividend coefficients }

     }
  }
   # out contains the quotient and remainder, the remainder being the size of the divisor (the remainder
   # has necessarily the same degree as the divisor since it's what we couldn't divide from the dividend), so we compute the index
   # where this separation is, and return the quotient and remainder.
  separator := -(divisor.len() - 1);
  return(out[0,separator], out[separator,*]) # return quotient, remainder.

}</lang> <lang zkl>println("POLYNOMIAL SYNTHETIC DIVISION"); N,D := T(1, -12, 0, -42), T(1, -3); print(" %s / %s =".fmt(N,D)); println(" %s remainder %s".fmt(extended_synthetic_division(N,D).xplode()));</lang>

Output:
POLYNOMIAL SYNTHETIC DIVISION
  L(1,-12,0,-42) / L(1,-3) = L(1,-9,-27) remainder L(-123)