Polynomial synthetic division: Difference between revisions

m (→‎{{header|Phix}}: syntax coloured, made p2js compatible)
 
(2 intermediate revisions by 2 users not shown)
Line 9:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F extended_synthetic_division(dividend, divisor)
‘Fast polynomial division by using Extended Synthetic Division. Also works with non-monic polynomials.’
V out = copy(dividend)
Line 27:
print(‘ #. / #. =’.format(n, D), end' ‘ ’)
V (a, b) = extended_synthetic_division(n, D)
print(‘#. remainder #.’.format(a, b))</langsyntaxhighlight>
 
{{out}}
Line 37:
=={{header|C++}}==
{{trans|Java}}
<langsyntaxhighlight lang="cpp">/*
* C++ Polynomial Sythetic Division
* GNU Compile example for filename <synthdiv.cpp>
Line 163:
 
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 215:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
Line 222:
{{Trans|Go}}
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/DelphiBigNumbers Velthuis.BigRationals] library.<br>
<syntaxhighlight lang="delphi">
<lang Delphi>
program Polynomial_synthetic_division;
 
Line 300:
writeln(result[0].ToString, ' remainder ', result[1].ToString);
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>[1 -12 0 -42 ] / [1 -3 ] = [1 -9 -27 ] remainder [-123 ]</pre>
Line 307:
=={{header|Go}}==
{{trans|Python}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 341:
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 348:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
 
normalized :: (Eq a, Num a) => [a] -> [a]
Line 366:
k = length p1 - length as
a:as = normalized p2
ker = negate <$> (as ++ repeat 0)</langsyntaxhighlight>
 
<pre>*Main> shortDiv [1,-12,0,-42] [1,1,-3]
Line 376:
For monic divisors it is possible to perform purely integral computations (without Fractional constraint):
 
<langsyntaxhighlight lang="haskell">isMonic :: (Eq a, Num a) => [a] -> Bool
isMonic = ([1] ==) . take 1 . normalized
 
Line 390:
k = length p1 - length as
_:as = normalized p2
ker = negate <$> as ++ repeat 0</langsyntaxhighlight>
 
<pre>shortDivMonic [1,-12,0,-42] [1,1,-3 :: Int]
Line 399:
Solving this the easy way:
 
<langsyntaxhighlight Jlang="j"> psd=: [:(}. ;{.) ([ (] -/@,:&}. (* {:)) ] , %&{.~)^:(>:@-~&#)~</langsyntaxhighlight>
 
Task example:
 
<langsyntaxhighlight Jlang="j"> (1, (-12), 0, -42) psd (1, -3)
┌────────┬────┐
│1 _9 _27│_123│
└────────┴────┘
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
{{trans|Python}}
<langsyntaxhighlight lang="java">import java.util.Arrays;
 
public class Test {
Line 446:
};
}
}</langsyntaxhighlight>
 
<pre>[1, -12, 0, -42] / [1, -3] = [[1, -9, -27], [-123]]</pre>
 
=={{header|jq}}==
{{works with|jq}}
 
'''Works with gojq, the Go implementation of jq'''
 
'''Works with jaq, the Rust implementation of jq'''
 
In this entry, the polynomial of degree n, SIGMA c[i] * x^(n-i), is represented by
the JSON array c.
<syntaxhighlight lang="jq">
# Solution: {"quotient", "remainder"}
def extendedSyntheticDivision($dividend; $divisor):
{ out: $dividend,
normalizer: $divisor[0],
separator: (($dividend|length) - ($divisor|length) + 1) }
| reduce range(0; .separator) as $i (.;
.out[$i] = ((.out[$i] / .normalizer)|trunc)
| .out[$i] as $coef
| if $coef != 0
then reduce range(1; $divisor|length) as $j (.;
.out[$i + $j] -= $divisor[$j] * $coef )
else .
end )
| {quotient: .out[0:.separator], remainder: .out[.separator:]} ;
 
def task($n; $d):
def r: if length==1 then first else . end;
extendedSyntheticDivision($n; $d)
| "\($n) / \($d) = \(.quotient), remainder \(.remainder|r)" ;
 
task([1, -12, 0, -42]; [1, -3]),
task([1, 0, 0, 0, -2];[1, 1, 1, 1])
</syntaxhighlight>
{{output}}
<pre>
[1,-12,0,-42] / [1,-3] = [1,-9,-27], remainder -123
[1,0,0,0,-2] / [1,1,1,1] = [1,-1], remainder [0,0,-1]
</langpre>
 
=={{header|Julia}}==
{{trans|Perl}}
<langsyntaxhighlight lang="julia">function divrem(dividend::Vector, divisor::Vector)
result = copy(dividend)
quotientlen = length(divisor) - 1
Line 472 ⟶ 511:
println("[$n] / [$d] = [$quotient] with remainder [$remainder]")
end
</langsyntaxhighlight>{{out}}
<pre>
[[1, -12, 0, -42]] / [[1, -3]] = [[1, -9, -27]] with remainder [[-123]]
Line 480 ⟶ 519:
=={{header|Kotlin}}==
{{trans|Python}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun extendedSyntheticDivision(dividend: IntArray, divisor: IntArray): Pair<IntArray, IntArray> {
Line 509 ⟶ 548:
print("${n2.contentToString()} / ${d2.contentToString()} = ")
println("${q2.contentToString()}, remainder ${r2.contentToString()}")
}</langsyntaxhighlight>
 
{{out}}
Line 520 ⟶ 559:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">MakePolynomial[l_List, x_] := FromCoefficientRules[Thread[List /@ Range[Length[l] - 1, 0, -1] -> l], {x}]
num = MakePolynomial[{1, -12, 0, -42}, x];
den = MakePolynomial[{1, -3}, x];
PolynomialQuotient[num, den, x]
PolynomialRemainder[num, den, x]</langsyntaxhighlight>
{{out}}
<pre>-27 - 9 x + x^2
Line 531 ⟶ 570:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import strformat
 
type Polynomial = seq[int]
Line 558 ⟶ 597:
let d2 = @[1, 1, 1, 1]
let (q2, r2) = extendedSyntheticDivision(n2, d2)
echo &"{n2} / {d2} = {q2}, remainder {r2}"</langsyntaxhighlight>
 
{{out}}
Line 567 ⟶ 606:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">sub synthetic_division {
my($numerator,$denominator) = @_;
my @result = @$numerator;
Line 588 ⟶ 627:
 
print poly_divide([1, -12, 0, -42], [1, -3]);
print poly_divide([1, 0, 0, 0, -2], [1, 1, 1, 1]);</langsyntaxhighlight>
{{out}}
<pre>[1 -12 0 -42] / [1 -3] = [1 -9 -27], remainder [-123]
Line 595 ⟶ 634:
=={{header|Phix}}==
{{trans|Kotlin}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">extendedSyntheticDivision</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">dividend</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">divisor</span><span style="color: #0000FF;">)</span>
Line 625 ⟶ 664:
<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: #008000;">"%v / %v = %v, remainder %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 639 ⟶ 678:
{{works with|Python 2.7}}
{{works with|Python 3.x}}
<langsyntaxhighlight lang="python">from __future__ import print_function
from __future__ import division
 
Line 671 ⟶ 710:
D = [1, -3]
print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
</syntaxhighlight>
</lang>
 
Sample output:
Line 682 ⟶ 721:
{{trans|Python}}
 
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/list)
;; dividend and divisor are both polynomials, which are here simply lists of coefficients.
Line 715 ⟶ 754:
(define D '(1 -3))
(define-values (Q R) (extended-synthetic-division N D))
(printf "~a / ~a = ~a remainder ~a~%" N D Q R))</langsyntaxhighlight>
 
{{out}}
Line 727 ⟶ 766:
{{works with|Rakudo|2018.09}}
 
<syntaxhighlight lang="raku" perl6line>sub synthetic-division ( @numerator, @denominator ) {
my @result = @numerator;
my $end = @denominator.end;
Line 747 ⟶ 786:
my %result = synthetic-division( @n, @d );
say "[{@n}] / [{@d}] = [%result<quotient>], remainder [%result<remainder>]";
}</langsyntaxhighlight>
{{out}}
<pre>[1 -12 0 -42] / [1 -3] = [1 -9 -27], remainder [-123]
Line 754 ⟶ 793:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/* REXX Polynomial Division */
/* extended to support order of divisor >1 */
call set_dd '1 0 0 0 -1'
Line 823 ⟶ 862:
Return list']'
 
</syntaxhighlight>
</lang>
{{out}}
<pre>[1,-12,0,-42] / [1,-3]
Line 834 ⟶ 873:
===Java Interoperability===
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/59vpjcQ/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/uUk8yRPnQdGdS1aAUFjhmA Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">import java.util
 
object PolynomialSyntheticDivision extends App {
Line 862 ⟶ 901:
}%s")
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">func extended_synthetic_division(dividend, divisor) {
var end = divisor.end
var out = dividend.clone
Line 889 ⟶ 928:
var (n, d) = ([1, -12, 0, -42], [1, -3])
print(" %s / %s =" % (n, d))
print(" %s remainder %s\n" % extended_synthetic_division(n, d))</langsyntaxhighlight>
{{out}}
[1, -12, 0, -42] / [1, -3] = [1, -9, -27] remainder [-123]
Line 898 ⟶ 937:
This uses a common utility proc <tt>range</tt>, and a less common one called <tt>lincr</tt>, 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 <tt>polynomial multiply</tt>).
 
<langsyntaxhighlight Tcllang="tcl"># range ?start? end+1
# start defaults to 0: [range 5] = {0 1 2 3 4}
proc range {a {b ""}} {
Line 947 ⟶ 986:
puts "$top / $btm = $div"
}
test</langsyntaxhighlight>
 
{{out}}
Line 955 ⟶ 994:
{{trans|Kotlin}}
{{libheader|Wren-dynamic}}
<langsyntaxhighlight ecmascriptlang="wren">import "./dynamic" for Tuple
 
var Solution = Tuple.create("Solution", ["quotient", "remainder"])
Line 984 ⟶ 1,023:
var sol2 = extendedSyntheticDivision.call(n2, d2)
System.write("%(n2) / %(d2) = ")
System.print("%(sol2.quotient), remainder %(sol2.remainder)")</langsyntaxhighlight>
 
{{out}}
Line 996 ⟶ 1,035:
=={{header|zkl}}==
{{trans|Python}}
<langsyntaxhighlight lang="zkl">fcn 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]
Line 1,016 ⟶ 1,055:
separator := -(divisor.len() - 1);
return(out[0,separator], out[separator,*]) # return quotient, remainder.
}</langsyntaxhighlight>
<langsyntaxhighlight 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()));</langsyntaxhighlight>
{{out}}
<pre>
2,487

edits