Polynomial long division: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Wren}}: Added a translation of Kotlin version 2.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 97:
{{trans|Python}}
<
L !poly.empty & poly.last == 0
poly.pop()
Line 126:
print(‘ #. / #. =’.format(n, D), end' ‘ ’)
V (q, r) = poly_div(&n, &D)
print(‘ #. remainder #.’.format(q, r))</
{{out}}
Line 136:
=={{header|Ada}}==
long_division.adb:
<
procedure Long_Division is
Line 245:
Put ("Q: "); Output (Test_Q);
Put ("R: "); Output (Test_R);
end Long_Division;</
output:
Line 256:
=={{header|APL}}==
<
{
q r d←⍵
Line 264:
} ⍬ ⍺ ⍵
}
</syntaxhighlight>
{{out}}
<pre> N←¯42 0 ¯12 1
Line 274:
=={{header|BBC BASIC}}==
<
DIM D%(3) : D%() = -3, 1, 0, 0
DIM q%(3), r%(3)
Line 317:
IF n%<0 THEN = " - " + STR$(-n%)
IF n%=1 THEN = " + "
= " + " + STR$(n%)</
'''Output:'''
<pre>
Line 328:
{{libheader|GNU Scientific Library}}
<
#include <stdlib.h>
#include <stdarg.h>
Line 434:
return r;
}</
<
{
int i;
Line 458:
return 0;
}</
===Another version===
Without outside libs, for clarity. Note that polys are stored and show with zero-degree term first:<
#include <stdlib.h>
#include <stdarg.h>
Line 564:
return 0;
}</
=={{header|C sharp|C#}}==
{{trans|Java}}
<
namespace PolynomialLongDivision {
Line 690:
}
}
}</
{{out}}
<pre>Numerator : x^3 - 12.0x^2 - 42.0
Line 699:
=={{header|C++}}==
<
#include <iostream>
#include <iterator>
Line 798:
}
</syntaxhighlight>
=={{header|Clojure}}==
Line 806:
Since this algorithm is much more efficient when the input is in [https://en.wikipedia.org/wiki/Monomial_order#Graded_reverse_lexicographic_order graded reverse lexicographic (grevlex) order] a comparator is included to be used with Clojure's sorted-map—<code>(into (sorted-map-by grevlex) ...)</code>—as well as necessary functions to compute polynomial multiplication, monomial complements, and S-polynomials.
<
(let [grade1 (reduce +' term1)
grade2 (reduce +' term2)
Line 900:
(is (= (divide {[1 1] 2, [1 0] 10, [0 1] 3, [0 0] 15}
{[1 0] 2, [0 0] 3})
'({[0 1] 1, [0 0] 5} {}))))</
=={{header|Common Lisp}}==
Line 906:
Polynomials are represented as lists of degree/coefficient pairs ordered by degree (highest degree first), and pairs with zero coefficients can be omitted. <code>Multiply</code> and <code>divide</code> perform long multiplication and long division, respectively. <code>multiply</code> returns one value, the product, and <code>divide</code> returns two, the quotient and the remainder.
<
(do ((sum '())) ((and (endp p1) (endp p2)) (nreverse sum))
(let ((pd1 (if (endp p1) -1 (caar p1)))
Line 946:
(if (endp quotient) (return (values sum remainder))
(setf dividend remainder
sum (add quotient sum)))))))</
The [[wp:Polynomial_long_division#Example|wikipedia example]]:
<
'((1 . 1) (0 . -3))) ; x - 3
((2 . 1) (1 . -9) (0 . -27)) ; x^2 - 9x - 27
((0 . -123)) ; -123</
=={{header|D}}==
<
Tuple!(double[], double[]) polyDiv(in double[] inN, in double[] inD)
Line 997:
immutable D = [-3.0, 1.0, 0.0, 0.0];
writefln("%s / %s = %s remainder %s", N, D, polyDiv(N, D)[]);
}</
{{out}}
<pre>[-42, 0, -12, 1] / [-3, 1, 0, 0] = [-27, -9, 1] remainder [-123]</pre>
Line 1,003:
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Polynomial_long_division;
Line 1,246:
FreeMem(Solution, sizeof(TPolySolution));
Readln;
end.</
=={{header|E}}==
Line 1,349:
}</pre>
<
def d := makePolynomial([-3, 1])
println("Numerator: ", n)
Line 1,355:
def [q, r] := n.quotRem(d, stdout)
println("Quotient: ", q)
println("Remainder: ", r)</
Output:
Line 1,375:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def division(_, []), do: raise ArgumentError, "denominator is zero"
def division(_, [0]), do: raise ArgumentError, "denominator is zero"
Line 1,405:
{q, r} = Polynomial.division(f, g)
IO.puts "#{inspect f} / #{inspect g} => #{inspect q} remainder #{inspect r}"
end)</
{{out}}
Line 1,417:
=={{header|F_Sharp|F#}}==
{{trans|Ocaml}}
<
let rec shift n l = if n <= 0 then l else shift (n-1) (l @ [0.0])
let rec pad n l = if n <= 0 then l else pad (n-1) (0.0 :: l)
Line 1,457:
" (%s) div (%s)\ngives\nquotient:\t(%s)\nremainder:\t(%s)\n"
(str_poly f) (str_poly g) (str_poly q) (str_poly r)
</syntaxhighlight>
{{out}}
<pre>
Line 1,466:
</pre>
=={{header|Factor}}==
<
{ -42 0 -12 1 } { -3 1 } p/mod ptrim [ . ] bi@</
{{out}}
<pre>
Line 1,478:
{{works with|Fortran|95 and later}}
<
implicit none
Line 1,557:
end subroutine poly_print
end module Polynom</
<
use Polynom
implicit none
Line 1,576:
deallocate(q, r)
end program PolyDivTest</
=={{Header|FreeBASIC}}==
<
type polyterm
Line 1,678:
poly_print Q() 'quotient
poly_print R() 'remainder</
{{out}}
<pre>x^2 - 9x - 27
Line 1,685:
=={{header|GAP}}==
GAP has built-in functions for computations with polynomials.
<
p := x^11 + 3*x^8 + 7*x^2 + 3;
q := x^7 + 5*x^3 + 1;
QuotientRemainder(p, q);
# [ x^4+3*x-5, -16*x^4+25*x^3+7*x^2-3*x+8 ]</
=={{header|Go}}==
By the convention and pseudocode given in the task:
<
import "fmt"
Line 1,738:
}
return q, nn, true
}</
Output:
<pre>
Line 1,751:
Translated from the OCaml code elsewhere on the page.
{{works with|GHC|6.10}}
<
shift n l = l ++ replicate n 0
Line 1,772:
ks = map (* k) $ shift ddif s
q' = zipWith' (+) q $ shift ddif [k]
f' = norm $ tail $ zipWith' (-) f ks</
And this is the also-translated pretty printing function.
<
where term v 0 = show v
term 1 1 = "x"
Line 1,786:
terms [] = []
terms (0:t) = terms t
terms (h:t) = (term h (length t)) : (terms t)</
=={{header|J}}==
Line 1,792:
From http://www.jsoftware.com/jwiki/Phrases/Polynomials
<
Wikipedia example:
<
This produces the result:
┌────────┬────┐
Line 1,809:
<br><br>
To test and validate the results, polynomial multiplication and addition are also implemented.
<syntaxhighlight lang="java">
import java.math.BigInteger;
import java.util.ArrayList;
Line 2,353:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,371:
=={{header|Julia}}==
This task is straightforward with the help of Julia's [https://github.com/Keno/Polynomials.jl Polynomials] package.
<syntaxhighlight lang="julia">
using Polynomials
Line 2,380:
println(p, " divided by ", q, " is ", d, " with remainder ", r, ".")
</syntaxhighlight>
{{out}}
Line 2,389:
=={{header|Kotlin}}==
===Version 1===
<
typealias IAE = IllegalArgumentException
Line 2,478:
print("Remainder : ")
polyShow(r)
}</
{{out}}
Line 2,493:
===Version 2===
More succinct version that provides an easy-to-use API.
<
operator fun div(divisor: Polynom): Pair<Polynom, Polynom> {
Line 2,531:
print("$num / $den = $quot remainder $rem")
}</
{{out}}
Line 2,540:
=={{header|Maple}}==
As Maple is a symbolic computation system, polynomial arithmetic is, of course, provided by the language runtime. The remainder (rem) and quotient (quo) operations each allow for the other to be computed simultaneously by passing an unassigned name as an optional fourth argument. Since rem and quo deal also with multivariate polynomials, the indeterminate is passed as the third argument.
<syntaxhighlight lang="maple">
> p := randpoly( x ); # pick a random polynomial in x
5 4 3 2
Line 2,560:
> expand( (x^2+2)*q + r - p ); # check
0
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
output:
<pre>{-27 - 9 x + x^2, -123}</pre>
=={{header|Nim}}==
<
type
Line 2,655:
echo "D = ", D
echo "q = ", q
echo "r = ", r</
{{out}}
Line 2,666:
First define some utility operations on polynomials as lists (with highest power coefficient first).
<
let rec pad n l = if n <= 0 then l else pad (pred n) (0.0 :: l)
let rec norm = function | 0.0 :: tl -> norm tl | x -> x
Line 2,673:
let zip op p q =
let d = (List.length p) - (List.length q) in
List.map2 op (pad (-d) p) (pad d q)</
Then the main polynomial division function
<
let rec aux f s q =
let ddif = (deg f) - (deg s) in
Line 2,684:
and f' = norm (List.tl (zip (-.) f ks)) in
aux f' s q' in
aux (norm f) (norm g) []</
For output we need a pretty-printing function
<
let term v p = match (v, p) with
| ( _, 0) -> string_of_float v
Line 2,697:
| h :: t ->
if h = 0.0 then (terms t) else (term h (List.length t)) :: (terms t) in
String.concat " + " (terms l)</
and then the example
<
let f = [1.0; -4.0; 6.0; 5.0; 3.0] and g = [1.0; 2.0; 1.0] in
let q, r = polydiv f g in
Printf.printf
" (%s) div (%s)\ngives\nquotient:\t(%s)\nremainder:\t(%s)\n"
(str_poly f) (str_poly g) (str_poly q) (str_poly r)</
gives the output:
<pre>
Line 2,716:
Octave has already facilities to divide two polynomials (<code>deconv(n,d)</code>); and the reason to adopt the convention of keeping the highest power coefficient first, is to make the code compatible with builtin functions: we can use <tt>polyout</tt> to output the result.
<
gd = length(d);
pv = zeros(1, length(n));
Line 2,752:
[q, r] = poly_long_div([1,3], [1,-12,0,-42]);
polyout(q, 'x');
polyout(r, 'x');</
=={{header|PARI/GP}}==
This uses the built-in PARI polynomials.
<
my(rem=a%b);
[(a - rem)/b, rem]
};
poldiv(x^9+1, x^3+x-3)</
Alternately, use the built-in function <code>divrem</code>:
<
=={{header|Perl}}==
Line 2,768:
{{trans|Octave}}
<
use List::Util qw(min);
Line 2,789:
return ( [0], $rn );
}
}</
<
{
my @c = @_;
Line 2,800:
}
print "\n";
}</
<
($q, $r) = poly_long_div([1, -12, 0, -42], [1, -3]);
Line 2,819:
($q, $r) = poly_long_div([1,-4,6,5,3], [1,2,1]);
poly_print(@$q);
poly_print(@$r);</
=={{header|Phix}}==
<!--<
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Polynomial_long_division.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 2,894:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">num</span><span style="color: #0000FF;">,</span><span style="color: #000000;">den</span><span style="color: #0000FF;">,</span><span style="color: #000000;">quo</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rem</span><span style="color: #0000FF;">},</span><span style="color: #000000;">poly</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 2,907:
=={{header|PicoLisp}}==
<
(let I NIL
(for (N . C) P
Line 2,924:
(set (nth Q (inc Diff)) F)
(setq N (mapcar '((N E) (- N (* E F))) N E)) ) ) )
(list Q N) ) ) )</
Output:
<pre>: (divPoly (-42 0 -12 1) (-3 1 0 0))
Line 2,931:
=={{header|Python}}==
{{works with|Python 2.x}}
<
from itertools import izip
Line 2,963:
D = [-3, 1, 0, 0]
print " %s / %s =" % (N,D),
print " %s remainder %s" % poly_div(N, D)</
Sample output:
Line 2,971:
=={{header|R}}==
{{trans|Octave}}
<
gd <- length(d)
pv <- vector("numeric", length(n))
Line 3,004:
r <- polylongdiv(c(1,-12,0,-42), c(1,-3))
print.polynomial(r$q)
print.polynomial(r$r)</
=={{header|Racket}}==
<
#lang racket
(define (deg p)
Line 3,043:
'#(-27 -9 1)
'#(-123 0)
</syntaxhighlight>
=={{header|Raku}}==
Line 3,049:
{{Works with|rakudo|2018.10}}
{{trans|Perl}} for the core algorithm; original code for LaTeX pretty-printing.
<syntaxhighlight lang="raku"
return [0], |@n if +@n < +@d;
Line 3,072:
printf Q"%s , & %s \\\\\n", poly_long_div( @a, @b ).map: { poly_print($_) };
}
say '\end{array}</math>';</
Output:
Line 3,084:
=={{header|REXX}}==
<
z='1 -12 0 -42' /* Numerator */
n='1 -3' /* Denominator */
Line 3,127:
d=d-1
End
Return strip(space(res,0),'L','+')</
{{out}}
<pre>(x**3-12*x**2-42)/(x-3)=(x**2-9*x-27)
Line 3,134:
=={{header|Ruby}}==
Implementing the algorithm given in the task description:
<
dd = degree(denominator)
raise ArgumentError, "denominator is zero" if dd < 0
Line 3,179:
q, r = polynomial_long_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
# => [-42, 0, -12, 1] / [-3, 1, 1, 0] => [-13, 1, 0, 0] remainder [-81, 16, 0, 0]</
Implementing the algorithms on the [[wp:Polynomial long division|wikipedia page]] -- uglier code but nicer user interface
<
if g.length == 0 or (g.length == 1 and g[0] == 0)
raise ArgumentError, "denominator is zero"
Line 3,249:
q, r = polynomial_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
# => [1, -12, 0, -42] / [1, 1, -3] => [1, -13] remainder [16, -81]</
Best of both worlds: {{trans|Tcl}}
<
if g.length == 0 or (g.length == 1 and g[0] == 0)
raise ArgumentError, "denominator is zero"
Line 3,280:
q, r = polynomial_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
# => [1, -12, 0, -42] / [1, 1, -3] => [1.0, -13.0] remainder [16.0, -81.0]</
=={{header|Sidef}}==
{{trans|Perl}}
<
var n = rn.map{_}
Line 3,303:
return([0], rn)
}</
Example:
<
var l = c.len
c.each_kv {|i, n|
Line 3,328:
poly_print(r)
print "\n"
}</
{{out}}
Line 3,347:
=={{header|Slate}}==
<
p@(Polynomial traits) new &capacity: n
Line 3,408:
{q. n}]
ifFalse: [{p newFrom: #(0). p copy}]
].</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
|coeffs|
Polynomial class >> new [ ^ super basicNew init ]
Line 3,480:
]
displayNl [ self display. Character nl display ]
].</
<
res := OrderedCollection new.
Line 3,492:
res do: [ :o |
(o at: 1) display. ' with rest: ' display. (o at: 2) displayNl
]</
=={{header|SPAD}}==
Line 3,498:
{{works with|OpenAxiom}}
{{works with|Axiom}}
<
2
(1) [quotient = x - 9x - 27,remainder = - 123]
Type: Record(quotient: Polynomial(Integer),remainder: Polynomial(Integer))</
Domain:[http://fricas.github.io/api/PolynomialCategory.html#l-polynomial-category-monic-divide]
Line 3,511:
{{trans|Kotlin}}
<
static func / (lhs: Self, rhs: Self) -> Self
}
Line 3,640:
polyPrint(sol.quotient)
print("Remainder: ", terminator: "")
polyPrint(sol.remainder)</
{{out}}
Line 3,653:
{{works with|Tcl|8.5 and later}}
<
# Result is a list of two polynomials, q and r, where n = qd + r
# and the degree of r is less than the degree of b.
Line 3,692:
lassign [poldiv {-42. 0. -12. 1.} {-3. 1. 0. 0.}] Q R
puts [list Q = $Q]
puts [list R = $R]</
=={{header|Ursala}}==
Line 3,700:
of the algorithm in terms of list operations (fold, zip, map, distribute, etc.) instead
of array indexing, hence not unnecessarily verbose.
<
#import flo
Line 3,708:
@lrrPX ==!| zipp0.; @x not zeroid+ ==@h->hr ~&t,
(^lryPX/~&lrrl2C minus^*p/~&rrr times*lrlPD)^/div@bzPrrPlXO ~&,
@r ^|\~& ~&i&& :/0.)</
test program:
<
example = polydiv(<-42.,0.,-12.,1.>,<-3.,1.,0.,0.>)</
output:
<pre>(
Line 3,719:
=={{header|VBA}}==
{{trans|Phix}}<
Function degree(p As Variant)
For i = UBound(p) To 1 Step -1
Line 3,814:
Debug.Print polyn(Array(num, denom, quot, rmdr))
Next i
End Sub</
<pre> x3 - 12x2 - 42 / x - 3 = x2 - 9x - 27 rem -123
x - 3 / x3 - 12x2 - 42 = 0 rem x - 3
Line 3,827:
===Version 1===
{{libheader|Wren-dynamic}}
<
var Solution = Tuple.create("Solution", ["quotient", "remainder"])
Line 3,914:
polyShow.call(sol.quotient)
System.write("Remainder : ")
polyShow.call(sol.remainder)</
{{out}}
Line 3,926:
===Version 2===
<
construct new(factors) {
_factors = factors.toList
Line 3,970:
var quot = res[0]
var rem = res[1]
System.print("%(num) / %(den) = %(quot) remainder %(rem)")</
{{out}}
Line 3,978:
=={{header|zkl}}==
<
_assert_(degree(b)>=0,"degree(%s) < 0".fmt(b));
q:=List.createLong(a.len(),0.0);
Line 3,999:
if(str[0]=="+") str[1,*]; // leave leading space
else String("-",str[2,*]);
}</
<
println("Quotient = ",polyString(q));
println("Remainder = ",polyString(r));</
{{out}}
<pre>
|