Exponentiation order: Difference between revisions
(Exponentiation order in various BASIC dialents (QBasic, BASIC256, Run BASIC, True BASIC and Yabasic)) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 34: | Line 34: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
< |
<syntaxhighlight lang="11l">print(5 ^ 3 ^ 2) |
||
print((5 ^ 3) ^ 2) |
print((5 ^ 3) ^ 2) |
||
print(5 ^ (3 ^ 2))</ |
print(5 ^ (3 ^ 2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 47: | Line 47: | ||
There is no power operator in Action! Power function for REAL type is used. But the precision is insufficient. |
There is no power operator in Action! Power function for REAL type is used. But the precision is insufficient. |
||
{{libheader|Action! Tool Kit}} |
{{libheader|Action! Tool Kit}} |
||
< |
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit |
||
PROC Main() |
PROC Main() |
||
Line 70: | Line 70: | ||
Print("5^(3^2)=") |
Print("5^(3^2)=") |
||
PrintRE(tmp2) |
PrintRE(tmp2) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Exponentiation_order.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Exponentiation_order.png Screenshot from Atari 8-bit computer] |
||
Line 84: | Line 84: | ||
5**3**2 is not a valid Ada expression. Parenthesis are mandatory. |
5**3**2 is not a valid Ada expression. Parenthesis are mandatory. |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
procedure Exponentation_Order is |
procedure Exponentation_Order is |
||
Line 92: | Line 92: | ||
Put_Line ("(5**3)**2 : " & Natural'((5**3)**2)'Image); |
Put_Line ("(5**3)**2 : " & Natural'((5**3)**2)'Image); |
||
Put_Line ("5**(3**2) : " & Natural'(5**(3**2))'Image); |
Put_Line ("5**(3**2) : " & Natural'(5**(3**2))'Image); |
||
end Exponentation_Order;</ |
end Exponentation_Order;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 100: | Line 100: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Algol 68 provides various alternative symbols for the exponentiation operator generally, "**", "^" and "UP" can be used. |
Algol 68 provides various alternative symbols for the exponentiation operator generally, "**", "^" and "UP" can be used. |
||
< |
<syntaxhighlight lang="algol68">print( ( "5**3**2: ", 5**3**2, newline ) ); |
||
print( ( "(5**3)**2: ", (5**3)**2, newline ) ); |
print( ( "(5**3)**2: ", (5**3)**2, newline ) ); |
||
print( ( "5**(3**2): ", 5**(3**2), newline ) )</ |
print( ( "5**(3**2): ", 5**(3**2), newline ) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 112: | Line 112: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
The Algol W exponentiation operator always produces a real result and requires an integer right operand, hence the round functions in the following. |
The Algol W exponentiation operator always produces a real result and requires an integer right operand, hence the round functions in the following. |
||
< |
<syntaxhighlight lang="algolw">begin |
||
write( "5**3**2: ", round( 5 ** 3 ** 2 ) ); |
write( "5**3**2: ", round( 5 ** 3 ** 2 ) ); |
||
write( "(5**3)**2: ", round( ( 5 ** 3 ) ** 2 ) ); |
write( "(5**3)**2: ", round( ( 5 ** 3 ) ** 2 ) ); |
||
write( "5**(3**2): ", round( 5 ** round( 3 ** 2 ) ) ) |
write( "5**(3**2): ", round( 5 ** round( 3 ** 2 ) ) ) |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 139: | Line 139: | ||
AppleScript's compiler inserts its own parentheses with 5 ^ 3 ^ 2. |
AppleScript's compiler inserts its own parentheses with 5 ^ 3 ^ 2. |
||
< |
<syntaxhighlight lang="applescript">set r1 to 5 ^ 3 ^ 2 -- Changes to 5 ^ (3 ^ 2) when compiled. |
||
set r2 to (5 ^ 3) ^ 2 |
set r2 to (5 ^ 3) ^ 2 |
||
set r3 to 5 ^ (3 ^ 2) |
set r3 to 5 ^ (3 ^ 2) |
||
Line 145: | Line 145: | ||
return "5 ^ 3 ^ 2 = " & r1 & " |
return "5 ^ 3 ^ 2 = " & r1 & " |
||
(5 ^ 3) ^ 2 = " & r2 & " |
(5 ^ 3) ^ 2 = " & r2 & " |
||
5 ^ (3 ^ 2) = " & r3</ |
5 ^ (3 ^ 2) = " & r3</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Line 154: | Line 154: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">print 5^3^2 |
||
print (5^3)^2 |
print (5^3)^2 |
||
print 5^(3^2)</ |
print 5^(3^2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 165: | Line 165: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f EXPONENTIATION_ORDER.AWK |
# syntax: GAWK -f EXPONENTIATION_ORDER.AWK |
||
BEGIN { |
BEGIN { |
||
Line 173: | Line 173: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
<p>output:</p> |
<p>output:</p> |
||
<pre> |
<pre> |
||
Line 183: | Line 183: | ||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
==={{header|Sinclair ZX81 BASIC}}=== |
==={{header|Sinclair ZX81 BASIC}}=== |
||
< |
<syntaxhighlight lang="basic">10 PRINT "5**3**2 = ";5**3**2 |
||
20 PRINT "(5**3)**2 = ";(5**3)**2 |
20 PRINT "(5**3)**2 = ";(5**3)**2 |
||
30 PRINT "5**(3**2) = ";5**(3**2)</ |
30 PRINT "5**(3**2) = ";5**(3**2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5**3**2 = 15625 |
<pre>5**3**2 = 15625 |
||
Line 192: | Line 192: | ||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
< |
<syntaxhighlight lang="bbcbasic">PRINT "5^3^2 = "; 5^3^2 |
||
PRINT "(5^3)^2 = "; (5^3)^2 |
PRINT "(5^3)^2 = "; (5^3)^2 |
||
PRINT "5^(3^2) = "; 5^(3^2)</ |
PRINT "5^(3^2) = "; 5^(3^2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 15625 |
<pre>5^3^2 = 15625 |
||
Line 201: | Line 201: | ||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 PRINT "5^3^2 =";5^3^2 |
||
110 PRINT "(5^3)^2 =";(5^3)^2 |
110 PRINT "(5^3)^2 =";(5^3)^2 |
||
120 PRINT "5^(3^2) =";5^(3^2)</ |
120 PRINT "5^(3^2) =";5^(3^2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 15625 |
<pre>5^3^2 = 15625 |
||
Line 217: | Line 217: | ||
{{works with|BASIC256}} |
{{works with|BASIC256}} |
||
{{works with|Run BASIC}} |
{{works with|Run BASIC}} |
||
< |
<syntaxhighlight lang="qbasic">PRINT "5^3^2 ="; 5^3^2 |
||
PRINT "(5^3)^2 ="; (5^3)^2 |
PRINT "(5^3)^2 ="; (5^3)^2 |
||
PRINT "5^(3^2) ="; 5^(3^2) |
PRINT "5^(3^2) ="; 5^(3^2) |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 15625 |
<pre>5^3^2 = 15625 |
||
Line 231: | Line 231: | ||
{{works with|True BASIC}} |
{{works with|True BASIC}} |
||
{{works with|Run BASIC}} |
{{works with|Run BASIC}} |
||
< |
<syntaxhighlight lang="freebasic">print "5^3^2 = "; 5^3^2 |
||
print "(5^3)^2 = "; (5^3)^2 |
print "(5^3)^2 = "; (5^3)^2 |
||
print "5^(3^2) = "; 5^(3^2) |
print "5^(3^2) = "; 5^(3^2) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 15625 |
<pre>5^3^2 = 15625 |
||
Line 245: | Line 245: | ||
{{works with|True BASIC}} |
{{works with|True BASIC}} |
||
{{works with|BASIC256}} |
{{works with|BASIC256}} |
||
< |
<syntaxhighlight lang="freebasic">print "5^3^2 = "; 5^3^2 |
||
print "(5^3)^2 = "; (5^3)^2 |
print "(5^3)^2 = "; (5^3)^2 |
||
print "5^(3^2) = "; 5^(3^2) |
print "5^(3^2) = "; 5^(3^2) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 15625 |
<pre>5^3^2 = 15625 |
||
Line 259: | Line 259: | ||
{{works with|BASIC256}} |
{{works with|BASIC256}} |
||
{{works with|Run BASIC}} |
{{works with|Run BASIC}} |
||
< |
<syntaxhighlight lang="qbasic">PRINT "5^3^2 ="; 5^3^2 |
||
PRINT "(5^3)^2 ="; (5^3)^2 |
PRINT "(5^3)^2 ="; (5^3)^2 |
||
PRINT "5^(3^2) ="; 5^(3^2) |
PRINT "5^(3^2) ="; 5^(3^2) |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 15625 |
<pre>5^3^2 = 15625 |
||
Line 273: | Line 273: | ||
{{works with|True BASIC}} |
{{works with|True BASIC}} |
||
{{works with|BASIC256}} |
{{works with|BASIC256}} |
||
< |
<syntaxhighlight lang="freebasic">print "5^3^2 = ", 5^3^2 |
||
print "(5^3)^2 = ", (5^3)^2 |
print "(5^3)^2 = ", (5^3)^2 |
||
print "5^(3^2) = ", 5^(3^2) |
print "5^(3^2) = ", 5^(3^2) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 15625 |
<pre>5^3^2 = 15625 |
||
Line 284: | Line 284: | ||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">put$str$("5^3^2: " 5^3^2 "\n(5^3)^2: " (5^3)^2 "\n5^(3^2): " 5^(3^2) \n) </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2: 1953125 |
<pre>5^3^2: 1953125 |
||
Line 293: | Line 293: | ||
C does not have an exponentiation operator. The caret operator '^' performs xor bitwise operation in C. The function pow in the standard C Math library takes two arguments. |
C does not have an exponentiation operator. The caret operator '^' performs xor bitwise operation in C. The function pow in the standard C Math library takes two arguments. |
||
< |
<syntaxhighlight lang="c">#include<stdio.h> |
||
#include<math.h> |
#include<math.h> |
||
Line 302: | Line 302: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 311: | Line 311: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <cmath> |
#include <cmath> |
||
Line 319: | Line 319: | ||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
}</ |
}</syntaxhighlight> |
||
With permissive flag: |
With permissive flag: |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <cmath> |
#include <cmath> |
||
Line 334: | Line 334: | ||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 343: | Line 343: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
namespace exponents |
namespace exponents |
||
Line 363: | Line 363: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 373: | Line 373: | ||
Clojure uses prefix notation and expt only takes 2 arguments for exponentiation, so "5**3**2" isn't represented. |
Clojure uses prefix notation and expt only takes 2 arguments for exponentiation, so "5**3**2" isn't represented. |
||
< |
<syntaxhighlight lang="clojure">(use 'clojure.math.numeric-tower) |
||
;; (5**3)**2 |
;; (5**3)**2 |
||
(expt (expt 5 3) 2) ; => 15625 |
(expt (expt 5 3) 2) ; => 15625 |
||
Line 385: | Line 385: | ||
;; 5**(3**2) alternative: evaluating right-to-left with reduce requires a small modification |
;; 5**(3**2) alternative: evaluating right-to-left with reduce requires a small modification |
||
(defn rreduce [f coll] (reduce #(f %2 %) (reverse coll))) |
(defn rreduce [f coll] (reduce #(f %2 %) (reverse coll))) |
||
(rreduce expt [5 3 2]) ; => 1953125</ |
(rreduce expt [5 3 2]) ; => 1953125</syntaxhighlight> |
||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">start_up = proc () |
||
po: stream := stream$primary_output() |
po: stream := stream$primary_output() |
||
Line 394: | Line 394: | ||
stream$putl(po, "(5**3)**2 = " || int$unparse((5**3)**2)) |
stream$putl(po, "(5**3)**2 = " || int$unparse((5**3)**2)) |
||
stream$putl(po, "5**(3**2) = " || int$unparse(5**(3**2))) |
stream$putl(po, "5**(3**2) = " || int$unparse(5**(3**2))) |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5**3**2 = 1953125 |
<pre>5**3**2 = 1953125 |
||
Line 402: | Line 402: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Because Common Lisp uses prefix notation and <code>expt</code> accepts only two arguments, it doesn't have an expression for <code>5**3**2</code>. Just showing expressions for the latter two. |
Because Common Lisp uses prefix notation and <code>expt</code> accepts only two arguments, it doesn't have an expression for <code>5**3**2</code>. Just showing expressions for the latter two. |
||
< |
<syntaxhighlight lang="lisp">(expt (expt 5 3) 2) |
||
(expt 5 (expt 3 2))</ |
(expt 5 (expt 3 2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>15625 |
<pre>15625 |
||
Line 409: | Line 409: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.math, std.algorithm; |
import std.stdio, std.math, std.algorithm; |
||
Line 416: | Line 416: | ||
writefln("5 ^^ (3 ^^ 2) = %7d", 5 ^^ (3 ^^ 2)); |
writefln("5 ^^ (3 ^^ 2) = %7d", 5 ^^ (3 ^^ 2)); |
||
writefln("[5, 3, 2].reduce!pow = %7d", [5, 3, 2].reduce!pow); |
writefln("[5, 3, 2].reduce!pow = %7d", [5, 3, 2].reduce!pow); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5 ^^ 3 ^^ 2 = 1953125 |
<pre>5 ^^ 3 ^^ 2 = 1953125 |
||
Line 424: | Line 424: | ||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
;; the standard and secure way is to use the (expt a b) function |
;; the standard and secure way is to use the (expt a b) function |
||
(expt 5 (expt 3 2)) ;; 5 ** ( 3 ** 2) |
(expt 5 (expt 3 2)) ;; 5 ** ( 3 ** 2) |
||
Line 441: | Line 441: | ||
(5 ** (3 ** 2)) |
(5 ** (3 ** 2)) |
||
→ 1953125 |
→ 1953125 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Factor is a stack language where expressions take the form of reverse Polish notation, so there is no ambiguity here. It is up to you, the programmer, to perform operations in the order you intend. |
Factor is a stack language where expressions take the form of reverse Polish notation, so there is no ambiguity here. It is up to you, the programmer, to perform operations in the order you intend. |
||
< |
<syntaxhighlight lang="factor">USING: formatting math.functions ; |
||
5 3 2 ^ ^ |
5 3 2 ^ ^ |
||
Line 451: | Line 451: | ||
5 3 ^ 2 ^ |
5 3 ^ 2 ^ |
||
"5 3 ^ 2 ^ %d\n" printf</ |
"5 3 ^ 2 ^ %d\n" printf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 460: | Line 460: | ||
Factor also has syntax for infix arithmetic via the the <code>infix</code> vocabulary. |
Factor also has syntax for infix arithmetic via the the <code>infix</code> vocabulary. |
||
< |
<syntaxhighlight lang="factor">USING: formatting infix ; |
||
[infix 5**3**2 infix] |
[infix 5**3**2 infix] |
||
Line 469: | Line 469: | ||
[infix 5**(3**2) infix] |
[infix 5**(3**2) infix] |
||
"5**(3**2) = %d\n" printf</ |
"5**(3**2) = %d\n" printf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 478: | Line 478: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
< |
<syntaxhighlight lang="fortran">write(*, "(a, i0)") "5**3**2 = ", 5**3**2 |
||
write(*, "(a, i0)") "(5**3)**2 = ", (5**3)**2 |
write(*, "(a, i0)") "(5**3)**2 = ", (5**3)**2 |
||
write(*, "(a, i0)") "5**(3**2) = ", 5**(3**2)</ |
write(*, "(a, i0)") "5**(3**2) = ", 5**(3**2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5**3**2 = 1953125 |
<pre>5**3**2 = 1953125 |
||
Line 487: | Line 487: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 |
||
' The exponentation operator in FB is ^ rather than **. |
' The exponentation operator in FB is ^ rather than **. |
||
Line 497: | Line 497: | ||
Print "(5^3)^2 =>"; (5^3)^2 |
Print "(5^3)^2 =>"; (5^3)^2 |
||
Print "5^(3^2) =>"; 5^(3^2) |
Print "5^(3^2) =>"; 5^(3^2) |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 509: | Line 509: | ||
Frink correctly follows standard mathematical notation that exponent towers are performed from "top to bottom" or "right to left." |
Frink correctly follows standard mathematical notation that exponent towers are performed from "top to bottom" or "right to left." |
||
< |
<syntaxhighlight lang="frink">println["5^3^2 = " + 5^3^2] |
||
println["(5^3)^2 = " + (5^3)^2] |
println["(5^3)^2 = " + (5^3)^2] |
||
println["5^(3^2) = " + 5^(3^2)] |
println["5^(3^2) = " + 5^(3^2)] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 522: | Line 522: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 535: | Line 535: | ||
fmt.Printf("(5^3)^2 = %.0f\n", b) |
fmt.Printf("(5^3)^2 = %.0f\n", b) |
||
fmt.Printf("5^(3^2) = %.0f\n", c) |
fmt.Printf("5^(3^2) = %.0f\n", c) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 547: | Line 547: | ||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">println(" 5 ** 3 ** 2 == " + 5**3**2) |
||
println("(5 ** 3)** 2 == " + (5**3)**2) |
println("(5 ** 3)** 2 == " + (5**3)**2) |
||
println(" 5 **(3 ** 2)== " + 5**(3**2))</ |
println(" 5 **(3 ** 2)== " + 5**(3**2))</syntaxhighlight> |
||
Output: |
Output: |
||
Line 610: | Line 610: | ||
J uses the same evaluation order for exponentiation as it does for assignment. That is to say: the bottom up view is right-to-left and the top-down view is left-to-right. |
J uses the same evaluation order for exponentiation as it does for assignment. That is to say: the bottom up view is right-to-left and the top-down view is left-to-right. |
||
< |
<syntaxhighlight lang="j"> 5^3^2 |
||
1.95312e6 |
1.95312e6 |
||
(5^3)^2 |
(5^3)^2 |
||
15625 |
15625 |
||
5^(3^2) |
5^(3^2) |
||
1.95312e6</ |
1.95312e6</syntaxhighlight> |
||
---- |
---- |
||
Line 627: | Line 627: | ||
jq's built-in for exponentiation is an arity-two function and thus no ambiguity arising from infix-notation is possible. Here's an example: |
jq's built-in for exponentiation is an arity-two function and thus no ambiguity arising from infix-notation is possible. Here's an example: |
||
< |
<syntaxhighlight lang="jq">jq -n 'pow(pow(5;3);2)' |
||
15625</ |
15625</syntaxhighlight> |
||
For chaining, one could use `reduce`: |
For chaining, one could use `reduce`: |
||
< |
<syntaxhighlight lang="jq"> def pow: reduce .[1:] as $i (.[0]; pow(.;$i)) |
||
[5,3,2] | pow</ |
[5,3,2] | pow</syntaxhighlight> |
||
Result: 15625 |
Result: 15625 |
||
Line 641: | Line 641: | ||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia">@show 5 ^ 3 ^ 2 # default: power operator is read right-to-left |
||
@show (5 ^ 3) ^ 2 |
@show (5 ^ 3) ^ 2 |
||
@show 5 ^ (3 ^ 2) |
@show 5 ^ (3 ^ 2) |
||
@show reduce(^, [5, 3, 2]) |
@show reduce(^, [5, 3, 2]) |
||
@show foldl(^, [5, 3, 2]) # guarantees left associativity |
@show foldl(^, [5, 3, 2]) # guarantees left associativity |
||
@show foldr(^, [5, 3, 2]) # guarantees right associativity</ |
@show foldr(^, [5, 3, 2]) # guarantees right associativity</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 658: | Line 658: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Kotlin does not have a dedicated exponentiation operator and we would normally use Java's Math.pow function instead. However, it's possible to define an infix function which would look like an operator and here we do so for integer base and exponent. For simplicity we disallow negative exponents altogether and consider 0 ** 0 == 1. Associativity would, of course, be the same as for a normal function call. |
Kotlin does not have a dedicated exponentiation operator and we would normally use Java's Math.pow function instead. However, it's possible to define an infix function which would look like an operator and here we do so for integer base and exponent. For simplicity we disallow negative exponents altogether and consider 0 ** 0 == 1. Associativity would, of course, be the same as for a normal function call. |
||
< |
<syntaxhighlight lang="scala">// version 1.0.5-2 |
||
infix fun Int.ipow(exp: Int): Int = when { |
infix fun Int.ipow(exp: Int): Int = when { |
||
Line 680: | Line 680: | ||
println("(5**3)**2 = ${(5 ipow 3) ipow 2}") |
println("(5**3)**2 = ${(5 ipow 3) ipow 2}") |
||
println("5**(3**2) = ${5 ipow (3 ipow 2)}") |
println("5**(3**2) = ${5 ipow (3 ipow 2)}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 693: | Line 693: | ||
Because lambdatalk uses prefix notation and {pow a b} accepts only two arguments, it doesn't have an expression for 5**3**2. Just showing expressions for the latter two. |
Because lambdatalk uses prefix notation and {pow a b} accepts only two arguments, it doesn't have an expression for 5**3**2. Just showing expressions for the latter two. |
||
< |
<syntaxhighlight lang="scheme"> |
||
'{pow {pow 5 3} 2} |
'{pow {pow 5 3} 2} |
||
-> {pow {pow 5 3} 2} |
-> {pow {pow 5 3} 2} |
||
'{pow 5 {pow 3 2}} |
'{pow 5 {pow 3 2}} |
||
-> {pow 5 {pow 3 2}} |
-> {pow 5 {pow 3 2}} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Latitude}}== |
=={{header|Latitude}}== |
||
< |
<syntaxhighlight lang="latitude">5 ^ 3 ^ 2. ;; 1953125 |
||
(5 ^ 3) ^ 2. ;; 15625 |
(5 ^ 3) ^ 2. ;; 15625 |
||
5 ^ (3 ^ 2). ;; 1953125</ |
5 ^ (3 ^ 2). ;; 1953125</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">print("5^3^2 = " .. 5^3^2) |
||
print("(5^3)^2 = " .. (5^3)^2) |
print("(5^3)^2 = " .. (5^3)^2) |
||
print("5^(3^2) = " .. 5^(3^2))</ |
print("5^(3^2) = " .. 5^(3^2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 1953125 |
<pre>5^3^2 = 1953125 |
||
Line 716: | Line 716: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">5^3^2; |
||
(5^3)^2; |
(5^3)^2; |
||
5^(3^2);</ |
5^(3^2);</syntaxhighlight> |
||
{{Out|Output}} |
{{Out|Output}} |
||
<pre>Error, ambiguous use of `^`, please use parentheses |
<pre>Error, ambiguous use of `^`, please use parentheses |
||
Line 725: | Line 725: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">a = "5^3^2"; |
||
Print[a <> " = " <> ToString[ToExpression[a]]] |
Print[a <> " = " <> ToString[ToExpression[a]]] |
||
b = "(5^3)^2"; |
b = "(5^3)^2"; |
||
Print[b <> " = " <> ToString[ToExpression[b]]] |
Print[b <> " = " <> ToString[ToExpression[b]]] |
||
c = "5^(3^2)"; |
c = "5^(3^2)"; |
||
Print[c <> " = " <> ToString[ToExpression[c]]]</ |
Print[c <> " = " <> ToString[ToExpression[c]]]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 1953125 |
<pre>5^3^2 = 1953125 |
||
Line 739: | Line 739: | ||
As with other postfix languages, there is no ambiguity because all operators have the same precedence. |
As with other postfix languages, there is no ambiguity because all operators have the same precedence. |
||
{{works with|min|0.19.6}} |
{{works with|min|0.19.6}} |
||
< |
<syntaxhighlight lang="min">5 3 2 pow pow |
||
"5 3 2 ^ ^ " print! puts! |
"5 3 2 ^ ^ " print! puts! |
||
5 3 pow 2 pow |
5 3 pow 2 pow |
||
"5 3 ^ 2 ^ " print! puts!</ |
"5 3 ^ 2 ^ " print! puts!</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 752: | Line 752: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
Nanoquery uses the '^' operator, which performs exponentiation in order like multiplication. Parenthesis are often needed to perform operations like 5^3^2 correctly. |
Nanoquery uses the '^' operator, which performs exponentiation in order like multiplication. Parenthesis are often needed to perform operations like 5^3^2 correctly. |
||
< |
<syntaxhighlight lang="nanoquery">% println 5^3^2 |
||
15625 |
15625 |
||
% println (5^3)^2 |
% println (5^3)^2 |
||
15625 |
15625 |
||
% println 5^(3^2) |
% println 5^(3^2) |
||
1953125</ |
1953125</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
Line 766: | Line 766: | ||
echo "5^(3^2) = ", 5^(3^2) |
echo "5^(3^2) = ", 5^(3^2) |
||
echo "foldl([5, 3, 2], a^b) = ", foldl([5, 3, 2], a^b) |
echo "foldl([5, 3, 2], a^b) = ", foldl([5, 3, 2], a^b) |
||
echo "foldr([5, 3, 2], a^b) = ", foldr([5, 3, 2], a^b)</ |
echo "foldr([5, 3, 2], a^b) = ", foldr([5, 3, 2], a^b)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 792: | Line 792: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Exponentiation is right-associative in GP. |
Exponentiation is right-associative in GP. |
||
< |
<syntaxhighlight lang="parigp">f(s)=print(s" = "eval(s)); |
||
apply(f, ["5^3^2", "(5^3)^2", "5^(3^2)"]);</ |
apply(f, ["5^3^2", "(5^3)^2", "5^(3^2)"]);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5^3^2 = 1953125 |
<pre>5^3^2 = 1953125 |
||
Line 800: | Line 800: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">say "$_ = " . eval($_) for qw/5**3**2 (5**3)**2 5**(3**2)/;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 811: | Line 811: | ||
{{libheader|Phix/basics}} |
{{libheader|Phix/basics}} |
||
Phix has a power function rather than an infix power operator, hence there is no possible confusion. |
Phix has a power function rather than an infix power operator, hence there is no possible confusion. |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #0000FF;">?<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #000000;">5<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">)</span> |
<span style="color: #0000FF;">?<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #000000;">5<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">)</span> |
||
<span style="color: #0000FF;">?<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #000000;">5<span style="color: #0000FF;">,<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #000000;">3<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">)<span style="color: #0000FF;">) |
<span style="color: #0000FF;">?<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #000000;">5<span style="color: #0000FF;">,<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #000000;">3<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">)<span style="color: #0000FF;">) |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 823: | Line 823: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
The PicoLisp '**' exponentiation function takes 2 arguments |
The PicoLisp '**' exponentiation function takes 2 arguments |
||
< |
<syntaxhighlight lang="picolisp">: (** (** 5 3) 2) |
||
-> 15625 |
-> 15625 |
||
: (** 5 (** 3 2)) |
: (** 5 (** 3 2)) |
||
-> 1953125</ |
-> 1953125</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">exponentiation: procedure options(main); |
||
put skip edit('5**3**2 = ', 5**3**2) (A,F(7)); |
put skip edit('5**3**2 = ', 5**3**2) (A,F(7)); |
||
put skip edit('(5**3)**2 = ', (5**3)**2) (A,F(7)); |
put skip edit('(5**3)**2 = ', (5**3)**2) (A,F(7)); |
||
put skip edit('5**(3**2) = ', 5**(3**2)) (A,F(7)); |
put skip edit('5**(3**2) = ', 5**(3**2)) (A,F(7)); |
||
end exponentiation;</ |
end exponentiation;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5**3**2 = 15625 |
<pre>5**3**2 = 15625 |
||
Line 841: | Line 841: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">>>> 5**3**2 |
||
1953125 |
1953125 |
||
>>> (5**3)**2 |
>>> (5**3)**2 |
||
Line 853: | Line 853: | ||
>>> reduce(pow, (5, 3, 2)) |
>>> reduce(pow, (5, 3, 2)) |
||
15625 |
15625 |
||
>>> </ |
>>> </syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 876: | Line 876: | ||
It turns out that the parser is so blind to "**" that we cannot even quote it. The following are identical: |
It turns out that the parser is so blind to "**" that we cannot even quote it. The following are identical: |
||
< |
<syntaxhighlight lang="rsplus">print(quote(5**3)) |
||
print(quote(5^3))</ |
print(quote(5^3))</syntaxhighlight> |
||
Another method is to use "^" as if it is an ordinary function of two arguments. It appears that "**" does not support this. As there is no potential for ambiguity in the operator precedence, we will not print this result below. For example: |
Another method is to use "^" as if it is an ordinary function of two arguments. It appears that "**" does not support this. As there is no potential for ambiguity in the operator precedence, we will not print this result below. For example: |
||
< |
<syntaxhighlight lang="rsplus">'^'('^'(5, 3), 2)</syntaxhighlight> |
||
is clearly (5^3)^2 i.e. 15625, whereas |
is clearly (5^3)^2 i.e. 15625, whereas |
||
< |
<syntaxhighlight lang="rsplus">'^'(5, '^'(3, 2))</syntaxhighlight> |
||
is clearly 5^(3^2) i.e. 1953125. |
is clearly 5^(3^2) i.e. 1953125. |
||
As for actually solving the task, the requirement that each output be on a new line causes us a surprising amount of difficulty. To avoid repeating ourselves, we must almost resort to metaprogramming: |
As for actually solving the task, the requirement that each output be on a new line causes us a surprising amount of difficulty. To avoid repeating ourselves, we must almost resort to metaprogramming: |
||
< |
<syntaxhighlight lang="rsplus">inputs <- alist(5^3^2, (5^3)^2, 5^(3^2), 5**3**2, (5**3)**2, 5**(3**2)) |
||
invisible(sapply(inputs, function(x) cat(deparse(x), "returns: ", eval(x), "\n")))</ |
invisible(sapply(inputs, function(x) cat(deparse(x), "returns: ", eval(x), "\n")))</syntaxhighlight> |
||
Alternatively, we could print out a matrix or data frame: |
Alternatively, we could print out a matrix or data frame: |
||
< |
<syntaxhighlight lang="rsplus">print(matrix(sapply(inputs, eval), dimnames = list(inputs, "Outputs"))) |
||
print(data.frame(Inputs = sapply(inputs, deparse), Outputs = sapply(inputs, eval))))</ |
print(data.frame(Inputs = sapply(inputs, deparse), Outputs = sapply(inputs, eval))))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>> print(quote(5**3)) |
<pre>> print(quote(5**3)) |
||
Line 922: | Line 922: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
;; 5**3**2 depends on associativity of ** : Racket's (scheme's) prefix function |
;; 5**3**2 depends on associativity of ** : Racket's (scheme's) prefix function |
||
;; calling syntax only allows for pairs of arguments for expt. |
;; calling syntax only allows for pairs of arguments for expt. |
||
Line 943: | Line 943: | ||
(require (only-in srfi/1 reduce reduce-right)) |
(require (only-in srfi/1 reduce reduce-right)) |
||
(reduce expt 1 '(5 3 2)) |
(reduce expt 1 '(5 3 2)) |
||
(reduce-right expt 1 '(5 3 2))</ |
(reduce-right expt 1 '(5 3 2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>prefix |
<pre>prefix |
||
Line 961: | Line 961: | ||
Note that the reduction forms automatically go right-to-left because the base operator is right-associative. Most other operators are left-associative and would automatically reduce left-to-right instead. |
Note that the reduction forms automatically go right-to-left because the base operator is right-associative. Most other operators are left-associative and would automatically reduce left-to-right instead. |
||
<lang |
<syntaxhighlight lang="raku" line>use MONKEY-SEE-NO-EVAL; |
||
sub demo($x) { say " $x\t───► ", EVAL $x } |
sub demo($x) { say " $x\t───► ", EVAL $x } |
||
Line 975: | Line 975: | ||
demo '(5³)²'; |
demo '(5³)²'; |
||
demo '5³²'; |
demo '5³²'; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 992: | Line 992: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
In Red, operators simply evaluate left to right. As this differs from mathematical order of operations, Red provides the <code>math</code> function which evaluates a block using math rules instead of Red's default evaluation. One could also use the <code>power</code> function, sidestepping the issue of evaluation order entirely. All three approaches are shown. |
In Red, operators simply evaluate left to right. As this differs from mathematical order of operations, Red provides the <code>math</code> function which evaluates a block using math rules instead of Red's default evaluation. One could also use the <code>power</code> function, sidestepping the issue of evaluation order entirely. All three approaches are shown. |
||
< |
<syntaxhighlight lang="rebol">Red["Exponentiation order"] |
||
exprs: [ |
exprs: [ |
||
Line 1,007: | Line 1,007: | ||
print [mold/only expr "=" math expr "using math"] |
print [mold/only expr "=" math expr "using math"] |
||
] |
] |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,021: | Line 1,021: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates various ways of multiple exponentiations. */ |
||
/*┌────────────────────────────────────────────────────────────────────┐ |
/*┌────────────────────────────────────────────────────────────────────┐ |
||
│ The REXX language uses ** for exponentiation. │ |
│ The REXX language uses ** for exponentiation. │ |
||
Line 1,031: | Line 1,031: | ||
say ' (5**3)**2 ───► ' (5**3)**2 |
say ' (5**3)**2 ───► ' (5**3)**2 |
||
say ' 5**(3**2) ───► ' 5**(3**2) |
say ' 5**(3**2) ───► ' 5**(3**2) |
||
/*stick a fork in it, we're done.*/</ |
/*stick a fork in it, we're done.*/</syntaxhighlight> |
||
'''output''' |
'''output''' |
||
<pre> |
<pre> |
||
Line 1,043: | Line 1,043: | ||
In the Ring it is impossible to show the result of: 5^3^2 |
In the Ring it is impossible to show the result of: 5^3^2 |
||
< |
<syntaxhighlight lang="ring"> |
||
see "(5^3)^2 =>" + pow(pow(5,3),2) + nl |
see "(5^3)^2 =>" + pow(pow(5,3),2) + nl |
||
see "5^(3^2) =>" + pow(5,pow(3,2)) + nl |
see "5^(3^2) =>" + pow(5,pow(3,2)) + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,054: | Line 1,054: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">ar = ["5**3**2", "(5**3)**2", "5**(3**2)", "[5,3,2].inject(:**)"] |
||
ar.each{|exp| puts "#{exp}:\t#{eval exp}"} |
ar.each{|exp| puts "#{exp}:\t#{eval exp}"} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,067: | Line 1,067: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
println!("5**3**2 = {:7}", 5u32.pow(3).pow(2)); |
println!("5**3**2 = {:7}", 5u32.pow(3).pow(2)); |
||
println!("(5**3)**2 = {:7}", (5u32.pow(3)).pow(2)); |
println!("(5**3)**2 = {:7}", (5u32.pow(3)).pow(2)); |
||
println!("5**(3**2) = {:7}", 5u32.pow(3u32.pow(2))); |
println!("5**(3**2) = {:7}", 5u32.pow(3u32.pow(2))); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,083: | Line 1,083: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 1,090: | Line 1,090: | ||
writeln("(5**3)**2 = " <& (5**3)**2); |
writeln("(5**3)**2 = " <& (5**3)**2); |
||
writeln("5**(3**2) = " <& 5**(3**2)); |
writeln("5**(3**2) = " <& 5**(3**2)); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,101: | Line 1,101: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
In Sidef, the whitespace between the operands and the operator controls the precedence of the operation. |
In Sidef, the whitespace between the operands and the operator controls the precedence of the operation. |
||
< |
<syntaxhighlight lang="ruby">var a = [ |
||
'5**3**2', |
'5**3**2', |
||
'(5**3)**2', |
'(5**3)**2', |
||
Line 1,113: | Line 1,113: | ||
a.each {|e| |
a.each {|e| |
||
"%-12s == %s\n".printf(e, eval(e)) |
"%-12s == %s\n".printf(e, eval(e)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,126: | Line 1,126: | ||
=={{header|Simula}}== |
=={{header|Simula}}== |
||
< |
<syntaxhighlight lang="simula">OutText("5** 3 **2: "); OutInt(5** 3 **2, 0); Outimage; |
||
OutText("(5**3)**2: "); OutInt((5**3)**2, 0); Outimage; |
OutText("(5**3)**2: "); OutInt((5**3)**2, 0); Outimage; |
||
OutText("5**(3**2): "); OutInt(5**(3**2), 0); Outimage</ |
OutText("5**(3**2): "); OutInt(5**(3**2), 0); Outimage</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5** 3 **2: 15625 |
<pre>5** 3 **2: 15625 |
||
Line 1,137: | Line 1,137: | ||
Works in Smalltalk/X ¹ |
Works in Smalltalk/X ¹ |
||
<p>Smalltalk strictly evaluates left to right; operators are not known to the language/parser, but instead message sends to the receiver on the left side (aka: virtual function calls) . |
<p>Smalltalk strictly evaluates left to right; operators are not known to the language/parser, but instead message sends to the receiver on the left side (aka: virtual function calls) . |
||
< |
<syntaxhighlight lang="smalltalk">Transcript show:'5**3**2 => '; showCR: 5**3**2. |
||
Transcript show:'(5**3)**2 => '; showCR: (5**3)**2. |
Transcript show:'(5**3)**2 => '; showCR: (5**3)**2. |
||
Transcript show:'5**(3**2) => '; showCR: 5**(3**2).</ |
Transcript show:'5**(3**2) => '; showCR: 5**(3**2).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,150: | Line 1,150: | ||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">. di (5^3^2) |
||
15625 |
15625 |
||
Line 1,157: | Line 1,157: | ||
. di (5^(3^2)) |
. di (5^(3^2)) |
||
1953125</ |
1953125</syntaxhighlight> |
||
Likewise in Mata: |
Likewise in Mata: |
||
< |
<syntaxhighlight lang="stata">. mata (5^3^2) |
||
15625 |
15625 |
||
Line 1,168: | Line 1,168: | ||
. mata (5^(3^2)) |
. mata (5^(3^2)) |
||
1953125</ |
1953125</syntaxhighlight> |
||
Line 1,175: | Line 1,175: | ||
Swift doesn't have an exponentiation operator, however it's possible to define one, including the precedence and associativity. |
Swift doesn't have an exponentiation operator, however it's possible to define one, including the precedence and associativity. |
||
< |
<syntaxhighlight lang="swift">precedencegroup ExponentiationPrecedence { |
||
associativity: left |
associativity: left |
||
higherThan: MultiplicationPrecedence |
higherThan: MultiplicationPrecedence |
||
Line 1,211: | Line 1,211: | ||
print(5 ** 3 ** 2) |
print(5 ** 3 ** 2) |
||
print((5 ** 3) ** 2) |
print((5 ** 3) ** 2) |
||
print(5 ** (3 ** 2))</ |
print(5 ** (3 ** 2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,220: | Line 1,220: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">foreach expression {5**3**2 (5**3)**2 5**(3**2)} { |
||
puts "${expression}:\t[expr $expression]" |
puts "${expression}:\t[expr $expression]" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,232: | Line 1,232: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Public Sub exp() |
||
Debug.Print "5^3^2", 5 ^ 3 ^ 2 |
Debug.Print "5^3^2", 5 ^ 3 ^ 2 |
||
Debug.Print "(5^3)^2", (5 ^ 3) ^ 2 |
Debug.Print "(5^3)^2", (5 ^ 3) ^ 2 |
||
Debug.Print "5^(3^2)", 5 ^ (3 ^ 2) |
Debug.Print "5^(3^2)", 5 ^ (3 ^ 2) |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>5^3^2 15625 |
<pre>5^3^2 15625 |
||
(5^3)^2 15625 |
(5^3)^2 15625 |
||
Line 1,243: | Line 1,243: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
WScript.StdOut.WriteLine "5^3^2 => " & 5^3^2 |
WScript.StdOut.WriteLine "5^3^2 => " & 5^3^2 |
||
WScript.StdOut.WriteLine "(5^3)^2 => " & (5^3)^2 |
WScript.StdOut.WriteLine "(5^3)^2 => " & (5^3)^2 |
||
WScript.StdOut.WriteLine "5^(3^2) => " & 5^(3^2) |
WScript.StdOut.WriteLine "5^(3^2) => " & 5^(3^2) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 1,257: | Line 1,257: | ||
=={{header|Verbexx}}== |
=={{header|Verbexx}}== |
||
< |
<syntaxhighlight lang="verbexx">// Exponentiation order example: |
||
@SAY "5**3**2 = " ( 5**3**2 ); |
@SAY "5**3**2 = " ( 5**3**2 ); |
||
Line 1,267: | Line 1,267: | ||
5**3**2 = 1953125 |
5**3**2 = 1953125 |
||
(5**3)**2 = 15625 |
(5**3)**2 = 15625 |
||
5**(3**2) = 1953125</ |
5**(3**2) = 1953125</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
Wren doesn't have an exponentiation operator as such but the Num class has a ''pow'' method which does the same thing. |
Wren doesn't have an exponentiation operator as such but the Num class has a ''pow'' method which does the same thing. |
||
< |
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt |
||
var ops = [ "5**3**2", "(5**3)**2", "5**(3**2)" ] |
var ops = [ "5**3**2", "(5**3)**2", "5**(3**2)" ] |
||
Line 1,278: | Line 1,278: | ||
for (i in 0...ops.count) { |
for (i in 0...ops.count) { |
||
System.print("%(Fmt.s(-9, ops[i])) -> %(results[i])") |
System.print("%(Fmt.s(-9, ops[i])) -> %(results[i])") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,290: | Line 1,290: | ||
{{trans|C}} |
{{trans|C}} |
||
zkl does not have an exponentiation operator but floats have a pow method. |
zkl does not have an exponentiation operator but floats have a pow method. |
||
< |
<syntaxhighlight lang="zkl">println("5 ^ 3 ^ 2 = %,d".fmt((5.0).pow((3.0).pow(2)))); |
||
println("(5 ^ 3) ^ 2 = %,d".fmt((5.0).pow(3).pow(2))); |
println("(5 ^ 3) ^ 2 = %,d".fmt((5.0).pow(3).pow(2))); |
||
println("5 ^ (3 ^ 2) = %,d".fmt((5.0).pow((3.0).pow(2))));</ |
println("5 ^ (3 ^ 2) = %,d".fmt((5.0).pow((3.0).pow(2))));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Revision as of 11:00, 27 August 2022
You are encouraged to solve this task according to the task description, using any language you may know.
This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **
, ^
, ↑
or some such for exponentiation.)
- Task requirements
Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):
- 5**3**2
- (5**3)**2
- 5**(3**2)
If there are other methods (or formats) of multiple exponentiations, show them as well.
- See also
- MathWorld entry: exponentiation
- Related tasks
- exponentiation operator
- arbitrary-precision integers (included)
- Exponentiation with infix operators in (or operating on) the base
11l
print(5 ^ 3 ^ 2)
print((5 ^ 3) ^ 2)
print(5 ^ (3 ^ 2))
- Output:
1.95313e+06 15625 1.95313e+06
Action!
There is no power operator in Action! Power function for REAL type is used. But the precision is insufficient.
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Main()
REAL r2,r3,r5,tmp1,tmp2
Put(125) PutE() ;clear screen
IntToReal(2,r2)
IntToReal(3,r3)
IntToReal(5,r5)
PrintE("There is no power operator in Action!")
PrintE("Power function for REAL type is used.")
PrintE("But the precision is insufficient.")
Power(r5,r3,tmp1)
Power(tmp1,r2,tmp2)
Print("(5^3)^2=")
PrintRE(tmp2)
Power(r3,r2,tmp1)
Power(r5,tmp1,tmp2)
Print("5^(3^2)=")
PrintRE(tmp2)
RETURN
- Output:
Screenshot from Atari 8-bit computer
There is no power operator in Action! Power function for REAL type is used. But the precision is insufficient. (5^3)^2=15624.9977 5^(3^2)=1953124.17
Ada
5**3**2 is not a valid Ada expression. Parenthesis are mandatory.
with Ada.Text_IO;
procedure Exponentation_Order is
use Ada.Text_IO;
begin
-- Put_Line ("5**3**2 : " & Natural'(5**3**2)'Image);
Put_Line ("(5**3)**2 : " & Natural'((5**3)**2)'Image);
Put_Line ("5**(3**2) : " & Natural'(5**(3**2))'Image);
end Exponentation_Order;
- Output:
(5**3)**2 : 15625 5**(3**2) : 1953125
ALGOL 68
Algol 68 provides various alternative symbols for the exponentiation operator generally, "**", "^" and "UP" can be used.
print( ( "5**3**2: ", 5**3**2, newline ) );
print( ( "(5**3)**2: ", (5**3)**2, newline ) );
print( ( "5**(3**2): ", 5**(3**2), newline ) )
- Output:
5**3**2: +15625 (5**3)**2: +15625 5**(3**2): +1953125
ALGOL W
The Algol W exponentiation operator always produces a real result and requires an integer right operand, hence the round functions in the following.
begin
write( "5**3**2: ", round( 5 ** 3 ** 2 ) );
write( "(5**3)**2: ", round( ( 5 ** 3 ) ** 2 ) );
write( "5**(3**2): ", round( 5 ** round( 3 ** 2 ) ) )
end.
- Output:
5**3**2: 15625 (5**3)**2: 15625 5**(3**2): 1953125
APL
APL has no order of precedence other than right-to-left operation. * is the APL exponentiation operator.
5*3*2 1953125 (5*3)*2 15625 5*(3*2) 1953125
AppleScript
AppleScript's compiler inserts its own parentheses with 5 ^ 3 ^ 2.
set r1 to 5 ^ 3 ^ 2 -- Changes to 5 ^ (3 ^ 2) when compiled.
set r2 to (5 ^ 3) ^ 2
set r3 to 5 ^ (3 ^ 2)
return "5 ^ 3 ^ 2 = " & r1 & "
(5 ^ 3) ^ 2 = " & r2 & "
5 ^ (3 ^ 2) = " & r3
- Output:
"5 ^ 3 ^ 2 = 1.953125E+6 (5 ^ 3) ^ 2 = 1.5625E+4 5 ^ (3 ^ 2) = 1.953125E+6"
Arturo
print 5^3^2
print (5^3)^2
print 5^(3^2)
- Output:
1953125 15625 1953125
AWK
# syntax: GAWK -f EXPONENTIATION_ORDER.AWK
BEGIN {
printf("5^3^2 = %d\n",5^3^2)
printf("(5^3)^2 = %d\n",(5^3)^2)
printf("5^(3^2) = %d\n",5^(3^2))
exit(0)
}
output:
5^3^2 = 1953125 (5^3)^2 = 15625 5^(3^2) = 1953125
BASIC
Sinclair ZX81 BASIC
10 PRINT "5**3**2 = ";5**3**2
20 PRINT "(5**3)**2 = ";(5**3)**2
30 PRINT "5**(3**2) = ";5**(3**2)
- Output:
5**3**2 = 15625 (5**3)**2 = 15625 5**(3**2) = 1953125
BBC BASIC
PRINT "5^3^2 = "; 5^3^2
PRINT "(5^3)^2 = "; (5^3)^2
PRINT "5^(3^2) = "; 5^(3^2)
- Output:
5^3^2 = 15625 (5^3)^2 = 15625 5^(3^2) = 1953125
IS-BASIC
100 PRINT "5^3^2 =";5^3^2
110 PRINT "(5^3)^2 =";(5^3)^2
120 PRINT "5^(3^2) =";5^(3^2)
- Output:
5^3^2 = 15625 (5^3)^2 = 15625 5^(3^2) = 1953125
QBasic
PRINT "5^3^2 ="; 5^3^2
PRINT "(5^3)^2 ="; (5^3)^2
PRINT "5^(3^2) ="; 5^(3^2)
END
- Output:
5^3^2 = 15625 (5^3)^2 = 15625 5^(3^2) = 1953125
BASIC256
print "5^3^2 = "; 5^3^2
print "(5^3)^2 = "; (5^3)^2
print "5^(3^2) = "; 5^(3^2)
end
- Output:
5^3^2 = 15625 (5^3)^2 = 15625 5^(3^2) = 1953125
Run BASIC
print "5^3^2 = "; 5^3^2
print "(5^3)^2 = "; (5^3)^2
print "5^(3^2) = "; 5^(3^2)
end
- Output:
5^3^2 = 15625 (5^3)^2 = 15625 5^(3^2) = 1953125
True BASIC
PRINT "5^3^2 ="; 5^3^2
PRINT "(5^3)^2 ="; (5^3)^2
PRINT "5^(3^2) ="; 5^(3^2)
END
- Output:
5^3^2 = 15625 (5^3)^2 = 15625 5^(3^2) = 1953125
Yabasic
print "5^3^2 = ", 5^3^2
print "(5^3)^2 = ", (5^3)^2
print "5^(3^2) = ", 5^(3^2)
end
- Output:
5^3^2 = 15625 (5^3)^2 = 15625 5^(3^2) = 1953125
Bracmat
put$str$("5^3^2: " 5^3^2 "\n(5^3)^2: " (5^3)^2 "\n5^(3^2): " 5^(3^2) \n)
- Output:
5^3^2: 1953125 (5^3)^2: 15625 5^(3^2): 1953125
C
C does not have an exponentiation operator. The caret operator '^' performs xor bitwise operation in C. The function pow in the standard C Math library takes two arguments.
#include<stdio.h>
#include<math.h>
int main()
{
printf("(5 ^ 3) ^ 2 = %.0f",pow(pow(5,3),2));
printf("\n5 ^ (3 ^ 2) = %.0f",pow(5,pow(3,2)));
return 0;
}
- Output:
(5 ^ 3) ^ 2 = 15625 5 ^ (3 ^ 2) = 1953125
C++
#include <iostream>
#include <cmath>
int main() {
std::cout << "(5 ^ 3) ^ 2 = " << (uint) pow(pow(5,3), 2) << std::endl;
std::cout << "5 ^ (3 ^ 2) = "<< (uint) pow(5, (pow(3, 2)));
return EXIT_SUCCESS;
}
With permissive flag:
#include <iostream>
#include <cmath>
enum my_int {};
inline my_int operator^(my_int a, my_int b) { return static_cast<my_int>(pow(a,b)); }
int main() {
my_int x = 5, y = 3, z = 2;
std::cout << "(5 ^ 3) ^ 2 = " << ((x^y)^z) << std::endl;
std::cout << "5 ^ (3 ^ 2) = "<< (x^(y^z));
return EXIT_SUCCESS;
}
- Output:
(5 ^ 3) ^ 2 = 15625 5 ^ (3 ^ 2) = 1953125
C#
using System;
namespace exponents
{
class Program
{
static void Main(string[] args)
{
/*
* Like C, C# does not have an exponent operator.
* Exponentiation is done via Math.Pow, which
* only takes two arguments
*/
Console.WriteLine(Math.Pow(Math.Pow(5, 3), 2));
Console.WriteLine(Math.Pow(5, Math.Pow(3, 2)));
Console.Read();
}
}
}
- Output:
15625 1953125
Clojure
Clojure uses prefix notation and expt only takes 2 arguments for exponentiation, so "5**3**2" isn't represented.
(use 'clojure.math.numeric-tower)
;; (5**3)**2
(expt (expt 5 3) 2) ; => 15625
;; 5**(3**2)
(expt 5 (expt 3 2)) ; => 1953125
;; (5**3)**2 alternative: use reduce
(reduce expt [5 3 2]) ; => 15625
;; 5**(3**2) alternative: evaluating right-to-left with reduce requires a small modification
(defn rreduce [f coll] (reduce #(f %2 %) (reverse coll)))
(rreduce expt [5 3 2]) ; => 1953125
CLU
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, "5**3**2 = " || int$unparse(5**3**2))
stream$putl(po, "(5**3)**2 = " || int$unparse((5**3)**2))
stream$putl(po, "5**(3**2) = " || int$unparse(5**(3**2)))
end start_up
- Output:
5**3**2 = 1953125 (5**3)**2 = 15625 5**(3**2) = 1953125
Common Lisp
Because Common Lisp uses prefix notation and expt
accepts only two arguments, it doesn't have an expression for 5**3**2
. Just showing expressions for the latter two.
(expt (expt 5 3) 2)
(expt 5 (expt 3 2))
- Output:
15625 1953125
D
void main() {
import std.stdio, std.math, std.algorithm;
writefln("5 ^^ 3 ^^ 2 = %7d", 5 ^^ 3 ^^ 2);
writefln("(5 ^^ 3) ^^ 2 = %7d", (5 ^^ 3) ^^ 2);
writefln("5 ^^ (3 ^^ 2) = %7d", 5 ^^ (3 ^^ 2));
writefln("[5, 3, 2].reduce!pow = %7d", [5, 3, 2].reduce!pow);
}
- Output:
5 ^^ 3 ^^ 2 = 1953125 (5 ^^ 3) ^^ 2 = 15625 5 ^^ (3 ^^ 2) = 1953125 [5, 3, 2].reduce!pow = 15625
EchoLisp
;; the standard and secure way is to use the (expt a b) function
(expt 5 (expt 3 2)) ;; 5 ** ( 3 ** 2)
→ 1953125
(expt (expt 5 3) 2) ;; (5 ** 3) ** 2
→ 15625
;; infix EchoLisp may use the ** operator, which right associates
(lib 'match)
(load 'infix.glisp)
(5 ** 3 ** 2)
→ 1953125
((5 ** 3) ** 2)
→ 15625
(5 ** (3 ** 2))
→ 1953125
Factor
Factor is a stack language where expressions take the form of reverse Polish notation, so there is no ambiguity here. It is up to you, the programmer, to perform operations in the order you intend.
USING: formatting math.functions ;
5 3 2 ^ ^
"5 3 2 ^ ^ %d\n" printf
5 3 ^ 2 ^
"5 3 ^ 2 ^ %d\n" printf
- Output:
5 3 2 ^ ^ 1953125 5 3 ^ 2 ^ 15625
Factor also has syntax for infix arithmetic via the the infix
vocabulary.
USING: formatting infix ;
[infix 5**3**2 infix]
"5**3**2 = %d\n" printf
[infix (5**3)**2 infix]
"(5**3)**2 = %d\n" printf
[infix 5**(3**2) infix]
"5**(3**2) = %d\n" printf
- Output:
5**3**2 = 15625 (5**3)**2 = 15625 5**(3**2) = 1953125
Fortran
write(*, "(a, i0)") "5**3**2 = ", 5**3**2
write(*, "(a, i0)") "(5**3)**2 = ", (5**3)**2
write(*, "(a, i0)") "5**(3**2) = ", 5**(3**2)
- Output:
5**3**2 = 1953125 (5**3)**2 = 15625 5**(3**2) = 1953125
FreeBASIC
' FB 1.05.0
' The exponentation operator in FB is ^ rather than **.
' In the absence of parenthesis this operator is
' left-associative. So the first example
' will have the same value as the second example.
Print "5^3^2 =>"; 5^3^2
Print "(5^3)^2 =>"; (5^3)^2
Print "5^(3^2) =>"; 5^(3^2)
Sleep
- Output:
5^3^2 => 15625 (5^3)^2 => 15625 5^(3^2) => 1953125
Frink
Frink correctly follows standard mathematical notation that exponent towers are performed from "top to bottom" or "right to left."
println["5^3^2 = " + 5^3^2]
println["(5^3)^2 = " + (5^3)^2]
println["5^(3^2) = " + 5^(3^2)]
- Output:
5^3^2 = 1953125 (5^3)^2 = 15625 5^(3^2) = 1953125
Go
package main
import "fmt"
import "math"
func main() {
var a, b, c float64
a = math.Pow(5, math.Pow(3, 2))
b = math.Pow(math.Pow(5, 3), 2)
c = math.Pow(5, math.Pow(3, 2))
fmt.Printf("5^3^2 = %.0f\n", a)
fmt.Printf("(5^3)^2 = %.0f\n", b)
fmt.Printf("5^(3^2) = %.0f\n", c)
}
- Output:
5^3^2 = 1953125 (5^3)^2 = 15625 5^(3^2) = 1953125
Groovy
Solution:
println(" 5 ** 3 ** 2 == " + 5**3**2)
println("(5 ** 3)** 2 == " + (5**3)**2)
println(" 5 **(3 ** 2)== " + 5**(3**2))
Output:
5 ** 3 ** 2 == 15625 (5 ** 3)** 2 == 15625 5 **(3 ** 2)== 1953125
Haskell
Haskell has three infix exponentiation operators dealing with different domains:
λ> :i (^) (^) :: (Num a, Integral b) => a -> b -> a -- Defined in ‘GHC.Real’ infixr 8 ^ λ> :i (**) class Fractional a => Floating a where ... (**) :: a -> a -> a ... -- Defined in ‘GHC.Float’ infixr 8 ** λ> :i (^^) (^^) :: (Fractional a, Integral b) => a -> b -> a -- Defined in ‘GHC.Real’ infixr 8 ^^
All of them are right-associative.
λ> 5^3^2 1953125 λ> (5^3)^2 15625 λ> 5^(3^2) 1953125 λ> 5**3**2 == 5**(3**2) True
However natural chaining of (^^) operator is impossible:
5^^3^^2 = 5^^(3^^2)
but (3^^2) is not Integral any longer, so evaluation leads to the type error. Left-assiciative chain is Ok:
λ> (5^^3)^^2 15625.0 λ> ((5^^3)^^2)^^4 5.9604644775390624e16
Io
Io> 5**3**2 ==> 15625 Io> (5**3)**2 ==> 15625 Io> 5**(3**2) ==> 1953125 Io> 5 pow(3) pow(2) ==> 15625 Io> 5 **(3) **(2) ==> 15625 Io> Number getSlot("**") == Number getSlot("pow") ==> true Io>
Operators in Io are implemented as methods. Here the **
method is the same as the pow
method. Syntax sugar converts "normal" mathematical expressions to messages.
J
J uses the same evaluation order for exponentiation as it does for assignment. That is to say: the bottom up view is right-to-left and the top-down view is left-to-right.
5^3^2
1.95312e6
(5^3)^2
15625
5^(3^2)
1.95312e6
Java
Java has no exponentiation operator, but uses the static method java.lang.Math.pow(double a, double b). There are no associativity issues.
jq
Requires: jq 1.5 or higher
jq's built-in for exponentiation is an arity-two function and thus no ambiguity arising from infix-notation is possible. Here's an example:
jq -n 'pow(pow(5;3);2)'
15625
For chaining, one could use `reduce`:
def pow: reduce .[1:] as $i (.[0]; pow(.;$i))
[5,3,2] | pow
Result: 15625
Julia
@show 5 ^ 3 ^ 2 # default: power operator is read right-to-left
@show (5 ^ 3) ^ 2
@show 5 ^ (3 ^ 2)
@show reduce(^, [5, 3, 2])
@show foldl(^, [5, 3, 2]) # guarantees left associativity
@show foldr(^, [5, 3, 2]) # guarantees right associativity
- Output:
5 ^ (3 ^ 2) = 1953125 (5 ^ 3) ^ 2 = 15625 5 ^ (3 ^ 2) = 1953125 reduce(^, [5, 3, 2]) = 15625 foldl(^, [5, 3, 2]) = 15625 foldr(^, [5, 3, 2]) = 1953125
Kotlin
Kotlin does not have a dedicated exponentiation operator and we would normally use Java's Math.pow function instead. However, it's possible to define an infix function which would look like an operator and here we do so for integer base and exponent. For simplicity we disallow negative exponents altogether and consider 0 ** 0 == 1. Associativity would, of course, be the same as for a normal function call.
// version 1.0.5-2
infix fun Int.ipow(exp: Int): Int = when {
exp < 0 -> throw IllegalArgumentException("negative exponents not allowed")
exp == 0 -> 1
else -> {
var ans = 1
var base = this
var e = exp
while(e != 0) {
if (e and 1 == 1) ans *= base
e = e shr 1
base *= base
}
ans
}
}
fun main(args: Array<String>) {
println("5**3**2 = ${5 ipow 3 ipow 2}")
println("(5**3)**2 = ${(5 ipow 3) ipow 2}")
println("5**(3**2) = ${5 ipow (3 ipow 2)}")
}
- Output:
5**3**2 = 15625 (5**3)**2 = 15625 5**(3**2) = 1953125
Lambdatalk
Because lambdatalk uses prefix notation and {pow a b} accepts only two arguments, it doesn't have an expression for 5**3**2. Just showing expressions for the latter two.
'{pow {pow 5 3} 2}
-> {pow {pow 5 3} 2}
'{pow 5 {pow 3 2}}
-> {pow 5 {pow 3 2}}
Latitude
5 ^ 3 ^ 2. ;; 1953125
(5 ^ 3) ^ 2. ;; 15625
5 ^ (3 ^ 2). ;; 1953125
Lua
print("5^3^2 = " .. 5^3^2)
print("(5^3)^2 = " .. (5^3)^2)
print("5^(3^2) = " .. 5^(3^2))
- Output:
5^3^2 = 1953125 (5^3)^2 = 15625 5^(3^2) = 1953125
Lua also has math.pow(a, b), which is identical to pow(a, b) in C. Since function arguments are contained in brackets anyway, the associativity of nested uses of math.pow will be obvious.
Maple
5^3^2;
(5^3)^2;
5^(3^2);
- Output:
Error, ambiguous use of `^`, please use parentheses 15625 1953125
Mathematica / Wolfram Language
a = "5^3^2";
Print[a <> " = " <> ToString[ToExpression[a]]]
b = "(5^3)^2";
Print[b <> " = " <> ToString[ToExpression[b]]]
c = "5^(3^2)";
Print[c <> " = " <> ToString[ToExpression[c]]]
- Output:
5^3^2 = 1953125 (5^3)^2 = 15625 5^(3^2) = 1953125
min
As with other postfix languages, there is no ambiguity because all operators have the same precedence.
5 3 2 pow pow
"5 3 2 ^ ^ " print! puts!
5 3 pow 2 pow
"5 3 ^ 2 ^ " print! puts!
- Output:
5 3 2 ^ ^ 1953125.0 5 3 ^ 2 ^ 15625.0
Nanoquery
Nanoquery uses the '^' operator, which performs exponentiation in order like multiplication. Parenthesis are often needed to perform operations like 5^3^2 correctly.
% println 5^3^2
15625
% println (5^3)^2
15625
% println 5^(3^2)
1953125
Nim
<Lang Nim>import math, sequtils
echo "5^3^2 = ", 5^3^2 echo "(5^3)^2 = ", (5^3)^2 echo "5^(3^2) = ", 5^(3^2) echo "foldl([5, 3, 2], a^b) = ", foldl([5, 3, 2], a^b) echo "foldr([5, 3, 2], a^b) = ", foldr([5, 3, 2], a^b)</syntaxhighlight>
- Output:
5^3^2 = 1953125 (5^3)^2 = 15625 5^(3^2) = 1953125 foldl([5, 3, 2], a^b) = 15625 foldr([5, 3, 2], a^b) = 1953125
OCaml
OCaml language has '**' as an exponentiation symbol for floating point integers <OCaml code>
- 5. ** 3. ** 2. ;;
- 5. **( 3. ** 2.) ;;
- (5. ** 3. ) **2. ;;
- Output:
- : float = 1953125. - : float = 1953125. - : float = 15625.
PARI/GP
Exponentiation is right-associative in GP.
f(s)=print(s" = "eval(s));
apply(f, ["5^3^2", "(5^3)^2", "5^(3^2)"]);
- Output:
5^3^2 = 1953125 (5^3)^2 = 15625 5^(3^2) = 1953125
Perl
say "$_ = " . eval($_) for qw/5**3**2 (5**3)**2 5**(3**2)/;
- Output:
5**3**2 = 1953125 (5**3)**2 = 15625 5**(3**2) = 1953125
Phix
Phix has a power function rather than an infix power operator, hence there is no possible confusion.
?power(power(5,3),2)
?power(5,power(3,2))
- Output:
15625 1953125
PicoLisp
The PicoLisp '**' exponentiation function takes 2 arguments
: (** (** 5 3) 2)
-> 15625
: (** 5 (** 3 2))
-> 1953125
PL/I
exponentiation: procedure options(main);
put skip edit('5**3**2 = ', 5**3**2) (A,F(7));
put skip edit('(5**3)**2 = ', (5**3)**2) (A,F(7));
put skip edit('5**(3**2) = ', 5**(3**2)) (A,F(7));
end exponentiation;
- Output:
5**3**2 = 15625 (5**3)**2 = 15625 5**(3**2) = 1953125
Python
>>> 5**3**2
1953125
>>> (5**3)**2
15625
>>> 5**(3**2)
1953125
>>> # The following is not normally done
>>> try: from functools import reduce # Py3K
except: pass
>>> reduce(pow, (5, 3, 2))
15625
>>>
Quackery
Quackery uses Reverse Polish Notation, so there is no ambiguity and no need for parenthesising.
As a dialogue in the Quackery Shell…
Welcome to Quackery. Enter "leave" to leave the shell. /O> $ "5 3 2 ** **" dup echo$ say " returns " quackery echo cr ... $ "5 3 ** 2 **" dup echo$ say " returns " quackery echo cr ... 5 3 2 ** ** returns 1953125 5 3 ** 2 ** returns 15625 Stack empty.
R
The 'Operator Syntax and Precedence' documentation tells us that "^" is "exponentiation (right to left)". The 'Arithmetic Operators' documentation also tells us that the parser translates "**" to "^", but its depreciation status is complicated.
It turns out that the parser is so blind to "**" that we cannot even quote it. The following are identical:
print(quote(5**3))
print(quote(5^3))
Another method is to use "^" as if it is an ordinary function of two arguments. It appears that "**" does not support this. As there is no potential for ambiguity in the operator precedence, we will not print this result below. For example:
'^'('^'(5, 3), 2)
is clearly (5^3)^2 i.e. 15625, whereas
'^'(5, '^'(3, 2))
is clearly 5^(3^2) i.e. 1953125.
As for actually solving the task, the requirement that each output be on a new line causes us a surprising amount of difficulty. To avoid repeating ourselves, we must almost resort to metaprogramming:
inputs <- alist(5^3^2, (5^3)^2, 5^(3^2), 5**3**2, (5**3)**2, 5**(3**2))
invisible(sapply(inputs, function(x) cat(deparse(x), "returns: ", eval(x), "\n")))
Alternatively, we could print out a matrix or data frame:
print(matrix(sapply(inputs, eval), dimnames = list(inputs, "Outputs")))
print(data.frame(Inputs = sapply(inputs, deparse), Outputs = sapply(inputs, eval))))
- Output:
> print(quote(5**3)) 5^3 > print(quote(5^3)) 5^3 > invisible(sapply(inputs, function(x) cat(deparse(x), "returns: ", eval(x), "\n"))) 5^3^2 returns: 1953125 (5^3)^2 returns: 15625 5^(3^2) returns: 1953125 5^3^2 returns: 1953125 (5^3)^2 returns: 15625 5^(3^2) returns: 1953125 > print(matrix(sapply(inputs, eval), dimnames = list(inputs, "Outputs"))) Outputs 5^3^2 1953125 (5^3)^2 15625 5^(3^2) 1953125 5^3^2 1953125 (5^3)^2 15625 5^(3^2) 1953125 > print(data.frame(Inputs = sapply(inputs, deparse), Outputs = sapply(inputs, eval))) Inputs Outputs 1 5^3^2 1953125 2 (5^3)^2 15625 3 5^(3^2) 1953125 4 5^3^2 1953125 5 (5^3)^2 15625 6 5^(3^2) 1953125
Racket
#lang racket
;; 5**3**2 depends on associativity of ** : Racket's (scheme's) prefix function
;; calling syntax only allows for pairs of arguments for expt.
;; So no can do for 5**3**2
;; (5**3)**2
(displayln "prefix")
(expt (expt 5 3) 2)
;; (5**3)**2
(expt 5 (expt 3 2))
;; There is also a less-used infix operation (for all functions, not just expt)... which I suppose
;; might do with an airing. But fundamentally nothing changes.
(displayln "\"in\"fix")
((5 . expt . 3) . expt . 2)
(5 . expt . (3 . expt . 2))
;; everyone's doing a reduction, it seems
(displayln "reduction")
(require (only-in srfi/1 reduce reduce-right))
(reduce expt 1 '(5 3 2))
(reduce-right expt 1 '(5 3 2))
- Output:
prefix 15625 1953125 "in"fix 15625 1953125 reduction 14134776518227074636666380005943348126619871175004951664972849610340958208 1953125
Raku
(formerly Perl 6)
Note that the reduction forms automatically go right-to-left because the base operator is right-associative. Most other operators are left-associative and would automatically reduce left-to-right instead.
use MONKEY-SEE-NO-EVAL;
sub demo($x) { say " $x\t───► ", EVAL $x }
demo '5**3**2'; # show ** is right associative
demo '(5**3)**2';
demo '5**(3**2)';
demo '[**] 5,3,2'; # reduction form, show only final result
demo '[\**] 5,3,2'; # triangle reduction, show growing results
# Unicode postfix exponents are supported as well:
demo '(5³)²';
demo '5³²';
- Output:
5**3**2 ───► 1953125 (5**3)**2 ───► 15625 5**(3**2) ───► 1953125 [**] 5,3,2 ───► 1953125 [\**] 5,3,2 ───► 2 9 1953125 (5³)² ───► 15625 5³² ───► 23283064365386962890625
The Unicode exponent form without parentheses ends up raising to the 32nd power. Nor are you even allowed to parenthesize it the other way: 5(³²) would be a syntax error. Despite all that, for programs that do a lot of squaring or cubing, the postfix forms can enhance both readability and concision.
Red
In Red, operators simply evaluate left to right. As this differs from mathematical order of operations, Red provides the math
function which evaluates a block using math rules instead of Red's default evaluation. One could also use the power
function, sidestepping the issue of evaluation order entirely. All three approaches are shown.
Red["Exponentiation order"]
exprs: [
[5 ** 3 ** 2]
[(5 ** 3) ** 2]
[5 ** (3 ** 2)]
[power power 5 3 2] ;-- functions too
[power 5 power 3 2]
]
foreach expr exprs [
print [mold/only expr "=" do expr]
if find expr '** [
print [mold/only expr "=" math expr "using math"]
]
]
- Output:
5 ** 3 ** 2 = 15625 5 ** 3 ** 2 = 1953125 using math (5 ** 3) ** 2 = 15625 (5 ** 3) ** 2 = 15625 using math 5 ** (3 ** 2) = 1953125 5 ** (3 ** 2) = 1953125 using math power power 5 3 2 = 15625 power 5 power 3 2 = 1953125
REXX
/*REXX program demonstrates various ways of multiple exponentiations. */
/*┌────────────────────────────────────────────────────────────────────┐
│ The REXX language uses ** for exponentiation. │
│ Also, * * can be used. │
| and even */*power of*/* |
└────────────────────────────────────────────────────────────────────┘*/
say ' 5**3**2 ───► ' 5**3**2
say ' (5**3)**2 ───► ' (5**3)**2
say ' 5**(3**2) ───► ' 5**(3**2)
/*stick a fork in it, we're done.*/
output
5**3**2 ───► 15625 (5**3)**2 ───► 15625 5**(3**2) ───► 1953125
Ring
In the Ring it is impossible to show the result of: 5^3^2
see "(5^3)^2 =>" + pow(pow(5,3),2) + nl
see "5^(3^2) =>" + pow(5,pow(3,2)) + nl
Output:
(5^3)^2 =>15625 5^(3^2) =>1953125
Ruby
ar = ["5**3**2", "(5**3)**2", "5**(3**2)", "[5,3,2].inject(:**)"]
ar.each{|exp| puts "#{exp}:\t#{eval exp}"}
- Output:
5**3**2: 1953125 (5**3)**2: 15625 5**(3**2): 1953125 [5,3,2].inject(:**): 15625
Rust
fn main() {
println!("5**3**2 = {:7}", 5u32.pow(3).pow(2));
println!("(5**3)**2 = {:7}", (5u32.pow(3)).pow(2));
println!("5**(3**2) = {:7}", 5u32.pow(3u32.pow(2)));
}
- Output:
5**3**2 = 15625 (5**3)**2 = 15625 5**(3**2) = 1953125
Scala
Scal has no exponentiation operator, but uses the function (scala.)math.pow(x: Double, y: Double): Double function in the Scala runtime library.
Integer exponentiation can be done with e.g. BigInt or BigInteger.pow(n: Int) method.
There are no associativity issues.
Seed7
$ include "seed7_05.s7i";
const proc: main is func
begin
writeln("5**3**2 = " <& 5**3**2);
writeln("(5**3)**2 = " <& (5**3)**2);
writeln("5**(3**2) = " <& 5**(3**2));
end func;
- Output:
5**3**2 = 1953125 (5**3)**2 = 15625 5**(3**2) = 1953125
Sidef
In Sidef, the whitespace between the operands and the operator controls the precedence of the operation.
var a = [
'5**3**2',
'(5**3)**2',
'5**(3**2)',
'5 ** 3 ** 2',
'5 ** 3**2',
'5**3 ** 2',
'[5,3,2]«**»',
]
a.each {|e|
"%-12s == %s\n".printf(e, eval(e))
}
- Output:
5**3**2 == 1953125 (5**3)**2 == 15625 5**(3**2) == 1953125 5 ** 3 ** 2 == 15625 5 ** 3**2 == 1953125 5**3 ** 2 == 15625 [5,3,2]«**» == 15625
Simula
OutText("5** 3 **2: "); OutInt(5** 3 **2, 0); Outimage;
OutText("(5**3)**2: "); OutInt((5**3)**2, 0); Outimage;
OutText("5**(3**2): "); OutInt(5**(3**2), 0); Outimage
- Output:
5** 3 **2: 15625 (5**3)**2: 15625 5**(3**2): 1953125
Smalltalk
Works in Smalltalk/X ¹
Smalltalk strictly evaluates left to right; operators are not known to the language/parser, but instead message sends to the receiver on the left side (aka: virtual function calls) .
Transcript show:'5**3**2 => '; showCR: 5**3**2.
Transcript show:'(5**3)**2 => '; showCR: (5**3)**2.
Transcript show:'5**(3**2) => '; showCR: 5**(3**2).
- Output:
5**(3**2) => 1953125 5**3**2 => 15625 (5**3)**2 => 15625
Note ¹ other Smalltalk's may define ** to simply call "raisedTo:", which is standard.
Stata
. di (5^3^2)
15625
. di ((5^3)^2)
15625
. di (5^(3^2))
1953125
Likewise in Mata:
. mata (5^3^2)
15625
. mata ((5^3)^2)
15625
. mata (5^(3^2))
1953125
Swift
Swift doesn't have an exponentiation operator, however it's possible to define one, including the precedence and associativity.
precedencegroup ExponentiationPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator ** : ExponentiationPrecedence
@inlinable
public func ** <T: BinaryInteger>(lhs: T, rhs: T) -> T {
guard lhs != 0 else {
return 1
}
var x = lhs
var n = rhs
var y = T(1)
while n > 1 {
switch n & 1 {
case 0:
n /= 2
case 1:
y *= x
n = (n - 1) / 2
case _:
fatalError()
}
x *= x
}
return x * y
}
print(5 ** 3 ** 2)
print((5 ** 3) ** 2)
print(5 ** (3 ** 2))
- Output:
15625 15625 1953125
Tcl
foreach expression {5**3**2 (5**3)**2 5**(3**2)} {
puts "${expression}:\t[expr $expression]"
}
- Output:
5**3**2: 1953125 (5**3)**2: 15625 5**(3**2): 1953125
There's also a binary pow()
expression function that always converts its arguments to floating point numbers and then applies the exponentiation operation; it's now largely obsolete because of the **
operator, but is retained for backward compatibility with older programs.
VBA
Public Sub exp()
Debug.Print "5^3^2", 5 ^ 3 ^ 2
Debug.Print "(5^3)^2", (5 ^ 3) ^ 2
Debug.Print "5^(3^2)", 5 ^ (3 ^ 2)
End Sub
- Output:
5^3^2 15625 (5^3)^2 15625 5^(3^2) 1953125
VBScript
WScript.StdOut.WriteLine "5^3^2 => " & 5^3^2
WScript.StdOut.WriteLine "(5^3)^2 => " & (5^3)^2
WScript.StdOut.WriteLine "5^(3^2) => " & 5^(3^2)
- Output:
5^3^2 => 15625 (5^3)^2 => 15625 5^(3^2) => 1953125
Verbexx
// Exponentiation order example:
@SAY "5**3**2 = " ( 5**3**2 );
@SAY "(5**3)**2 = " ( (5**3)**2 );
@SAY "5**(3**2) = " ( 5**(3**2) );
/] Output:
5**3**2 = 1953125
(5**3)**2 = 15625
5**(3**2) = 1953125
Wren
Wren doesn't have an exponentiation operator as such but the Num class has a pow method which does the same thing.
import "/fmt" for Fmt
var ops = [ "5**3**2", "(5**3)**2", "5**(3**2)" ]
var results = [ 5.pow(3).pow(2), (5.pow(3)).pow(2), 5.pow(3.pow(2)) ]
for (i in 0...ops.count) {
System.print("%(Fmt.s(-9, ops[i])) -> %(results[i])")
}
- Output:
5**3**2 -> 15625 (5**3)**2 -> 15625 5**(3**2) -> 1953125
zkl
zkl does not have an exponentiation operator but floats have a pow method.
println("5 ^ 3 ^ 2 = %,d".fmt((5.0).pow((3.0).pow(2))));
println("(5 ^ 3) ^ 2 = %,d".fmt((5.0).pow(3).pow(2)));
println("5 ^ (3 ^ 2) = %,d".fmt((5.0).pow((3.0).pow(2))));
- Output:
5 ^ 3 ^ 2 = 1,953,125 (5 ^ 3) ^ 2 = 15,625 5 ^ (3 ^ 2) = 1,953,125
- Programming Tasks
- Solutions by Programming Task
- 11l
- Action!
- Action! Tool Kit
- Ada
- ALGOL 68
- ALGOL W
- APL
- AppleScript
- Arturo
- AWK
- BASIC
- Sinclair ZX81 BASIC
- BBC BASIC
- IS-BASIC
- QBasic
- BASIC256
- Run BASIC
- True BASIC
- Yabasic
- Bracmat
- C
- C++
- C sharp
- Clojure
- CLU
- Common Lisp
- D
- EchoLisp
- Factor
- Fortran
- FreeBASIC
- Frink
- Go
- Groovy
- Haskell
- Io
- J
- Java
- Jq
- Julia
- Kotlin
- Lambdatalk
- Latitude
- Lua
- Maple
- Mathematica
- Wolfram Language
- Min
- Nanoquery
- Nim
- OCaml
- PARI/GP
- Perl
- Phix
- Phix/basics
- PicoLisp
- PL/I
- Python
- Quackery
- R
- Racket
- Raku
- Red
- REXX
- Ring
- Ruby
- Rust
- Scala
- Seed7
- Sidef
- Simula
- Smalltalk
- Stata
- Swift
- Tcl
- VBA
- VBScript
- Verbexx
- Wren
- Wren-fmt
- Zkl