Polynomial derivative: Difference between revisions
Content added Content deleted
(→{{header|Factor}}: update for new test cases) |
(Added Algol 68) |
||
Line 1: | Line 1: | ||
{{draft task}} |
{{draft task}} |
||
Given a polynomial, represented by an ordered list of its coefficients by increasing degree (e.g. [-1, 6, 5] represents 5x<sup>2</sup>+6x-1), calculate the polynomial representing the derivative. For example, the derivative of the aforementioned polynomial is 10x+6, represented by [6, 10]. Test cases: 5, -3x+4, 5x<sup>2</sup>+6x-1, x<sup>3</sup>-2x<sup>2</sup>+3x-4, -x<sup>4</sup>-x<sup>3</sup>+x+1 |
Given a polynomial, represented by an ordered list of its coefficients by increasing degree (e.g. [-1, 6, 5] represents 5x<sup>2</sup>+6x-1), calculate the polynomial representing the derivative. For example, the derivative of the aforementioned polynomial is 10x+6, represented by [6, 10]. Test cases: 5, -3x+4, 5x<sup>2</sup>+6x-1, x<sup>3</sup>-2x<sup>2</sup>+3x-4, -x<sup>4</sup>-x<sup>3</sup>+x+1 |
||
=={{header|ALGOL 68}}== |
|||
<lang algol68>BEGIN # find the derivatives of polynominals, given their coefficients # |
|||
# returns the derivative polynominal of the polynominal defined by # |
|||
# the array of coeficients, where the coefficients are in # |
|||
# order of ioncreasing power of x # |
|||
OP DERIVATIVE = ( []INT p )[]INT: |
|||
BEGIN |
|||
[ 1 : UPB p - 1 ]INT result; |
|||
FOR i FROM 2 TO UPB p DO |
|||
result[ i - 1 ] := ( i - 1 ) * p[ i ] |
|||
OD; |
|||
result |
|||
END # DERIVATIVE # ; |
|||
# prints the polynomial defined by the coefficients in p # |
|||
OP SHOW = ( []INT p )VOID: |
|||
BEGIN |
|||
BOOL first := TRUE; |
|||
FOR i FROM UPB p BY -1 TO LWB p DO |
|||
IF p[ i ] /= 0 THEN |
|||
IF first THEN |
|||
IF p[ i ] < 0 THEN print( ( "-" ) ) FI |
|||
ELSE |
|||
IF p[ i ] < 0 |
|||
THEN print( ( " - " ) ) |
|||
ELSE print( ( " + " ) ) |
|||
FI |
|||
FI; |
|||
first := FALSE; |
|||
IF i = LWB p |
|||
THEN print( ( whole( ABS p[ i ], 0 ) ) ) |
|||
ELSE |
|||
IF ABS p[ i ] > 1 THEN print( ( whole( ABS p[ i ], 0 ) ) ) FI; |
|||
print( ( "x" ) ); |
|||
IF i > LWB p + 1 THEN print( ( "^", whole( i - 1, 0 ) ) ) FI |
|||
FI |
|||
FI |
|||
OD; |
|||
IF first THEN |
|||
# all coefficients were 0 # |
|||
print( ( "0" ) ) |
|||
FI |
|||
END # SHOW # ; |
|||
# task test cases # |
|||
PROC test = ( []INT p )VOID: BEGIN SHOW p; print( ( " -> " ) ); SHOW DERIVATIVE p; print( ( newline ) ) END; |
|||
test( ( 5 ) ); test( ( 4, -3 ) ); test( ( -1, 6, 5 ) ); test( ( -4, 3, -2, 1 ) ); test( ( 1, 1, 0, -1, -1 ) ) |
|||
END</lang> |
|||
{{out}} |
|||
<pre> |
|||
5 -> 0 |
|||
-3x + 4 -> -3 |
|||
5x^2 + 6x - 1 -> 10x + 6 |
|||
x^3 - 2x^2 + 3x - 4 -> 3x^2 - 4x + 3 |
|||
-x^4 - x^3 + x + 1 -> -4x^3 - 3x^2 + 1 |
|||
</pre> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |