task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#C
C
  #include<graphics.h> #include<stdio.h> #include<math.h>   #define pi M_PI   int main(){ double a,b,cycles,incr,i;   int steps,x=500,y=500;   printf("Enter the parameters a and b : "); scanf("%lf%lf",&a,&b);   printf("Enter cycles : "); scanf("%lf",&cycles);   printf("Enter divisional steps : "); scanf("%d",&steps);   incr = 1.0/steps;   initwindow(1000,1000,"Archimedean Spiral");   for(i=0;i<=cycles*pi;i+=incr){ putpixel(x + (a + b*i)*cos(i),x + (a + b*i)*sin(i),15); }   getch();   closegraph(); }  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Aikido
Aikido
  var doors = new int [100]   foreach pass 100 { for (var door = pass ; door < 100 ; door += pass+1) { doors[door] = !doors[door] } }   var d = 1 foreach door doors { println ("door " + d++ + " is " + (door ? "open" : "closed"))   }    
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#BQN
BQN
# Stranding: arr ← 1‿2‿'a'‿+‿5 # General List Syntax: arr1 ← ⟨1,2,'a',+,5⟩ •Show arr ≡ arr1 # both arrays are the same. •Show arr •Show arr1   # Taking nth element(⊑): •Show 3⊑arr   # Modifying the array(↩): arr ↩ "hello"⌾(4⊸⊑) arr
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Forth
Forth
S" fsl-util.fs" REQUIRED S" complex.fs" REQUIRED   zvariable x zvariable y 1e 1e x z! pi 1.2e y z!   x z@ y z@ z+ z. x z@ y z@ z* z. 1e 0e zconstant 1+0i 1+0i x z@ z/ z. x z@ znegate z.
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Go
Go
package main   import ( "fmt" "math" "math/big" )   func main() { var recip big.Rat max := int64(1 << 19) for candidate := int64(2); candidate < max; candidate++ { sum := big.NewRat(1, candidate) max2 := int64(math.Sqrt(float64(candidate))) for factor := int64(2); factor <= max2; factor++ { if candidate%factor == 0 { sum.Add(sum, recip.SetFrac64(1, factor)) if f2 := candidate / factor; f2 != factor { sum.Add(sum, recip.SetFrac64(1, f2)) } } } if sum.Denom().Int64() == 1 { perfectstring := "" if sum.Num().Int64() == 1 { perfectstring = "perfect!" } fmt.Printf("Sum of recipr. factors of %d = %d exactly %s\n", candidate, sum.Num().Int64(), perfectstring) } } }
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#jq
jq
def naive_agm(a; g; tolerance): def abs: if . < 0 then -. else . end; def _agm: # state [an,gn] if ((.[0] - .[1])|abs) > tolerance then [add/2, ((.[0] * .[1])|sqrt)] | _agm else . end; [a, g] | _agm | .[0] ;
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Julia
Julia
function agm(x, y, e::Real = 5) (x ≤ 0 || y ≤ 0 || e ≤ 0) && throw(DomainError("x, y must be strictly positive")) g, a = minmax(x, y) while e * eps(x) < a - g a, g = (a + g) / 2, sqrt(a * g) end a end   x, y = 1.0, 1 / √2 println("# Using literal-precision float numbers:") @show agm(x, y)   println("# Using half-precision float numbers:") x, y = Float32(x), Float32(y) @show agm(x, y)   println("# Using ", precision(BigFloat), "-bit float numbers:") x, y = big(1.0), 1 / √big(2.0) @show agm(x, y)
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Get two integers from the user,   and then (for those two integers), display their:   sum   difference   product   integer quotient   remainder   exponentiation   (if the operator exists) Don't include error handling. For quotient, indicate how it rounds   (e.g. towards zero, towards negative infinity, etc.). For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
#ZX_Spectrum_Basic
ZX Spectrum Basic
5 LET a=5: LET b=3 10 PRINT a;" + ";b;" = ";a+b 20 PRINT a;" - ";b;" = ";a-b 30 PRINT a;" * ";b;" = ";a*b 40 PRINT a;" / ";b;" = ";INT (a/b) 50 PRINT a;" mod ";b;" = ";a-INT (a/b)*b 60 PRINT a;" to the power of ";b;" = ";a^b  
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Elena
Elena
import system'routines; import extensions; import extensions'text;   class Token { object theValue;   rprop int Level;   constructor new(int level) { theValue := new StringWriter(); Level := level + 9; }   append(ch) { theValue.write(ch) }   Number = theValue.toReal(); }   class Node { prop object Left; prop object Right; rprop int Level;   constructor new(int level) { Level := level } }   class SummaryNode : Node { constructor new(int level) <= new(level + 1);   Number = Left.Number + Right.Number; }   class DifferenceNode : Node { constructor new(int level) <= new(level + 1);   Number = Left.Number - Right.Number; }   class ProductNode : Node { constructor new(int level) <= new(level + 2);   Number = Left.Number * Right.Number; }   class FractionNode : Node { constructor new(int level) <= new(level + 2);   Number = Left.Number / Right.Number; }   class Expression { rprop int Level; prop object Top;   constructor new(int level) { Level := level }   Right { get() = Top;   set(object node) { Top := node } }   get Number() => Top; }   singleton operatorState { eval(ch) { ch => $40 { // ( ^ __target.newBracket().gotoStarting() }  : { ^ __target.newToken().append(ch).gotoToken() } } }   singleton tokenState { eval(ch) { ch => $41 { // ) ^ __target.closeBracket().gotoToken() } $42 { // * ^ __target.newProduct().gotoOperator() } $43 { // + ^ __target.newSummary().gotoOperator() } $45 { // - ^ __target.newDifference().gotoOperator() } $47 { // / ^ __target.newFraction().gotoOperator() }  : { ^ __target.append:ch } } }   singleton startState { eval(ch) { ch => $40 { // ( ^ __target.newBracket().gotoStarting() } $45 { // - ^ __target.newToken().append("0").newDifference().gotoOperator() }  : { ^ __target.newToken().append:ch.gotoToken() } } }   class Scope { object theState; int theLevel; object theParser; object theToken; object theExpression;   constructor new(parser) { theState := startState; theLevel := 0; theExpression := Expression.new(0); theParser := parser }   newToken() { theToken := theParser.appendToken(theExpression, theLevel) }   newSummary() { theToken := nil;   theParser.appendSummary(theExpression, theLevel) }   newDifference() { theToken := nil;   theParser.appendDifference(theExpression, theLevel) }   newProduct() { theToken := nil;   theParser.appendProduct(theExpression, theLevel) }   newFraction() { theToken := nil;   theParser.appendFraction(theExpression, theLevel) }   newBracket() { theToken := nil;   theLevel := theLevel + 10;   theParser.appendSubexpression(theExpression, theLevel) }   closeBracket() { if (theLevel < 10) { InvalidArgumentException.new:"Invalid expression".raise() };   theLevel := theLevel - 10 }   append(ch) { if(ch >= $48 && ch < $58) { theToken.append:ch } else { InvalidArgumentException.new:"Invalid expression".raise() } }   append(string s) { s.forEach:(ch){ self.append:ch } }   gotoStarting() { theState := startState }   gotoToken() { theState := tokenState }   gotoOperator() { theState := operatorState }   get Number() => theExpression;   dispatch() => theState; }   class Parser { appendToken(object expression, int level) { var token := Token.new(level);   expression.Top := self.append(expression.Top, token);   ^ token }   appendSummary(object expression, int level) { expression.Top := self.append(expression.Top, SummaryNode.new(level)) }   appendDifference(object expression, int level) { expression.Top := self.append(expression.Top, DifferenceNode.new(level)) }   appendProduct(object expression, int level) { expression.Top := self.append(expression.Top, ProductNode.new(level)) }   appendFraction(object expression, int level) { expression.Top := self.append(expression.Top, FractionNode.new(level)) }   appendSubexpression(object expression, int level) { expression.Top := self.append(expression.Top, Expression.new(level)) }   append(lastNode, newNode) { if(nil == lastNode) { ^ newNode };   if (newNode.Level <= lastNode.Level) { newNode.Left := lastNode; ^ newNode };   var parent := lastNode; var current := lastNode.Right; while (nil != current && newNode.Level > current.Level) { parent := current; current := current.Right };   if (nil == current) { parent.Right := newNode } else { newNode.Left := current; parent.Right := newNode };   ^ lastNode }   run(text) { var scope := Scope.new(self);   text.forEach:(ch){ scope.eval:ch };   ^ scope.Number } }   public program() { var text := new StringWriter(); var parser := new Parser();   while (console.readLine().saveTo(text).Length > 0) { try { console.printLine("=",parser.run:text) } catch(Exception e) { console.writeLine:"Invalid Expression" };   text.clear() } }
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#C.23
C#
using System; using System.Linq; using System.Drawing; using System.Diagnostics; using System.Drawing.Drawing2D;   class Program { const int width = 380; const int height = 380; static PointF archimedeanPoint(int degrees) { const double a = 1; const double b = 9; double t = degrees * Math.PI / 180; double r = a + b * t; return new PointF { X = (float)(width / 2 + r * Math.Cos(t)), Y = (float)(height / 2 + r * Math.Sin(t)) }; }   static void Main(string[] args) { var bm = new Bitmap(width, height); var g = Graphics.FromImage(bm); g.SmoothingMode = SmoothingMode.AntiAlias; g.FillRectangle(new SolidBrush(Color.White), new Rectangle { X = 0, Y = 0, Width = width, Height = height }); var pen = new Pen(Color.OrangeRed, 1.5f);   var spiral = Enumerable.Range(0, 360 * 3).AsParallel().AsOrdered().Select(archimedeanPoint); var p0 = new PointF(width / 2, height / 2); foreach (var p1 in spiral) { g.DrawLine(pen, p0, p1); p0 = p1; } g.Save(); // is this really necessary ? bm.Save("archimedes-csharp.png"); Process.Start("archimedes-csharp.png"); // Launches default photo viewing app } }  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#ALGOL_60
ALGOL 60
  begin   comment - 100 doors problem in ALGOL-60;   boolean array doors[1:100]; integer i, j; boolean open, closed;   open := true; closed := not true;   outstring(1,"100 Doors Problem\n");   comment - all doors are initially closed; for i := 1 step 1 until 100 do doors[i] := closed;   comment cycle through at increasing intervals and flip each door encountered; for i := 1 step 1 until 100 do for j := i step i until 100 do doors[j] := not doors[j];   comment - show which doors are open; outstring(1,"The open doors are:"); for i := 1 step 1 until 100 do if doors[i] then outinteger(1,i);   end  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Bracmat
Bracmat
( tbl$(mytable,100) & 5:?(30$mytable) & 9:?(31$mytable) & out$(!(30$mytable)) & out$(!(-169$mytable)) { -169 mod 100 == 31 } & out$!mytable { still index 31 } & tbl$(mytable,0) & (!mytable & out$"mytable still exists" | out$"mytable is gone" ) );
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Fortran
Fortran
program cdemo complex :: a = (5,3), b = (0.5, 6.0) ! complex initializer complex :: absum, abprod, aneg, ainv   absum = a + b abprod = a * b aneg = -a ainv = 1.0 / a end program cdemo
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Groovy
Groovy
class Rational extends Number implements Comparable { final BigInteger num, denom   static final Rational ONE = new Rational(1) static final Rational ZERO = new Rational(0)   Rational(BigDecimal decimal) { this( decimal.scale() < 0 ? decimal.unscaledValue() * 10 ** -decimal.scale() : decimal.unscaledValue(), decimal.scale() < 0 ? 1  : 10 ** decimal.scale() ) }   Rational(BigInteger n, BigInteger d = 1) { if (!d || n == null) { n/d } (num, denom) = reduce(n, d) }   private List reduce(BigInteger n, BigInteger d) { BigInteger sign = ((n < 0) ^ (d < 0)) ? -1 : 1 (n, d) = [n.abs(), d.abs()] BigInteger commonFactor = gcd(n, d)   [n.intdiv(commonFactor) * sign, d.intdiv(commonFactor)] }   Rational toLeastTerms() { reduce(num, denom) as Rational }   private BigInteger gcd(BigInteger n, BigInteger m) { n == 0 ? m : { while(m%n != 0) { (n, m) = [m%n, n] }; n }() }   Rational plus(Rational r) { [num*r.denom + r.num*denom, denom*r.denom] } Rational plus(BigInteger n) { [num + n*denom, denom] } Rational plus(Number n) { this + ([n] as Rational) }   Rational next() { [num + denom, denom] }   Rational minus(Rational r) { [num*r.denom - r.num*denom, denom*r.denom] } Rational minus(BigInteger n) { [num - n*denom, denom] } Rational minus(Number n) { this - ([n] as Rational) }   Rational previous() { [num - denom, denom] }   Rational multiply(Rational r) { [num*r.num, denom*r.denom] } Rational multiply(BigInteger n) { [num*n, denom] } Rational multiply(Number n) { this * ([n] as Rational) }     Rational div(Rational r) { new Rational(num*r.denom, denom*r.num) } Rational div(BigInteger n) { new Rational(num, denom*n) } Rational div(Number n) { this / ([n] as Rational) }   BigInteger intdiv(BigInteger n) { num.intdiv(denom*n) }   Rational negative() { [-num, denom] }   Rational abs() { [num.abs(), denom] }   Rational reciprocal() { new Rational(denom, num) }   Rational power(BigInteger n) { def (nu, de) = (n < 0 ? [denom, num] : [num, denom])*.power(n.abs()) new Rational (nu, de) }   boolean asBoolean() { num != 0 }   BigDecimal toBigDecimal() { (num as BigDecimal)/(denom as BigDecimal) }   BigInteger toBigInteger() { num.intdiv(denom) }   Double toDouble() { toBigDecimal().toDouble() } double doubleValue() { toDouble() as double }   Float toFloat() { toBigDecimal().toFloat() } float floatValue() { toFloat() as float }   Integer toInteger() { toBigInteger().toInteger() } int intValue() { toInteger() as int }   Long toLong() { toBigInteger().toLong() } long longValue() { toLong() as long }   Object asType(Class type) { switch (type) { case this.class: return this case [Boolean, Boolean.TYPE]: return asBoolean() case BigDecimal: return toBigDecimal() case BigInteger: return toBigInteger() case [Double, Double.TYPE]: return toDouble() case [Float, Float.TYPE]: return toFloat() case [Integer, Integer.TYPE]: return toInteger() case [Long, Long.TYPE]: return toLong() case String: return toString() default: throw new ClassCastException("Cannot convert from type Rational to type " + type) } }   boolean equals(o) { compareTo(o) == 0 }   int compareTo(o) { o instanceof Rational ? compareTo(o as Rational)  : o instanceof Number ? compareTo(o as Number)  : (Double.NaN as int) } int compareTo(Rational r) { num*r.denom <=> denom*r.num } int compareTo(Number n) { num <=> denom*(n as BigInteger) }   int hashCode() { [num, denom].hashCode() }   String toString() { "${num}//${denom}" } }
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Klingphix
Klingphix
include ..\Utilitys.tlhy   :agm [ over over + 2 / rot rot * sqrt ] [ over over tostr swap tostr # ] while drop ;   1 1 2 sqrt / agm   pstack   " " input
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Kotlin
Kotlin
// version 1.0.5-2   fun agm(a: Double, g: Double): Double { var aa = a // mutable 'a' var gg = g // mutable 'g' var ta: Double // temporary variable to hold next iteration of 'aa' val epsilon = 1.0e-16 // tolerance for checking if limit has been reached   while (true) { ta = (aa + gg) / 2.0 if (Math.abs(aa - ta) <= epsilon) return ta gg = Math.sqrt(aa * gg) aa = ta } }   fun main(args: Array<String>) { println(agm(1.0, 1.0 / Math.sqrt(2.0))) }
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Emacs_Lisp
Emacs Lisp
#!/usr/bin/env emacs --script ;; -*- mode: emacs-lisp; lexical-binding: t -*- ;;> ./arithmetic-evaluation '(1 + 2) * 3'   (defun advance () (let ((rtn (buffer-substring-no-properties (point) (match-end 0)))) (goto-char (match-end 0)) rtn))   (defvar current-symbol nil)   (defun next-symbol () (when (looking-at "[ \t\n]+") (goto-char (match-end 0)))   (cond ((eobp) (setq current-symbol 'eof)) ((looking-at "[0-9]+") (setq current-symbol (string-to-number (advance)))) ((looking-at "[-+*/()]") (setq current-symbol (advance))) ((looking-at ".") (error "Unknown character '%s'" (advance)))))   (defun accept (sym) (when (equal sym current-symbol) (next-symbol) t))   (defun expect (sym) (unless (accept sym) (error "Expected symbol %s, but found %s" sym current-symbol)) t)   (defun p-expression () " expression = term { ('+' | '-') term } . " (let ((rtn (p-term))) (while (or (equal current-symbol "+") (equal current-symbol "-")) (let ((op current-symbol) (left rtn)) (next-symbol) (setq rtn (list op left (p-term))))) rtn))   (defun p-term () " term = factor { ('*' | '/') factor } . " (let ((rtn (p-factor))) (while (or (equal current-symbol "*") (equal current-symbol "/")) (let ((op current-symbol) (left rtn)) (next-symbol) (setq rtn (list op left (p-factor))))) rtn))   (defun p-factor () " factor = constant | variable | '(' expression ')' . " (let (rtn) (cond ((numberp current-symbol) (setq rtn current-symbol) (next-symbol)) ((accept "(") (setq rtn (p-expression)) (expect ")")) (t (error "Syntax error"))) rtn))   (defun ast-build (expression) (let (rtn) (with-temp-buffer (insert expression) (goto-char (point-min)) (next-symbol) (setq rtn (p-expression)) (expect 'eof)) rtn))   (defun ast-eval (v) (pcase v ((pred numberp) v) (`("+" ,a ,b) (+ (ast-eval a) (ast-eval b))) (`("-" ,a ,b) (- (ast-eval a) (ast-eval b))) (`("*" ,a ,b) (* (ast-eval a) (ast-eval b))) (`("/" ,a ,b) (/ (ast-eval a) (float (ast-eval b)))) (_ (error "Unknown value %s" v))))   (dolist (arg command-line-args-left) (let ((ast (ast-build arg))) (princ (format " ast = %s\n" ast)) (princ (format " value = %s\n" (ast-eval ast))) (terpri))) (setq command-line-args-left nil)  
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <iostream>   const int BMP_SIZE = 600;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class spiral { public: spiral() { bmp.create( BMP_SIZE, BMP_SIZE ); } void draw( int c, int s ) { double a = .2, b = .3, r, x, y; int w = BMP_SIZE >> 1; HDC dc = bmp.getDC(); for( double d = 0; d < c * 6.28318530718; d += .002 ) { r = a + b * d; x = r * cos( d ); y = r * sin( d ); SetPixel( dc, ( int )( s * x + w ), ( int )( s * y + w ), 255 ); } // saves the bitmap bmp.saveBitmap( "./spiral.bmp" ); } private: myBitmap bmp; }; int main(int argc, char* argv[]) { spiral s; s.draw( 16, 8 ); return 0; }  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#ALGOL_68
ALGOL 68
# declare some constants # INT limit = 100;   PROC doors = VOID: ( MODE DOORSTATE = BOOL; BOOL closed = FALSE; BOOL open = NOT closed; MODE DOORLIST = [limit]DOORSTATE;   DOORLIST the doors; FOR i FROM LWB the doors TO UPB the doors DO the doors[i]:=closed OD;   FOR i FROM LWB the doors TO UPB the doors DO FOR j FROM LWB the doors TO UPB the doors DO IF j MOD i = 0 THEN the doors[j] := NOT the doors[j] FI OD OD; FOR i FROM LWB the doors TO UPB the doors DO printf(($g" is "gl$,i,(the doors[i]|"opened"|"closed"))) OD ); doors;
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Brainf.2A.2A.2A
Brainf***
  ===========[ ARRAY DATA STRUCTURE   AUTHOR: Keith Stellyes WRITTEN: June 2016   This is a zero-based indexing array data structure, it assumes the following precondition:   >INDEX<|NULL|VALUE|NULL|VALUE|NULL|VALUE|NULL   (Where >< mark pointer position, and | separates addresses)   It relies heavily on [>] and [<] both of which are idioms for finding the next left/right null   HOW INDEXING WORKS: It runs a loop _index_ number of times, setting that many nulls to a positive, so it can be skipped by the mentioned idioms. Basically, it places that many "milestones".   EXAMPLE: If we seek index 2, and our array is {1 , 2 , 3 , 4 , 5}   FINDING INDEX 2: (loop to find next null, set to positive, as a milestone decrement index)   index 2 |0|1|0|2|0|3|0|4|0|5|0 1 |0|1|1|2|0|3|0|4|0|5|0 0 |0|1|1|2|1|3|0|4|0|5|0   ===========]   =======UNIT TEST======= SET ARRAY {48 49 50} >>++++++++++++++++++++++++++++++++++++++++++++++++>> +++++++++++++++++++++++++++++++++++++++++++++++++>> ++++++++++++++++++++++++++++++++++++++++++++++++++ <<<<<<++ Move back to index and set it to 2 =======================   ===RETRIEVE ELEMENT AT INDEX===   =ACCESS INDEX= [>>[>]+[<]<-] loop that sets a null to a positive for each iteration First it moves the pointer from index to first value Then it uses a simple loop that finds the next null it sets the null to a positive (1 in this case) Then it uses that same loop reversed to find the first null which will always be one right of our index so we decrement our index Finally we decrement pointer from the null byte to our index and decrement it   >> Move pointer to the first value otherwise we can't loop   [>]< This will find the next right null which will always be right of the desired value; then go one left     . Output the value (In the unit test this print "2"   [<[-]<] Reset array   ===ASSIGN VALUE AT INDEX===   STILL NEED TO ADJUST UNIT TESTS   NEWVALUE|>INDEX<|NULL|VALUE etc   [>>[>]+[<]<-] Like above logic except it empties the value and doesn't reset >>[>]<[-]   [<]< Move pointer to desired value note that where the index was stored is null because of the above loop   [->>[>]+[<]<] If NEWVALUE is GREATER than 0 then decrement it & then find the newly emptied cell and increment it   [>>[>]<+[<]<<-] Move pointer to first value find right null move pointer left then increment where we want our NEWVALUE to be stored then return back by finding leftmost null then decrementing pointer twice then decrement our NEWVALUE cell  
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type Complex As Double real, imag Declare Constructor(real As Double, imag As Double) Declare Function invert() As Complex Declare Function conjugate() As Complex Declare Operator cast() As String End Type   Constructor Complex(real As Double, imag As Double) This.real = real This.imag = imag End Constructor   Function Complex.invert() As Complex Dim denom As Double = real * real + imag * imag Return Complex(real / denom, -imag / denom) End Function   Function Complex.conjugate() As Complex Return Complex(real, -imag) End Function   Operator Complex.Cast() As String If imag >= 0 Then Return Str(real) + "+" + Str(imag) + "j" End If Return Str(real) + Str(imag) + "j" End Operator   Operator - (c As Complex) As Complex Return Complex(-c.real, -c.imag) End Operator   Operator + (c1 As Complex, c2 As Complex) As Complex Return Complex(c1.real + c2.real, c1.imag + c2.imag) End Operator   Operator - (c1 As Complex, c2 As Complex) As Complex Return c1 + (-c2) End Operator   Operator * (c1 As Complex, c2 As Complex) As Complex Return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c2.real * c1.imag) End Operator   Operator / (c1 As Complex, c2 As Complex) As Complex Return c1 * c2.invert End Operator   Var x = Complex(1, 3) Var y = Complex(5, 2) Print "x = "; x Print "y = "; y Print "x + y = "; x + y Print "x - y = "; x - y Print "x * y = "; x * y Print "x / y = "; x / y Print "-x = "; -x Print "1 / x = "; x.invert Print "x* = "; x.conjugate Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Haskell
Haskell
import Data.Ratio ((%))   -- Prints the first N perfect numbers. main = do let n = 4 mapM_ print $ take n [ candidate | candidate <- [2 .. 2 ^ 19] , getSum candidate == 1 ] where getSum candidate = 1 % candidate + sum [ 1 % factor + 1 % (candidate `div` factor) | factor <- [2 .. floor (sqrt (fromIntegral candidate))] , candidate `mod` factor == 0 ]  
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#LFE
LFE
  (defun agm (a g) (agm a g 1.0e-15))   (defun agm (a g tol) (if (=< (- a g) tol) a (agm (next-a a g) (next-g a g) tol)))   (defun next-a (a g) (/ (+ a g) 2))   (defun next-g (a g) (math:sqrt (* a g)))  
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Liberty_BASIC
Liberty BASIC
  print agm(1, 1/sqr(2)) print using("#.#################",agm(1, 1/sqr(2)))   function agm(a,g) do absdiff = abs(a-g) an=(a+g)/2 gn=sqr(a*g) a=an g=gn loop while abs(an-gn)< absdiff agm = a end function    
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#ERRE
ERRE
  PROGRAM EVAL   ! ! arithmetic expression evaluator !   !$KEY   LABEL 98,100,110   DIM STACK$[50]   PROCEDURE DISEGNA_STACK  !$RCODE="LOCATE 3,1"  !$RCODE="COLOR 0,7" PRINT(TAB(35);"S T A C K";TAB(79);)  !$RCODE="COLOR 7,0" FOR TT=1 TO 38 DO IF TT>=20 THEN  !$RCODE="LOCATE 3+TT-19,40" ELSE  !$RCODE="LOCATE 3+TT,1" END IF IF TT=NS THEN PRINT(">";) ELSE PRINT(" ";) END IF PRINT(RIGHT$(STR$(TT),2);"³ ";STACK$[TT];" ") END FOR REPEAT GET(Z$) UNTIL LEN(Z$)<>0 END PROCEDURE   PROCEDURE COMPATTA_STACK IF NS>1 THEN R=1 WHILE R<NS DO IF INSTR(OP_LIST$,STACK$[R])=0 AND INSTR(OP_LIST$,STACK$[R+1])=0 THEN FOR R1=R TO NS-1 DO STACK$[R1]=STACK$[R1+1] END FOR NS=NS-1 END IF R=R+1 END WHILE END IF DISEGNA_STACK END PROCEDURE   PROCEDURE CALC_ARITM L=NS1 WHILE L<=NS2 DO IF STACK$[L]="^" THEN IF L>=NS2 THEN GOTO 100 END IF N1#=VAL(STACK$[L-1]) N2#=VAL(STACK$[L+1]) NOP=NOP-1 IF STACK$[L]="^" THEN RI#=N1#^N2# END IF STACK$[L-1]=STR$(RI#) N=L WHILE N<=NS2-2 DO STACK$[N]=STACK$[N+2] N=N+1 END WHILE NS2=NS2-2 L=NS1-1 END IF L=L+1 END WHILE   L=NS1 WHILE L<=NS2 DO IF STACK$[L]="*" OR STACK$[L]="/" THEN IF L>=NS2 THEN GOTO 100 END IF N1#=VAL(STACK$[L-1]) N2#=VAL(STACK$[L+1]) NOP=NOP-1 IF STACK$[L]="*" THEN RI#=N1#*N2# ELSE RI#=N1#/N2# END IF STACK$[L-1]=STR$(RI#) N=L WHILE N<=NS2-2 DO STACK$[N]=STACK$[N+2] N=N+1 END WHILE NS2=NS2-2 L=NS1-1 END IF L=L+1 END WHILE   L=NS1 WHILE L<=NS2 DO IF STACK$[L]="+" OR STACK$[L]="-" THEN EXIT IF L>=NS2 N1#=VAL(STACK$[L-1]) N2#=VAL(STACK$[L+1]) NOP=NOP-1 IF STACK$[L]="+" THEN RI#=N1#+N2# ELSE RI#=N1#-N2# END IF STACK$[L-1]=STR$(RI#) N=L WHILE N<=NS2-2 DO STACK$[N]=STACK$[N+2] N=N+1 END WHILE NS2=NS2-2 L=NS1-1 END IF L=L+1 END WHILE 100: IF NOP<2 THEN  ! operator priority DB#=VAL(STACK$[NS1]) ELSE IF NOP<3 THEN DB#=VAL(STACK$[NS1+2]) ELSE DB#=VAL(STACK$[NS1+4]) END IF END IF END PROCEDURE   PROCEDURE SVOLGI_PAR NPA=NPA-1 FOR J=NS TO 1 STEP -1 DO EXIT IF STACK$[J]="(" END FOR IF J=0 THEN NS1=1 NS2=NS CALC_ARITM NERR=7 ELSE FOR R=J TO NS-1 DO STACK$[R]=STACK$[R+1] END FOR NS1=J NS2=NS-1 CALC_ARITM IF NS1=2 THEN NS1=1 STACK$[1]=STACK$[2] END IF NS=NS1 COMPATTA_STACK END IF END PROCEDURE   BEGIN OP_LIST$="+-*/^(" NOP=0 NPA=0 NS=1 K$="" STACK$[1]="@"  ! init stack   PRINT(CHR$(12);) INPUT(LINE,EXPRESSION$)   FOR W=1 TO LEN(EXPRESSION$) DO LOOP CODE=ASC(MID$(EXPRESSION$,W,1)) IF (CODE>=48 AND CODE<=57) OR CODE=46 THEN K$=K$+CHR$(CODE) W=W+1 IF W>LEN(EXPRESSION$) THEN GOTO 98 END IF ELSE EXIT IF K$="" IF NS>1 OR (NS=1 AND STACK$[1]<>"@") THEN NS=NS+1 END IF IF FLAG=0 THEN STACK$[NS]=K$ ELSE STACK$[NS]=STR$(VAL(K$)*FLAG) END IF K$="" FLAG=0 EXIT END IF END LOOP IF CODE=43 THEN K$="+" END IF IF CODE=45 THEN K$="-" END IF IF CODE=42 THEN K$="*" END IF IF CODE=47 THEN K$="/" END IF IF CODE=94 THEN K$="^" END IF   CASE CODE OF 43,45,42,47,94-> IF MID$(EXPRESSION$,W+1,1)="-" THEN FLAG=-1 W=W+1 END IF IF INSTR(OP_LIST$,STACK$[NS])<>0 THEN NERR=5 ELSE NS=NS+1 STACK$[NS]=K$ NOP=NOP+1 IF NOP>=2 THEN FOR J=NS TO 1 STEP -1 DO IF STACK$[J]<>"(" THEN CONTINUE FOR END IF IF J<NS-2 THEN EXIT ELSE GOTO 110 END IF END FOR NS1=J+1 NS2=NS CALC_ARITM NS=NS2 STACK$[NS]=K$ REGISTRO_X#=VAL(STACK$[NS-1]) END IF END IF 110: END ->   40-> IF NS>1 OR (NS=1 AND STACK$[1]<>"@") THEN NS=NS+1 END IF STACK$[NS]="(" NPA=NPA+1 IF MID$(EXPRESSION$,W+1,1)="-" THEN FLAG=-1 W=W+1 END IF END ->   41-> SVOLGI_PAR IF NERR=7 THEN NERR=0 NOP=0 NPA=0 NS=1 ELSE IF NERR=0 OR NERR=1 THEN DB#=VAL(STACK$[NS]) REGISTRO_X#=DB# ELSE NOP=0 NPA=0 NS=1 END IF END IF END ->   OTHERWISE NERR=8 END CASE K$="" DISEGNA_STACK END FOR   98: IF K$<>"" THEN IF NS>1 OR (NS=1 AND STACK$[1]<>"@") THEN NS=NS+1 END IF IF FLAG=0 THEN STACK$[NS]=K$ ELSE STACK$[NS]=STR$(VAL(K$)*FLAG) END IF END IF DISEGNA_STACK IF INSTR(OP_LIST$,STACK$[NS])<>0 THEN NERR=6 ELSE WHILE NPA<>0 DO SVOLGI_PAR END WHILE IF NERR<>7 THEN NS1=1 NS2=NS CALC_ARITM END IF END IF NS=1 NOP=0 NPA=0  !$RCODE="LOCATE 23,1" IF NERR>0 THEN PRINT("Internal Error #";NERR) ELSE PRINT("Value is ";DB#) END IF END PROGRAM  
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Clojure
Clojure
  (use '(incanter core stats charts io))   (defn Arquimidean-function [a b theta] (+ a (* theta b)))   (defn transform-pl-xy [r theta] (let [x (* r (sin theta)) y (* r (cos theta))] [x y]))   (defn arq-spiral [t] (transform-pl-xy (Arquimidean-function 0 7 t) t))   (view (parametric-plot arq-spiral 0 (* 10 Math/PI)))    
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Common_Lisp
Common Lisp
(defun draw-coords-as-text (coords size fill-char) (let* ((min-x (apply #'min (mapcar #'car coords))) (min-y (apply #'min (mapcar #'cdr coords))) (max-x (apply #'max (mapcar #'car coords))) (max-y (apply #'max (mapcar #'cdr coords))) (real-size (max (+ (abs min-x) (abs max-x)) ; bounding square (+ (abs min-y) (abs max-y)))) (scale-factor (* (1- size) (/ 1 real-size))) (center-x (* scale-factor -1 min-x)) (center-y (* scale-factor -1 min-y)) (intermediate-result (make-array (list size size) :element-type 'char :initial-element #\space))) (dolist (c coords) (let ((final-x (floor (+ center-x (* scale-factor (car c))))) (final-y (floor (+ center-y (* scale-factor (cdr c)))))) (setf (aref intermediate-result final-x final-y) fill-char))) ; print results to output (loop for i below (array-total-size intermediate-result) do (when (zerop (mod i size)) (terpri)) (princ (row-major-aref intermediate-result i)))))     (defun spiral (a b step-resolution step-count) "Returns a list of coordinates for r=a+b*theta stepping theta by step-resolution" (loop for theta from 0 upto (* step-count step-resolution) by step-resolution for r = (+ a (* b theta)) for x = (* r (cos theta)) for y = (* r (sin theta)) collect (cons x y)))   (draw-coords-as-text (spiral 10 10 0.01 1500) 30 #\*) ; Output: ; ; * ; ****** * ; **** *** ** ; *** ** * ; ** ** * ; ** ** * ; * ** ** ; ** * * ; ** ****** * * ; * ** ** ** * ; * ** * * * ; * ** * * ** ; * * * * * ; * * * ** * * ; * * *** ** * ; * ** * * ; * * ** * ; * ** ** ** ; ** ** ** * ; * ** ** ** ; ** ******** * ; * ** ; ** ** ; ** ** ; ** *** ; ** ** ; **** *** ; ******* ;        
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#ALGOL_W
ALGOL W
begin  % find the first few squares via the unoptimised door flipping method  %   integer doorMax; doorMax := 100;   begin  % need to start a new block so the array can have variable bounds  %    % array of doors - door( i ) is true if open, false if closed  % logical array door( 1 :: doorMax );    % set all doors to closed  % for i := 1 until doorMax do door( i ) := false;    % repeatedly flip the doors  % for i := 1 until doorMax do begin for j := i step i until doorMax do begin door( j ) := not door( j ) end end;    % display the results  % i_w := 1; % set integer field width  % s_w := 1; % and separator width  % for i := 1 until doorMax do if door( i ) then writeon( i )   end   end.
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#C
C
int myArray2[10] = { 1, 2, 0 }; /* the rest of elements get the value 0 */ float myFloats[] ={1.2, 2.5, 3.333, 4.92, 11.2, 22.0 }; /* automatically sizes */
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Free_Pascal
Free Pascal
Program ComplexDemo;   uses ucomplex;   var a, b, absum, abprod, aneg, ainv, acong: complex;   function complex(const re, im: real): ucomplex.complex; overload; begin complex.re := re; complex.im := im; end;   begin a := complex(5, 3); b := complex(0.5, 6.0); absum := a + b; writeln ('(5 + i3) + (0.5 + i6.0): ', absum.re:3:1, ' + i', absum.im:3:1); abprod := a * b; writeln ('(5 + i3) * (0.5 + i6.0): ', abprod.re:5:1, ' + i', abprod.im:4:1); aneg := -a; writeln ('-(5 + i3): ', aneg.re:3:1, ' + i', aneg.im:3:1); ainv := 1.0 / a; writeln ('1/(5 + i3): ', ainv.re:3:1, ' + i', ainv.im:3:1); acong := cong(a); writeln ('conj(5 + i3): ', acong.re:3:1, ' + i', acong.im:3:1); end.  
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Icon_and_Unicon
Icon and Unicon
procedure main() limit := 2^19   write("Perfect numbers up to ",limit," (using rational arithmetic):") every write(is_perfect(c := 2 to limit)) write("End of perfect numbers")   # verify the rest of the implementation   zero := makerat(0) # from integer half := makerat(0.5) # from real qtr := makerat("1/4") # from strings ... one := makerat("1") mone := makerat("-1")   verifyrat("eqrat",zero,zero) verifyrat("ltrat",zero,half) verifyrat("ltrat",half,zero) verifyrat("gtrat",zero,half) verifyrat("gtrat",half,zero) verifyrat("nerat",zero,half) verifyrat("nerat",zero,zero) verifyrat("absrat",mone,)   end   procedure is_perfect(c) #: test for perfect numbers using rational arithmetic rsum := rational(1, c, 1) every f := 2 to sqrt(c) do if 0 = c % f then rsum := addrat(rsum,addrat(rational(1,f,1),rational(1,integer(c/f),1))) if rsum.numer = rsum.denom = 1 then return c end
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#LiveCode
LiveCode
function agm aa,g put abs(aa-g) into absdiff put (aa+g)/2 into aan put sqrt(aa*g) into gn repeat while abs(aan - gn) < absdiff put abs(aa-g) into absdiff put (aa+g)/2 into aan put sqrt(aa*g) into gn put aan into aa put gn into g end repeat return aa end agm
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#LLVM
LLVM
; This is not strictly LLVM, as it uses the C library function "printf". ; LLVM does not provide a way to print values, so the alternative would be ; to just load the string into memory, and that would be boring.   ; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps   $"ASSERTION" = comdat any $"OUTPUT" = comdat any   @"ASSERTION" = linkonce_odr unnamed_addr constant [48 x i8] c"arithmetic-geometric mean undefined when x*y<0\0A\00", comdat, align 1 @"OUTPUT" = linkonce_odr unnamed_addr constant [42 x i8] c"The arithmetic-geometric mean is %0.19lf\0A\00", comdat, align 1   ;--- The declarations for the external C functions declare i32 @printf(i8*, ...) declare void @exit(i32) #1 declare double @sqrt(double) #1   declare double @llvm.fabs.f64(double) #2   ;---------------------------------------------------------------- ;-- arithmetic geometric mean define double @agm(double, double) #0 { %3 = alloca double, align 8 ; allocate local g %4 = alloca double, align 8 ; allocate local a %5 = alloca double, align 8 ; allocate iota %6 = alloca double, align 8 ; allocate a1 %7 = alloca double, align 8 ; allocate g1 store double %1, double* %3, align 8 ; store param g in local g store double %0, double* %4, align 8 ; store param a in local a store double 1.000000e-15, double* %5, align 8 ; store 1.0e-15 in iota (1.0e-16 was causing the program to hang)   %8 = load double, double* %4, align 8 ; load a %9 = load double, double* %3, align 8 ; load g %10 = fmul double %8, %9 ; a * g %11 = fcmp olt double %10, 0.000000e+00 ; a * g < 0.0 br i1 %11, label %enforce, label %loop   enforce: %12 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([48 x i8], [48 x i8]* @"ASSERTION", i32 0, i32 0)) call void @exit(i32 1) #6 unreachable   loop: %13 = load double, double* %4, align 8 ; load a %14 = load double, double* %3, align 8 ; load g %15 = fsub double %13, %14 ; a - g %16 = call double @llvm.fabs.f64(double %15) ; fabs(a - g) %17 = load double, double* %5, align 8 ; load iota %18 = fcmp ogt double %16, %17 ; fabs(a - g) > iota br i1 %18, label %loop_body, label %eom   loop_body: %19 = load double, double* %4, align 8 ; load a %20 = load double, double* %3, align 8 ; load g %21 = fadd double %19, %20 ; a + g %22 = fdiv double %21, 2.000000e+00 ; (a + g) / 2.0 store double %22, double* %6, align 8 ; store %22 in a1   %23 = load double, double* %4, align 8 ; load a %24 = load double, double* %3, align 8 ; load g %25 = fmul double %23, %24 ; a * g %26 = call double @sqrt(double %25) #4 ; sqrt(a * g) store double %26, double* %7, align 8 ; store %26 in g1   %27 = load double, double* %6, align 8 ; load a1 store double %27, double* %4, align 8 ; store a1 in a   %28 = load double, double* %7, align 8 ; load g1 store double %28, double* %3, align 8 ; store g1 in g   br label %loop   eom: %29 = load double, double* %4, align 8 ; load a ret double %29 ; return a }   ;---------------------------------------------------------------- ;-- main define i32 @main() #0 { %1 = alloca double, align 8 ; allocate x %2 = alloca double, align 8 ; allocate y   store double 1.000000e+00, double* %1, align 8 ; store 1.0 in x   %3 = call double @sqrt(double 2.000000e+00) #4 ; calculate the square root of two %4 = fdiv double 1.000000e+00, %3 ; divide 1.0 by %3 store double %4, double* %2, align 8 ; store %4 in y   %5 = load double, double* %2, align 8 ; reload y %6 = load double, double* %1, align 8 ; reload x %7 = call double @agm(double %6, double %5) ; agm(x, y)   %8 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([42 x i8], [42 x i8]* @"OUTPUT", i32 0, i32 0), double %7)   ret i32 0 ; finished }   attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #1 = { noreturn "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #2 = { nounwind readnone speculatable } attributes #4 = { nounwind } attributes #6 = { noreturn }
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#F.23
F#
module AbstractSyntaxTree   type Expression = | Int of int | Plus of Expression * Expression | Minus of Expression * Expression | Times of Expression * Expression | Divide of Expression * Expression
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#FOCAL
FOCAL
1.1 S A=1.5 1.2 S B=2 1.3 S N=250 1.4 F T=1,N; D 2 1.5 X FSKP(2*N) 1.6 Q   2.1 S R=A+B*T; D 3 2.2 X FPT(2*T,X1+512,Y1+390) 2.3 S R=A+B*(T+1); D 4 2.4 X FVEC(2*T+1,X2-X1,Y2-Y1)   3.1 S X1=R*FSIN(.2*T) 3.2 S Y1=R*FCOS(.2*T)   4.1 S X2=R*FSIN(.2*(T+1)) 4.2 S Y2=R*FCOS(.2*(T+1))
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Frege
Frege
module Archimedean where   import Java.IO import Prelude.Math   data BufferedImage = native java.awt.image.BufferedImage where pure native type_3byte_bgr "java.awt.image.BufferedImage.TYPE_3BYTE_BGR" :: Int native new :: Int -> Int -> Int -> STMutable s BufferedImage native createGraphics :: Mutable s BufferedImage -> STMutable s Graphics2D   data Color = pure native java.awt.Color where pure native orange "java.awt.Color.orange" :: Color pure native white "java.awt.Color.white" :: Color pure native new :: Int -> Color   data BasicStroke = pure native java.awt.BasicStroke where pure native new :: Float -> BasicStroke   data RenderingHints = native java.awt.RenderingHints where pure native key_antialiasing "java.awt.RenderingHints.KEY_ANTIALIASING" :: RenderingHints_Key pure native value_antialias_on "java.awt.RenderingHints.VALUE_ANTIALIAS_ON" :: Object   data RenderingHints_Key = pure native java.awt.RenderingHints.Key   data Graphics2D = native java.awt.Graphics2D where native drawLine :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s () native drawOval :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s () native fillRect :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s () native setColor :: Mutable s Graphics2D -> Color -> ST s () native setRenderingHint :: Mutable s Graphics2D -> RenderingHints_Key -> Object -> ST s () native setStroke :: Mutable s Graphics2D -> BasicStroke -> ST s ()   data ImageIO = mutable native javax.imageio.ImageIO where native write "javax.imageio.ImageIO.write" :: MutableIO BufferedImage -> String -> MutableIO File -> IO Bool throws IOException   width = 640 center = width `div` 2   roundi = fromIntegral . round   drawGrid :: Mutable s Graphics2D -> ST s () drawGrid g = do g.setColor $ Color.new 0xEEEEEE g.setStroke $ BasicStroke.new 2 let angle = toRadians 45 margin = 10 numRings = 8 spacing = (width - 2 * margin) `div` (numRings * 2) forM_ [0 .. numRings-1] $ \i -> do let pos = margin + i * spacing size = width - (2 * margin + i * 2 * spacing) ia = fromIntegral i * angle multiplier = fromIntegral $ (width - 2 * margin) `div` 2 x2 = center + (roundi (cos ia * multiplier)) y2 = center - (roundi (sin ia * multiplier)) g.drawOval pos pos size size g.drawLine center center x2 y2   drawSpiral :: Mutable s Graphics2D -> ST s () drawSpiral g = do g.setStroke $ BasicStroke.new 2 g.setColor $ Color.orange let degrees = toRadians 0.1 end = 360 * 2 * 10 * degrees a = 0 b = 20 c = 1 drSp theta = do let r = a + b * theta ** (1 / c) x = r * cos theta y = r * sin theta theta' = theta + degrees plot g (center + roundi x) (center - roundi y) when (theta' < end) (drSp (theta' + degrees)) drSp 0   plot :: Mutable s Graphics2D -> Int -> Int -> ST s () plot g x y = g.drawOval x y 1 1   main = do buffy <- BufferedImage.new width width BufferedImage.type_3byte_bgr g <- buffy.createGraphics g.setRenderingHint RenderingHints.key_antialiasing RenderingHints.value_antialias_on g.setColor Color.white g.fillRect 0 0 width width drawGrid g drawSpiral g f <- File.new "SpiralFrege.png" void $ ImageIO.write buffy "png" f
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Go
Go
package main   import ( "image" "image/color" "image/draw" "image/png" "log" "math" "os" )   func main() { const ( width, height = 600, 600 centre = width / 2.0 degreesIncr = 0.1 * math.Pi / 180 turns = 2 stop = 360 * turns * 10 * degreesIncr fileName = "spiral.png" )   img := image.NewNRGBA(image.Rect(0, 0, width, height)) // create new image bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) // prepare white for background draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) // fill the background fgCol := color.RGBA{255, 0, 0, 255} // red plot   a := 1.0 b := 20.0   for theta := 0.0; theta < stop; theta += degreesIncr { r := a + b*theta x := r * math.Cos(theta) y := r * math.Sin(theta) img.Set(int(centre+x), int(centre-y), fgCol) }   imgFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer imgFile.Close()   if err := png.Encode(imgFile, img); err != nil { imgFile.Close() log.Fatal(err) } }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#ALGOL-M
ALGOL-M
  BEGIN   INTEGER ARRAY DOORS[1:100]; INTEGER I, J, OPEN, CLOSED;   OPEN := 1; CLOSED := 0;   % ALL DOORS ARE INITIALLY CLOSED % FOR I := 1 STEP 1 UNTIL 100 DO BEGIN DOORS[I] := CLOSED; END;   % PASS THROUGH AT INCREASING INTERVALS AND FLIP % FOR I := 1 STEP 1 UNTIL 100 DO BEGIN FOR J := I STEP I UNTIL 100 DO BEGIN DOORS[J] := 1 - DOORS[J]; END; END;   % SHOW RESULTS % WRITE("THE OPEN DOORS ARE:"); WRITE(""); FOR I := 1 STEP 1 UNTIL 100 DO BEGIN IF DOORS[I] = OPEN THEN WRITEON(I); END;   END
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#C.23
C#
int[] numbers = new int[10];
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Frink
Frink
  add[x,y] := x + y multiply[x,y] := x * y negate[x] := -x invert[x] := 1/x // Could also use inv[x] or recip[x] conjugate[x] := Re[x] - Im[x] i   a = 3 + 2.5i b = 7.3 - 10i println["$a + $b = " + add[a,b]] println["$a * $b = " + multiply[a,b]] println["-$a = " + negate[a]] println["1/$a = " + invert[a]] println["conjugate[$a] = " + conjugate[a]]  
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#J
J
(x: 3) % (x: -4) _3r4 3 %&x: -4 _3r4
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Logo
Logo
to about :a :b output and [:a - :b < 1e-15] [:a - :b > -1e-15] end to agm :arith :geom if about :arith :geom [output :arith] output agm (:arith + :geom)/2 sqrt (:arith * :geom) end   show agm 1 1/sqrt 2  
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Lua
Lua
function agm(a, b, tolerance) if not tolerance or tolerance < 1e-15 then tolerance = 1e-15 end repeat a, b = (a + b) / 2, math.sqrt(a * b) until math.abs(a-b) < tolerance return a end   print(string.format("%.15f", agm(1, 1 / math.sqrt(2))))
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Factor
Factor
USING: accessors kernel locals math math.parser peg.ebnf ; IN: rosetta.arith   TUPLE: operator left right ; TUPLE: add < operator ; C: <add> add TUPLE: sub < operator ; C: <sub> sub TUPLE: mul < operator ; C: <mul> mul TUPLE: div < operator ; C: <div> div   EBNF: expr-ast spaces = [\n\t ]* digit = [0-9] number = (digit)+ => [[ string>number ]]   value = spaces number:n => [[ n ]] | spaces "(" exp:e spaces ")" => [[ e ]]   fac = fac:a spaces "*" value:b => [[ a b <mul> ]] | fac:a spaces "/" value:b => [[ a b <div> ]] | value   exp = exp:a spaces "+" fac:b => [[ a b <add> ]] | exp:a spaces "-" fac:b => [[ a b <sub> ]] | fac   main = exp:e spaces !(.) => [[ e ]] ;EBNF   GENERIC: eval-ast ( ast -- result )   M: number eval-ast ;   : recursive-eval ( ast -- left-result right-result ) [ left>> eval-ast ] [ right>> eval-ast ] bi ;   M: add eval-ast recursive-eval + ; M: sub eval-ast recursive-eval - ; M: mul eval-ast recursive-eval * ; M: div eval-ast recursive-eval / ;   : evaluate ( string -- result ) expr-ast eval-ast ;
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Haskell
Haskell
#!/usr/bin/env stack -- stack --resolver lts-7.0 --install-ghc runghc --package Rasterific --package JuicyPixels   import Codec.Picture( PixelRGBA8( .. ), writePng ) import Graphics.Rasterific import Graphics.Rasterific.Texture import Graphics.Rasterific.Transformations   archimedeanPoint a b t = V2 x y where r = a + b * t x = r * cos t y = r * sin t   main :: IO () main = do let white = PixelRGBA8 255 255 255 255 drawColor = PixelRGBA8 0xFF 0x53 0x73 255 size = 800 points = map (archimedeanPoint 0 10) [0, 0.01 .. 60] hSize = fromIntegral size / 2 img = renderDrawing size size white $ withTransformation (translate $ V2 hSize hSize) $ withTexture (uniformTexture drawColor) $ stroke 4 JoinRound (CapRound, CapRound) $ polyline points   writePng "SpiralHaskell.png" img
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#J
J
require'plot' 'aspect 1' plot (*^)j.0.01*i.1400
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#AmigaE
AmigaE
PROC main() DEF t[100]: ARRAY, pass, door FOR door := 0 TO 99 DO t[door] := FALSE FOR pass := 0 TO 99 door := pass WHILE door <= 99 t[door] := Not(t[door]) door := door + pass + 1 ENDWHILE ENDFOR FOR door := 0 TO 99 DO WriteF('\d is \s\n', door+1, IF t[door] THEN 'open' ELSE 'closed') ENDPROC
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#C.2B.2B
C++
#include <array> #include <vector>   // These headers are only needed for the demonstration #include <algorithm> #include <iostream> #include <iterator> #include <string>   // This is a template function that works for any array-like object template <typename Array> void demonstrate(Array& array) { // Array element access array[2] = "Three"; // Fast, but unsafe - if the index is out of bounds you // get undefined behaviour array.at(1) = "Two"; // *Slightly* less fast, but safe - if the index is out // of bounds, an exception is thrown   // Arrays can be used with standard algorithms std::reverse(begin(array), end(array)); std::for_each(begin(array), end(array), [](typename Array::value_type const& element) // in C++14, you can just use auto { std::cout << element << ' '; });   std::cout << '\n'; }   int main() { // Compile-time sized fixed-size array auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" }; // If you do not supply enough elements, the remainder are default-initialized   // Dynamic array auto dynamic_array = std::vector<std::string>{ "One", "Four" }; dynamic_array.push_back("Eight"); // Dynamically grows to accept new element   // All types of arrays can be used more or less interchangeably demonstrate(fixed_size_array); demonstrate(dynamic_array); }
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Futhark
Futhark
  type complex = (f64,f64)   fun complexAdd((a,b): complex) ((c,d): complex): complex = (a + c, b + d)   fun complexMult((a,b): complex) ((c,d): complex): complex = (a*c - b * d, a*d + b * c)   fun complexInv((r,i): complex): complex = let denom = r*r + i * i in (r / denom, -i / denom)   fun complexNeg((r,i): complex): complex = (-r, -i)   fun complexConj((r,i): complex): complex = (r, -i)   fun main (o: int) (a: complex) (b: complex): complex = if o == 0 then complexAdd a b else if o == 1 then complexMult a b else if o == 2 then complexInv a else if o == 3 then complexNeg a else complexConj a  
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#GAP
GAP
# GAP knows gaussian integers, gaussian rationals (i.e. Q[i]), and cyclotomic fields. Here are some examples. # E(n) is an nth primitive root of 1 i := Sqrt(-1); # E(4) (3 + 2*i)*(5 - 7*i); # 29-11*E(4) 1/i; # -E(4) Sqrt(-3); # E(3)-E(3)^2   i in GaussianIntegers; # true i/2 in GaussianIntegers; # false i/2 in GaussianRationals; # true Sqrt(-3) in Cyclotomics; # true
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Java
Java
public class BigRationalFindPerfectNumbers { public static void main(String[] args) { int MAX_NUM = 1 << 19; System.out.println("Searching for perfect numbers in the range [1, " + (MAX_NUM - 1) + "]");   BigRational TWO = BigRational.valueOf(2); for (int i = 1; i < MAX_NUM; i++) { BigRational reciprocalSum = BigRational.ONE; if (i > 1) reciprocalSum = reciprocalSum.add(BigRational.valueOf(i).reciprocal()); int maxDivisor = (int) Math.sqrt(i); if (maxDivisor >= i) maxDivisor--;   for (int divisor = 2; divisor <= maxDivisor; divisor++) { if (i % divisor == 0) { reciprocalSum = reciprocalSum.add(BigRational.valueOf(divisor).reciprocal()); int dividend = i / divisor; if (divisor != dividend) reciprocalSum = reciprocalSum.add(BigRational.valueOf(dividend).reciprocal()); } } if (reciprocalSum.equals(TWO)) System.out.println(String.valueOf(i) + " is a perfect number"); } } }
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Function Agm { \\ new stack constructed at calling the Agm() with two values Repeat { Read a0, b0 Push Sqrt(a0*b0), (a0+b0)/2 ' last pushed first read } Until Stackitem(1)==Stackitem(2) =Stackitem(1) \\ stack deconstructed at exit of function } Print Agm(1,1/Sqrt(2)) } Checkit  
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Maple
Maple
  > evalf( GaussAGM( 1, 1 / sqrt( 2 ) ) ); # default precision is 10 digits 0.8472130847   > evalf[100]( GaussAGM( 1, 1 / sqrt( 2 ) ) ); # to 100 digits 0.847213084793979086606499123482191636481445910326942185060579372659\ 7340048341347597232002939946112300  
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#FreeBASIC
FreeBASIC
  'Arithmetic evaluation ' 'Create a program which parses and evaluates arithmetic expressions. ' 'Requirements ' ' * An abstract-syntax tree (AST) for the expression must be created from parsing the ' input. ' * The AST must be used in evaluation, also, so the input may not be directly evaluated ' (e.g. by calling eval or a similar language feature.) ' * The expression will be a string or list of symbols like "(1+3)*7". ' * The four symbols + - * / must be supported as binary operators with conventional ' precedence rules. ' * Precedence-control parentheses must also be supported. ' 'Standard mathematical precedence should be followed: ' ' Parentheses ' Multiplication/Division (left to right) ' Addition/Subtraction (left to right) ' ' test cases: ' 2*-3--4+-0.25 : returns -2.25 ' 1 + 2 * (3 + (4 * 5 + 6 * 7 * 8) - 9) / 10 : returns 71   enum false = 0 true = -1 end enum   enum Symbol unknown_sym minus_sym plus_sym lparen_sym rparen_sym number_sym mul_sym div_sym unary_minus_sym unary_plus_sym done_sym eof_sym end enum   type Tree as Tree ptr leftp, rightp op as Symbol value as double end type   dim shared sym as Symbol dim shared tokenval as double dim shared usr_input as string   declare function expr(byval p as integer) as Tree ptr   function isdigit(byval ch as string) as long return ch <> "" and Asc(ch) >= Asc("0") and Asc(ch) <= Asc("9") end function   sub error_msg(byval msg as string) print msg system end sub   ' tokenize the input string sub getsym() do if usr_input = "" then line input usr_input usr_input += chr(10) endif dim as string ch = mid(usr_input, 1, 1) ' get the next char usr_input = mid(usr_input, 2) ' remove it from input   sym = unknown_sym select case ch case " ": continue do case chr(10), "": sym = done_sym: return case "+": sym = plus_sym: return case "-": sym = minus_sym: return case "*": sym = mul_sym: return case "/": sym = div_sym: return case "(": sym = lparen_sym: return case ")": sym = rparen_sym: return case else if isdigit(ch) then dim s as string = "" dim dot as integer = 0 do s += ch if ch = "." then dot += 1 ch = mid(usr_input, 1, 1) ' get the next char usr_input = mid(usr_input, 2) ' remove it from input loop while isdigit(ch) orelse ch = "." if ch = "." or dot > 1 then error_msg("bogus number") usr_input = ch + usr_input ' prepend the char to input tokenval = val(s) sym = number_sym end if return end select loop end sub   function make_node(byval op as Symbol, byval leftp as Tree ptr, byval rightp as Tree ptr) as Tree ptr dim t as Tree ptr   t = callocate(len(Tree)) t->op = op t->leftp = leftp t->rightp = rightp return t end function   function is_binary(byval op as Symbol) as integer select case op case mul_sym, div_sym, plus_sym, minus_sym: return true case else: return false end select end function   function prec(byval op as Symbol) as integer select case op case unary_minus_sym, unary_plus_sym: return 100 case mul_sym, div_sym: return 90 case plus_sym, minus_sym: return 80 case else: return 0 end select end function   function primary as Tree ptr dim t as Tree ptr = 0   select case sym case minus_sym, plus_sym dim op as Symbol = sym getsym() t = expr(prec(unary_minus_sym)) if op = minus_sym then return make_node(unary_minus_sym, t, 0) if op = plus_sym then return make_node(unary_plus_sym, t, 0) case lparen_sym getsym() t = expr(0) if sym <> rparen_sym then error_msg("expecting rparen") getsym() return t case number_sym t = make_node(sym, 0, 0) t->value = tokenval getsym() return t case else: error_msg("expecting a primary") end select end function   function expr(byval p as integer) as Tree ptr dim t as Tree ptr = primary()   while is_binary(sym) andalso prec(sym) >= p dim t1 as Tree ptr dim op as Symbol = sym getsym() t1 = expr(prec(op) + 1) t = make_node(op, t, t1) wend return t end function   function eval(byval t as Tree ptr) as double if t <> 0 then select case t->op case minus_sym: return eval(t->leftp) - eval(t->rightp) case plus_sym: return eval(t->leftp) + eval(t->rightp) case mul_sym: return eval(t->leftp) * eval(t->rightp) case div_sym: return eval(t->leftp) / eval(t->rightp) case unary_minus_sym: return -eval(t->leftp) case unary_plus_sym: return eval(t->leftp) case number_sym: return t->value case else: error_msg("unexpected tree node") end select end if return 0 end function   do getsym() if sym = eof_sym then exit do if sym = done_sym then continue do dim t as Tree ptr = expr(0) print"> "; eval(t) if sym = eof_sym then exit do if sym <> done_sym then error_msg("unexpected input") loop  
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Java
Java
import java.awt.*; import static java.lang.Math.*; import javax.swing.*;   public class ArchimedeanSpiral extends JPanel {   public ArchimedeanSpiral() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); }   void drawGrid(Graphics2D g) { g.setColor(new Color(0xEEEEEE)); g.setStroke(new BasicStroke(2));   double angle = toRadians(45);   int w = getWidth(); int center = w / 2; int margin = 10; int numRings = 8;   int spacing = (w - 2 * margin) / (numRings * 2);   for (int i = 0; i < numRings; i++) { int pos = margin + i * spacing; int size = w - (2 * margin + i * 2 * spacing); g.drawOval(pos, pos, size, size);   double ia = i * angle; int x2 = center + (int) (cos(ia) * (w - 2 * margin) / 2); int y2 = center - (int) (sin(ia) * (w - 2 * margin) / 2);   g.drawLine(center, center, x2, y2); } }   void drawSpiral(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(Color.orange);   double degrees = toRadians(0.1); double center = getWidth() / 2; double end = 360 * 2 * 10 * degrees; double a = 0; double b = 20; double c = 1;   for (double theta = 0; theta < end; theta += degrees) { double r = a + b * pow(theta, 1 / c); double x = r * cos(theta); double y = r * sin(theta); plot(g, (int) (center + x), (int) (center - y)); } }   void plot(Graphics2D g, int x, int y) { g.drawOval(x, y, 1, 1); }   @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);   drawGrid(g); drawSpiral(g); }   public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Archimedean Spiral"); f.setResizable(false); f.add(new ArchimedeanSpiral(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#APL
APL
doors←{100⍴((⍵-1)⍴0),1} ≠⌿⊃doors¨ ⍳100
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Ceylon
Ceylon
import ceylon.collection {   ArrayList }   shared void run() {   // you can get an array from the Array.ofSize named constructor value array = Array.ofSize(10, "hello"); value a = array[3]; print(a); array[4] = "goodbye"; print(array);   // for a dynamic list import ceylon.collection in your module.ceylon file value list = ArrayList<String>(); list.push("hello"); list.push("hello again"); print(list); }
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Go
Go
package main   import ( "fmt" "math/cmplx" )   func main() { a := 1 + 1i b := 3.14159 + 1.25i fmt.Println("a: ", a) fmt.Println("b: ", b) fmt.Println("a + b: ", a+b) fmt.Println("a * b: ", a*b) fmt.Println("-a: ", -a) fmt.Println("1 / a: ", 1/a) fmt.Println("a̅: ", cmplx.Conj(a)) }
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#JavaScript
JavaScript
// the constructor function Rational(numerator, denominator) { if (denominator === undefined) denominator = 1; else if (denominator == 0) throw "divide by zero";   this.numer = numerator; if (this.numer == 0) this.denom = 1; else this.denom = denominator;   this.normalize(); }   // getter methods Rational.prototype.numerator = function() {return this.numer}; Rational.prototype.denominator = function() {return this.denom};   // clone a rational Rational.prototype.dup = function() { return new Rational(this.numerator(), this.denominator()); };   // conversion methods Rational.prototype.toString = function() { if (this.denominator() == 1) { return this.numerator().toString(); } else { // implicit conversion of numbers to strings return this.numerator() + '/' + this.denominator() } }; Rational.prototype.toFloat = function() {return eval(this.toString())} Rational.prototype.toInt = function() {return Math.floor(this.toFloat())};   // reduce Rational.prototype.normalize = function() { // greatest common divisor var a=Math.abs(this.numerator()), b=Math.abs(this.denominator()) while (b != 0) { var tmp = a; a = b; b = tmp % b; } // a is the gcd   this.numer /= a; this.denom /= a; if (this.denom < 0) { this.numer *= -1; this.denom *= -1; } return this; }   // absolute value // returns a new rational Rational.prototype.abs = function() { return new Rational(Math.abs(this.numerator()), this.denominator()); };   // inverse // returns a new rational Rational.prototype.inv = function() { return new Rational(this.denominator(), this.numerator()); };   // // arithmetic methods   // variadic, modifies receiver Rational.prototype.add = function() { for (var i = 0; i < arguments.length; i++) { this.numer = this.numer * arguments[i].denominator() + this.denom * arguments[i].numerator(); this.denom = this.denom * arguments[i].denominator(); } return this.normalize(); };   // variadic, modifies receiver Rational.prototype.subtract = function() { for (var i = 0; i < arguments.length; i++) { this.numer = this.numer * arguments[i].denominator() - this.denom * arguments[i].numerator(); this.denom = this.denom * arguments[i].denominator(); } return this.normalize(); };   // unary "-" operator // returns a new rational Rational.prototype.neg = function() { return (new Rational(0)).subtract(this); };   // variadic, modifies receiver Rational.prototype.multiply = function() { for (var i = 0; i < arguments.length; i++) { this.numer *= arguments[i].numerator(); this.denom *= arguments[i].denominator(); } return this.normalize(); };   // modifies receiver Rational.prototype.divide = function(rat) { return this.multiply(rat.inv()); }     // increment // modifies receiver Rational.prototype.inc = function() { this.numer += this.denominator(); return this.normalize(); }   // decrement // modifies receiver Rational.prototype.dec = function() { this.numer -= this.denominator(); return this.normalize(); }   // // comparison methods   Rational.prototype.isZero = function() { return (this.numerator() == 0); } Rational.prototype.isPositive = function() { return (this.numerator() > 0); } Rational.prototype.isNegative = function() { return (this.numerator() < 0); }   Rational.prototype.eq = function(rat) { return this.dup().subtract(rat).isZero(); } Rational.prototype.ne = function(rat) { return !(this.eq(rat)); } Rational.prototype.lt = function(rat) { return this.dup().subtract(rat).isNegative(); } Rational.prototype.gt = function(rat) { return this.dup().subtract(rat).isPositive(); } Rational.prototype.le = function(rat) { return !(this.gt(rat)); } Rational.prototype.ge = function(rat) { return !(this.lt(rat)); }
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
PrecisionDigits = 85; AGMean[a_, b_] := FixedPoint[{ Tr@#/2, Sqrt[Times@@#] }&, N[{a,b}, PrecisionDigits]]〚1〛
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#MATLAB_.2F_Octave
MATLAB / Octave
function [a,g]=agm(a,g) %%arithmetic_geometric_mean(a,g) while (1) a0=a; a=(a0+g)/2; g=sqrt(a0*g); if (abs(a0-a) < a*eps) break; end; end; end
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Go
Go
enum Op { ADD('+', 2), SUBTRACT('-', 2), MULTIPLY('*', 1), DIVIDE('/', 1);   static { ADD.operation = { a, b -> a + b } SUBTRACT.operation = { a, b -> a - b } MULTIPLY.operation = { a, b -> a * b } DIVIDE.operation = { a, b -> a / b } }   final String symbol final int precedence Closure operation   private Op(String symbol, int precedence) { this.symbol = symbol this.precedence = precedence }   String toString() { symbol }   static Op fromSymbol(String symbol) { Op.values().find { it.symbol == symbol } } }   interface Expression { Number evaluate(); }   class Constant implements Expression { Number value   Constant (Number value) { this.value = value }   Constant (String str) { try { this.value = str as BigInteger } catch (e) { this.value = str as BigDecimal } }   Number evaluate() { value }   String toString() { "${value}" } }   class Term implements Expression { Op op Expression left, right   Number evaluate() { op.operation(left.evaluate(), right.evaluate()) }   String toString() { "(${op} ${left} ${right})" } }   void fail(String msg, Closure cond = {true}) { if (cond()) throw new IllegalArgumentException("Cannot parse expression: ${msg}") }   Expression parse(String expr) { def tokens = tokenize(expr) def elements = groupByParens(tokens, 0) parse(elements) }   List tokenize(String expr) { def tokens = [] def constStr = "" def captureConstant = { i -> if (constStr) { try { tokens << new Constant(constStr) } catch (NumberFormatException e) { fail "Invalid constant '${constStr}' near position ${i}" } constStr = '' } } for(def i = 0; i<expr.size(); i++) { def c = expr[i] def constSign = c in ['+','-'] && constStr.empty && (tokens.empty || tokens[-1] != ')') def isConstChar = { it in ['.'] + ('0'..'9') || constSign } if (c in ([')'] + Op.values()*.symbol) && !constSign) { captureConstant(i) } switch (c) { case ~/\s/: break case isConstChar: constStr += c; break case Op.values()*.symbol: tokens << Op.fromSymbol(c); break case ['(',')']: tokens << c; break default: fail "Invalid character '${c}' at position ${i+1}" } } captureConstant(expr.size()) tokens }   List groupByParens(List tokens, int depth) { def deepness = depth def tokenGroups = [] for (def i = 0; i < tokens.size(); i++) { def token = tokens[i] switch (token) { case '(': fail("'(' too close to end of expression") { i+2 > tokens.size() } def subGroup = groupByParens(tokens[i+1..-1], depth+1) tokenGroups << subGroup[0..-2] i += subGroup[-1] + 1 break case ')': fail("Unbalanced parens, found extra ')'") { deepness == 0 } tokenGroups << i return tokenGroups default: tokenGroups << token } } fail("Unbalanced parens, unclosed groupings at end of expression") { deepness != 0 } def n = tokenGroups.size() fail("The operand/operator sequence is wrong") { n%2 == 0 } (0..<n).each { def i = it fail("The operand/operator sequence is wrong") { (i%2 == 0) == (tokenGroups[i] instanceof Op) } } tokenGroups }   Expression parse(List elements) { while (elements.size() > 1) { def n = elements.size() fail ("The operand/operator sequence is wrong") { n%2 == 0 } def groupLoc = (0..<n).find { i -> elements[i] instanceof List } if (groupLoc != null) { elements[groupLoc] = parse(elements[groupLoc]) continue } def opLoc = (0..<n).find { i -> elements[i] instanceof Op && elements[i].precedence == 1 } \ ?: (0..<n).find { i -> elements[i] instanceof Op && elements[i].precedence == 2 } if (opLoc != null) { fail ("Operator out of sequence") { opLoc%2 == 0 } def term = new Term(left:elements[opLoc-1], op:elements[opLoc], right:elements[opLoc+1]) elements[(opLoc-1)..(opLoc+1)] = [term] continue } } return elements[0] instanceof List ? parse(elements[0]) : elements[0] }
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#JavaScript
JavaScript
  <!-- ArchiSpiral.html --> <html> <head><title>Archimedean spiral</title></head> <body onload="pAS(35,'navy');"> <h3>Archimedean spiral</h3> <p id=bo></p> <canvas id="canvId" width="640" height="640" style="border: 2px outset;"></canvas> <script> // Plotting Archimedean_spiral aev 3/17/17 // lps - number of loops, clr - color. function pAS(lps,clr) { var a=.0,ai=.1,r=.0,ri=.1,as=lps*2*Math.PI,n=as/ai; var cvs=document.getElementById("canvId"); var ctx=cvs.getContext("2d"); ctx.fillStyle="white"; ctx.fillRect(0,0,cvs.width,cvs.height); var x=y=0, s=cvs.width/2; ctx.beginPath(); for (var i=1; i<n; i++) { x=r*Math.cos(a), y=r*Math.sin(a); ctx.lineTo(x+s,y+s); r+=ri; a+=ai; }//fend i ctx.strokeStyle = clr; ctx.stroke(); } </script></body></html>  
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#jq
jq
def spiral($zero; $turns; $step):   def pi: 1 | atan * 4; def p2: (. * 100 | round) / 100;   def svg: 400 as $width | 400 as $height | 2 as $swidth # stroke | "blue" as $stroke | (range($zero; $turns * 2 * pi; $step) as $theta | (((($theta)|cos) * 2 * $theta + ($width/2)) |p2) as $x | (((($theta)|sin) * 2 * $theta + ($height/2))|p2) as $y | if $theta == $zero then "<path fill='transparent' style='stroke:\($stroke); stroke-width:\($swidth)' d='M \($x) \($y)" else " L \($x) \($y)" end), "' />";   "<svg width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'>", svg, "</svg>" ;   spiral(0; 10; 0.025)  
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Julia
Julia
using UnicodePlots   spiral(θ, a=0, b=1) = @. b * θ * cos(θ + a), b * θ * sin(θ + a)   x, y = spiral(1:0.1:10) println(lineplot(x, y))
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#AppleScript
AppleScript
set is_open to {} repeat 100 times set end of is_open to false end repeat with pass from 1 to 100 repeat with door from pass to 100 by pass set item door of is_open to not item door of is_open end end set open_doors to {} repeat with door from 1 to 100 if item door of is_open then set end of open_doors to door end end set text item delimiters to ", " display dialog "Open doors: " & open_doors
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#ChucK
ChucK
  int array[0]; // instantiate int array array << 1; // append item array << 2 << 3; // append items 4 => array[3]; // assign element(4) to index(3) 5 => array.size; // resize array.clear(); // clear elements <<<array.size()>>>; // print in cosole array size [1,2,3,4,5,6,7] @=> array; array.popBack(); // Pop last element  
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Groovy
Groovy
class Complex { final Number real, imag   static final Complex i = [0,1] as Complex   Complex(Number r, Number i = 0) { (real, imag) = [r, i] }   Complex(Map that) { (real, imag) = [that.real ?: 0, that.imag ?: 0] }   Complex plus (Complex c) { [real + c.real, imag + c.imag] as Complex } Complex plus (Number n) { [real + n, imag] as Complex }   Complex minus (Complex c) { [real - c.real, imag - c.imag] as Complex } Complex minus (Number n) { [real - n, imag] as Complex }   Complex multiply (Complex c) { [real*c.real - imag*c.imag , imag*c.real + real*c.imag] as Complex } Complex multiply (Number n) { [real*n , imag*n] as Complex }   Complex div (Complex c) { this * c.recip() } Complex div (Number n) { this * (1/n) }   Complex negative () { [-real, -imag] as Complex }   /** the complex conjugate of this complex number. Overloads the bitwise complement (~) operator. */ Complex bitwiseNegate () { [real, -imag] as Complex }   /** the magnitude of this complex number. */ // could also use Math.sqrt( (this * (~this)).real ) Number getAbs() { Math.sqrt( real*real + imag*imag ) } /** the magnitude of this complex number. */ Number abs() { this.abs }   /** the reciprocal of this complex number. */ Complex getRecip() { (~this) / (ρ**2) } /** the reciprocal of this complex number. */ Complex recip() { this.recip }   /** derived polar angle θ (theta) for polar form. Normalized to 0 ≤ θ < 2π. */ Number getTheta() { def θ = Math.atan2(imag,real) θ = θ < 0 ? θ + 2 * Math.PI : θ } /** derived polar angle θ (theta) for polar form. Normalized to 0 ≤ θ < 2π. */ Number getΘ() { this.theta } // this is greek uppercase theta   /** derived polar magnitude ρ (rho) for polar form. */ Number getRho() { this.abs } /** derived polar magnitude ρ (rho) for polar form. */ Number getΡ() { this.abs } // this is greek uppercase rho, not roman P   /** Runs Euler's polar-to-Cartesian complex conversion, * converting [ρ, θ] inputs into a [real, imag]-based complex number */ static Complex fromPolar(Number ρ, Number θ) { [ρ * Math.cos(θ), ρ * Math.sin(θ)] as Complex }   /** Creates new complex with same magnitude ρ, but different angle θ */ Complex withTheta(Number θ) { fromPolar(this.rho, θ) } /** Creates new complex with same magnitude ρ, but different angle θ */ Complex withΘ(Number θ) { fromPolar(this.rho, θ) }   /** Creates new complex with same angle θ, but different magnitude ρ */ Complex withRho(Number ρ) { fromPolar(ρ, this.θ) } /** Creates new complex with same angle θ, but different magnitude ρ */ Complex withΡ(Number ρ) { fromPolar(ρ, this.θ) } // this is greek uppercase rho, not roman P   static Complex exp(Complex c) { fromPolar(Math.exp(c.real), c.imag) }   static Complex log(Complex c) { [Math.log(c.rho), c.theta] as Complex }   Complex power(Complex c) { def zero = [0] as Complex (this == zero && c != zero) \ ? zero \  : c == 1 \ ? this \  : exp( log(this) * c ) }   Complex power(Number n) { this ** ([n, 0] as Complex) }   boolean equals(that) { that != null && (that instanceof Complex \ ? [this.real, this.imag] == [that.real, that.imag] \  : that instanceof Number && [this.real, this.imag] == [that, 0]) }   int hashCode() { [real, imag].hashCode() }   String toString() { def realPart = "${real}" def imagPart = imag.abs() == 1 ? "i" : "${imag.abs()}i" real == 0 && imag == 0 \ ? "0" \  : real == 0 \ ? (imag > 0 ? '' : "-") + imagPart \  : imag == 0 \ ? realPart \  : realPart + (imag > 0 ? " + " : " - ") + imagPart } }
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#jq
jq
# a and b are assumed to be non-zero integers def gcd(a; b): # subfunction expects [a,b] as input # i.e. a ~ .[0] and b ~ .[1] def rgcd: if .[1] == 0 then .[0] else [.[1], .[0] % .[1]] | rgcd end; [a,b] | rgcd;   # To take advantage of gojq's support for accurate integer division: def idivide($j): . as $i | ($i % $j) as $mod | ($i - $mod) / $j ;   # To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   # $p should be an integer or a rational # $q should be a non-zero integer or a rational # Output: a Rational: $p // $q def r($p;$q): def r: if type == "number" then {n: ., d: 1} else . end; # The remaining subfunctions assume all args are Rational def n: if .d < 0 then {n: -.n, d: -.d} else . end; def rdiv($a;$b): ($a.d * $b.n) as $denom | if $denom==0 then "r: division by 0" | error else r($a.n * $b.d; $denom) end; if $q == 1 and ($p|type) == "number" then {n: $p, d: 1} elif $q == 0 then "r: denominator cannot be 0" | error else if ($p|type == "number") and ($q|type == "number") then gcd($p;$q) as $g | {n: ($p/$g), d: ($q/$g)} | n else rdiv($p|r; $q|r) end end;   # Polymorphic (integers and rationals in general) def requal($a; $b): if $a | type == "number" and $b | type == "number" then $a == $b else r($a;1) == r($b;1) end;   # Input: a Rational # Output: a Rational with a denominator that has no more than $digits digits # and such that |rBefore - rAfter| < 1/(10|power($digits) # where $digits should be a positive integer. def rround($digits): if .d | length > $digits then (10|power($digits)) as $p | .d as $d | r($p * .n | idivide($d); $p) else . end;   # Polymorphic; see also radd/0 def radd($a; $b): def r: if type == "number" then {n: ., d: 1} else . end; ($a|r) as {n: $na, d: $da} | ($b|r) as {n: $nb, d: $db} | r( ($na * $db) + ($nb * $da); $da * $db );   # Polymorphic; see also rmult/0 def rmult($a; $b): def r: if type == "number" then {n: ., d: 1} else . end; ($a|r) as {n: $na, d: $da} | ($b|r) as {n: $nb, d: $db} | r( $na * $nb; $da * $db ) ;   # Input: an array of rationals (integers and/or Rationals) # Output: a Rational computed using left-associativity def rmult: if length == 0 then r(1;1) elif length == 1 then r(.[0]; 1) # ensure the result is Rational else .[0] as $first | reduce .[1:][] as $x ($first; rmult(.; $x)) end;   # Input: an array of rationals (integers and/or Rationals) # Output: a Rational computed using left-associativity def radd: if length == 0 then r(0;1) elif length == 1 then r(.[0]; 1) # ensure the result is Rational else .[0] as $first | reduce .[1:][] as $x ($first; radd(. ; $x)) end;   def rabs: r(.;1) | r(.n|length; .d|length);   def rminus: r(-1 * .n; .d);   def rminus($a; $b): radd($a; rmult(-1; $b));   # Note that rinv does not check for division by 0 def rinv: r(1; .);   def rdiv($a; $b): r($a; $b);   # Input: an integer or a Rational, $p # Output: $p < $q def rlessthan($q): # lt($b) assumes . and $b have the same sign def lt($b): . as $a | ($a.n * $b.d) < ($b.n * $a.d);   if $q|type == "number" then rlessthan(r($q;1)) else if type == "number" then r(.;1) else . end | if .n < 0 then if ($q.n >= 0) then true else . as $p | ($q|rminus | rlessthan($p|rminus)) end else lt($q) end end;   def rgreaterthan($q): . as $p | $q | rlessthan($p);   def rlessthanOrEqual($q): requal(.;$q) or rlessthan($q); def rgreaterthanOrEqual($q): requal(.;$q) or rgreaterthan($q);   # Input: non-negative integer or Rational def rsqrt(precision): r(.;1) as $n | (precision + 1) as $digits | def update: rmult( r(1;2); radd(.x; rdiv($n; .x))) | rround($digits);   | def update: rmult( r(1;2); radd(.x; rdiv($n; .x)));   r(1; 10|power(precision)) as $p | { x: .} | .root = update | until( rminus(.root; .x) | rabs | rlessthan($p); .x = .root | .root = update ) | .root ;   # Use native floats # q.v. r_to_decimal(precision) def r_to_decimal: .n / .d;   # Input: a Rational, or {n, d} in general, or an integer. # Output: a string representation of the input as a decimal number. # If the input is a number, it is simply converted to a string. # Otherwise, $precision determines the number of digits after the decimal point, # obtained by truncating, but trailing 0s are omitted. # Examples assuming $digits is 5: # -0//1 => "0" # 2//1 => "2" # 1//2 => "0.5" # 1//3 => "0.33333" # 7//9 => "0.77777" # 1//100 => "0.01" # -1//10 => "-0.1" # 1//1000000 => "0." def r_to_decimal($digits): if .n == 0 # captures the annoying case of -0 then "0" elif type == "number" then tostring elif .d < 0 then {n: -.n, d: -.d}|r_to_decimal($digits) elif .n < 0 then "-" + ((.n = -.n) | r_to_decimal($digits)) else (10|power($digits)) as $p | .d as $d | if $d == 1 then .n|tostring else ($p * .n | idivide($d) | tostring) as $n | ($n|length) as $nlength | (if $nlength > $digits then $n[0:$nlength-$digits] + "." + $n[$nlength-$digits:] else "0." + ("0"*($digits - $nlength) + $n) end) | sub("0+$";"") end end;   # pretty print ala Julia def rpp: "\(.n) // \(.d)";
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Maxima
Maxima
agm(a, b) := %pi/4*(a + b)/elliptic_kc(((a - b)/(a + b))^2)$   agm(1, 1/sqrt(2)), bfloat, fpprec: 85; /* 8.472130847939790866064991234821916364814459103269421850605793726597340048341347597232b-1 */
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#.D0.9C.D0.9A-61.2F52
МК-61/52
П1 <-> П0 1 ВП 8 /-/ П2 ИП0 ИП1 - ИП2 - /-/ x<0 31 ИП1 П3 ИП0 ИП1 * КвКор П1 ИП0 ИП3 + 2 / П0 БП 08 ИП0 С/П
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Groovy
Groovy
enum Op { ADD('+', 2), SUBTRACT('-', 2), MULTIPLY('*', 1), DIVIDE('/', 1);   static { ADD.operation = { a, b -> a + b } SUBTRACT.operation = { a, b -> a - b } MULTIPLY.operation = { a, b -> a * b } DIVIDE.operation = { a, b -> a / b } }   final String symbol final int precedence Closure operation   private Op(String symbol, int precedence) { this.symbol = symbol this.precedence = precedence }   String toString() { symbol }   static Op fromSymbol(String symbol) { Op.values().find { it.symbol == symbol } } }   interface Expression { Number evaluate(); }   class Constant implements Expression { Number value   Constant (Number value) { this.value = value }   Constant (String str) { try { this.value = str as BigInteger } catch (e) { this.value = str as BigDecimal } }   Number evaluate() { value }   String toString() { "${value}" } }   class Term implements Expression { Op op Expression left, right   Number evaluate() { op.operation(left.evaluate(), right.evaluate()) }   String toString() { "(${op} ${left} ${right})" } }   void fail(String msg, Closure cond = {true}) { if (cond()) throw new IllegalArgumentException("Cannot parse expression: ${msg}") }   Expression parse(String expr) { def tokens = tokenize(expr) def elements = groupByParens(tokens, 0) parse(elements) }   List tokenize(String expr) { def tokens = [] def constStr = "" def captureConstant = { i -> if (constStr) { try { tokens << new Constant(constStr) } catch (NumberFormatException e) { fail "Invalid constant '${constStr}' near position ${i}" } constStr = '' } } for(def i = 0; i<expr.size(); i++) { def c = expr[i] def constSign = c in ['+','-'] && constStr.empty && (tokens.empty || tokens[-1] != ')') def isConstChar = { it in ['.'] + ('0'..'9') || constSign } if (c in ([')'] + Op.values()*.symbol) && !constSign) { captureConstant(i) } switch (c) { case ~/\s/: break case isConstChar: constStr += c; break case Op.values()*.symbol: tokens << Op.fromSymbol(c); break case ['(',')']: tokens << c; break default: fail "Invalid character '${c}' at position ${i+1}" } } captureConstant(expr.size()) tokens }   List groupByParens(List tokens, int depth) { def deepness = depth def tokenGroups = [] for (def i = 0; i < tokens.size(); i++) { def token = tokens[i] switch (token) { case '(': fail("'(' too close to end of expression") { i+2 > tokens.size() } def subGroup = groupByParens(tokens[i+1..-1], depth+1) tokenGroups << subGroup[0..-2] i += subGroup[-1] + 1 break case ')': fail("Unbalanced parens, found extra ')'") { deepness == 0 } tokenGroups << i return tokenGroups default: tokenGroups << token } } fail("Unbalanced parens, unclosed groupings at end of expression") { deepness != 0 } def n = tokenGroups.size() fail("The operand/operator sequence is wrong") { n%2 == 0 } (0..<n).each { def i = it fail("The operand/operator sequence is wrong") { (i%2 == 0) == (tokenGroups[i] instanceof Op) } } tokenGroups }   Expression parse(List elements) { while (elements.size() > 1) { def n = elements.size() fail ("The operand/operator sequence is wrong") { n%2 == 0 } def groupLoc = (0..<n).find { i -> elements[i] instanceof List } if (groupLoc != null) { elements[groupLoc] = parse(elements[groupLoc]) continue } def opLoc = (0..<n).find { i -> elements[i] instanceof Op && elements[i].precedence == 1 } \ ?: (0..<n).find { i -> elements[i] instanceof Op && elements[i].precedence == 2 } if (opLoc != null) { fail ("Operator out of sequence") { opLoc%2 == 0 } def term = new Term(left:elements[opLoc-1], op:elements[opLoc], right:elements[opLoc+1]) elements[(opLoc-1)..(opLoc+1)] = [term] continue } } return elements[0] instanceof List ? parse(elements[0]) : elements[0] }
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Kotlin
Kotlin
// version 1.1.0   import java.awt.* import javax.swing.*   class ArchimedeanSpiral : JPanel() { init { preferredSize = Dimension(640, 640) background = Color.white }   private fun drawGrid(g: Graphics2D) { g.color = Color(0xEEEEEE) g.stroke = BasicStroke(2f) val angle = Math.toRadians(45.0) val w = width val center = w / 2 val margin = 10 val numRings = 8 val spacing = (w - 2 * margin) / (numRings * 2)   for (i in 0 until numRings) { val pos = margin + i * spacing val size = w - (2 * margin + i * 2 * spacing) g.drawOval(pos, pos, size, size) val ia = i * angle val x2 = center + (Math.cos(ia) * (w - 2 * margin) / 2).toInt() val y2 = center - (Math.sin(ia) * (w - 2 * margin) / 2).toInt() g.drawLine(center, center, x2, y2) } }   private fun drawSpiral(g: Graphics2D) { g.stroke = BasicStroke(2f) g.color = Color.magenta val degrees = Math.toRadians(0.1) val center = width / 2 val end = 360 * 2 * 10 * degrees val a = 0.0 val b = 20.0 val c = 1.0 var theta = 0.0 while (theta < end) { val r = a + b * Math.pow(theta, 1.0 / c) val x = r * Math.cos(theta) val y = r * Math.sin(theta) plot(g, (center + x).toInt(), (center - y).toInt()) theta += degrees } }   private fun plot(g: Graphics2D, x: Int, y: Int) { g.drawOval(x, y, 1, 1) }   override fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawGrid(g) drawSpiral(g) } }   fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.title = "Archimedean Spiral" f.isResizable = false f.add(ArchimedeanSpiral(), BorderLayout.CENTER) f.pack() f.setLocationRelativeTo(null) f.isVisible = true } }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Arbre
Arbre
  openshut(n): for x in [1..n] x%n==0   pass(n): if n==100 openshut(n) else openshut(n) xor pass(n+1)   100doors(): pass(1) -> io  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Clean
Clean
array :: {String} array = {"Hello", "World"}
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Hare
Hare
use fmt; use math::complex::{c128,addc128,mulc128,divc128,negc128,conjc128};   export fn main() void = { let x: c128 = (1.0, 1.0); let y: c128 = (3.14159265, 1.2);   // addition let (re, im) = addc128(x, y); fmt::printfln("{} + {}i", re, im)!; // multiplication let (re, im) = mulc128(x, y); fmt::printfln("{} + {}i", re, im)!; // inversion let (re, im) = divc128((1.0, 0.0), x); fmt::printfln("{} + {}i", re, im)!; // negation let (re, im) = negc128(x); fmt::printfln("{} + {}i", re, im)!; // conjugate let (re, im) = conjc128(x); fmt::printfln("{} + {}i", re, im)!; };
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Haskell
Haskell
import Data.Complex   main = do let a = 1.0 :+ 2.0 -- complex number 1+2i let b = 4 -- complex number 4+0i -- 'b' is inferred to be complex because it's used in -- arithmetic with 'a' below. putStrLn $ "Add: " ++ show (a + b) putStrLn $ "Subtract: " ++ show (a - b) putStrLn $ "Multiply: " ++ show (a * b) putStrLn $ "Divide: " ++ show (a / b) putStrLn $ "Negate: " ++ show (-a) putStrLn $ "Inverse: " ++ show (recip a) putStrLn $ "Conjugate:" ++ show (conjugate a)
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Julia
Julia
using Primes divisors(n) = foldl((a, (p, e)) -> vcat((a * [p^i for i in 0:e]')...), factor(n), init=[1])   isperfect(n) = sum(1 // d for d in divisors(n)) == 2   lo, hi = 2, 2^19 println("Perfect numbers between ", lo, " and ", hi, ": ", collect(filter(isperfect, lo:hi)))  
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Modula-2
Modula-2
MODULE AGM; FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE; FROM LongConv IMPORT ValueReal; FROM LongMath IMPORT sqrt; FROM LongStr IMPORT RealToStr; FROM Terminal IMPORT ReadChar,Write,WriteString,WriteLn;   VAR TextWinExSrc : ExceptionSource;   PROCEDURE ReadReal() : LONGREAL; VAR buffer : ARRAY[0..63] OF CHAR; i : CARDINAL; c : CHAR; BEGIN i := 0;   LOOP c := ReadChar(); IF ((c >= '0') AND (c <= '9')) OR (c = '.') THEN buffer[i] := c; Write(c); INC(i) ELSE WriteLn; EXIT END END;   buffer[i] := 0C; RETURN ValueReal(buffer) END ReadReal;   PROCEDURE WriteReal(r : LONGREAL); VAR buffer : ARRAY[0..63] OF CHAR; BEGIN RealToStr(r, buffer); WriteString(buffer) END WriteReal;   PROCEDURE AGM(a,g : LONGREAL) : LONGREAL; CONST iota = 1.0E-16; VAR a1, g1 : LONGREAL; BEGIN IF a * g < 0.0 THEN RAISE(TextWinExSrc, 0, "arithmetic-geometric mean undefined when x*y<0") END;   WHILE ABS(a - g) > iota DO a1 := (a + g) / 2.0; g1 := sqrt(a * g);   a := a1; g := g1 END;   RETURN a END AGM;   VAR x, y, z: LONGREAL; BEGIN WriteString("Enter two numbers: "); x := ReadReal(); y := ReadReal(); WriteReal(AGM(x, y)); WriteLn END AGM.
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#11l
11l
print(0 ^ 0)
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Haskell
Haskell
{-# LANGUAGE FlexibleContexts #-}   import Text.Parsec import Text.Parsec.Expr import Text.Parsec.Combinator import Data.Functor import Data.Function (on)   data Exp = Num Int | Add Exp Exp | Sub Exp Exp | Mul Exp Exp | Div Exp Exp   expr :: Stream s m Char => ParsecT s u m Exp expr = buildExpressionParser table factor where table = [ [op "*" Mul AssocLeft, op "/" Div AssocLeft] , [op "+" Add AssocLeft, op "-" Sub AssocLeft] ] op s f = Infix (f <$ string s) factor = (between `on` char) '(' ')' expr <|> (Num . read <$> many1 digit)   eval :: Integral a => Exp -> a eval (Num x) = fromIntegral x eval (Add a b) = eval a + eval b eval (Sub a b) = eval a - eval b eval (Mul a b) = eval a * eval b eval (Div a b) = eval a `div` eval b   solution :: Integral a => String -> a solution = either (const (error "Did not parse")) eval . parse expr ""   main :: IO () main = print $ solution "(1+3)*7"
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Lua
Lua
  a=1 b=2 cycles=40 step=0.001 x=0 y=0   function love.load() x = love.graphics.getWidth()/2 y = love.graphics.getHeight()/2 end   function love.draw() love.graphics.print("a="..a,16,16) love.graphics.print("b="..b,16,32)   for i=0,cycles*math.pi,step do love.graphics.points(x+(a + b*i)*math.cos(i),y+(a + b*i)*math.sin(i)) end end  
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#M2000_Interpreter
M2000 Interpreter
  module Archimedean_spiral { smooth on ' enable GDI+ def r(θ)=5+3*θ cls #002222,0 pen #FFFF00 refresh 5000 every 1000 { \\ redifine window (console width and height) and place it to center (symbol ;) Window 12, random(10, 18)*1000, random(8, 12)*1000; move scale.x/2, scale.y/2 let N=2, k1=pi/120, k=k1, op=5, op1=1 for i=1 to int(1200*min.data(scale.x, scale.y)/18000) pen op swap op, op1 Width 3 {draw angle k, r(k)*n} k+=k1 next refresh 5000 \\ press space to exit loop if keypress(32) then exit } pen 14 cls 5 refresh 50 } Archimedean_spiral  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Argile
Argile
use std, array   close all doors for each pass from 1 to 100 for (door = pass) (door <= 100) (door += pass) toggle door   let int pass, door.   .: close all doors :. {memset doors 0 size of doors} .:toggle <int door>:. {  !!(doors[door - 1]) }   let doors be an array of 100 bool   for each door from 1 to 100 printf "#%.3d %s\n" door (doors[door - 1]) ? "[ ]", "[X]"
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Clipper
Clipper
// Declare and initialize two-dimensional array Local arr1 := { { "NITEM","N",10,0 }, { "CONTENT","C",60,0} } // Create an empty array Local arr2 := {} // Declare three-dimensional array Local arr3[2,100,3] // Create an array Local arr4 := Array(50)   // Array can be dynamically resized: arr4 := ASize( arr4, 80 )
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Icon_and_Unicon
Icon and Unicon
procedure main()   SetupComplex() a := complex(1,2) b := complex(3,4)   c := complex(&pi,1.5) d := complex(1) e := complex(,1)   every v := !"abcde" do write(v," := ",cpxstr(variable(v)))   write("a+b := ", cpxstr(cpxadd(a,b))) write("a-b := ", cpxstr(cpxsub(a,b))) write("a*b := ", cpxstr(cpxmul(a,b))) write("a/b := ", cpxstr(cpxdiv(a,b))) write("neg(a) := ", cpxstr(cpxneg(a))) write("inv(a) := ", cpxstr(cpxinv(a))) write("conj(a) := ", cpxstr(cpxconj(a))) write("abs(a) := ", cpxabs(a)) write("neg(1) := ", cpxstr(cpxneg(1))) end
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Kotlin
Kotlin
// version 1.1.2   fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)   infix fun Long.ldiv(denom: Long) = Frac(this, denom)   infix fun Int.idiv(denom: Int) = Frac(this.toLong(), denom.toLong())   fun Long.toFrac() = Frac(this, 1)   fun Int.toFrac() = Frac(this.toLong(), 1)   class Frac : Comparable<Frac> { val num: Long val denom: Long   companion object { val ZERO = Frac(0, 1) val ONE = Frac(1, 1) }   constructor(n: Long, d: Long) { require(d != 0L) var nn = n var dd = d if (nn == 0L) { dd = 1 } else if (dd < 0) { nn = -nn dd = -dd } val g = Math.abs(gcd(nn, dd)) if (g > 1) { nn /= g dd /= g } num = nn denom = dd }   constructor(n: Int, d: Int) : this(n.toLong(), d.toLong())   operator fun plus(other: Frac) = Frac(num * other.denom + denom * other.num, other.denom * denom)   operator fun unaryPlus() = this   operator fun unaryMinus() = Frac(-num, denom)   operator fun minus(other: Frac) = this + (-other)   operator fun times(other: Frac) = Frac(this.num * other.num, this.denom * other.denom)   operator fun rem(other: Frac) = this - Frac((this / other).toLong(), 1) * other   operator fun inc() = this + ONE operator fun dec() = this - ONE   fun inverse(): Frac { require(num != 0L) return Frac(denom, num) }   operator fun div(other: Frac) = this * other.inverse()   fun abs() = if (num >= 0) this else -this   override fun compareTo(other: Frac): Int { val diff = this.toDouble() - other.toDouble() return when { diff < 0.0 -> -1 diff > 0.0 -> +1 else -> 0 } }   override fun equals(other: Any?): Boolean { if (other == null || other !is Frac) return false return this.compareTo(other) == 0 }   override fun hashCode() = num.hashCode() xor denom.hashCode()   override fun toString() = if (denom == 1L) "$num" else "$num/$denom"   fun toDouble() = num.toDouble() / denom   fun toLong() = num / denom }   fun isPerfect(n: Long): Boolean { var sum = Frac(1, n) val limit = Math.sqrt(n.toDouble()).toLong() for (i in 2L..limit) { if (n % i == 0L) sum += Frac(1, i) + Frac(1, n / i) } return sum == Frac.ONE }   fun main(args: Array<String>) { var frac1 = Frac(12, 3) println ("frac1 = $frac1") var frac2 = 15 idiv 2 println("frac2 = $frac2") println("frac1 <= frac2 is ${frac1 <= frac2}") println("frac1 >= frac2 is ${frac1 >= frac2}") println("frac1 == frac2 is ${frac1 == frac2}") println("frac1 != frac2 is ${frac1 != frac2}") println("frac1 + frac2 = ${frac1 + frac2}") println("frac1 - frac2 = ${frac1 - frac2}") println("frac1 * frac2 = ${frac1 * frac2}") println("frac1 / frac2 = ${frac1 / frac2}") println("frac1 % frac2 = ${frac1 % frac2}") println("inv(frac1) = ${frac1.inverse()}") println("abs(-frac1) = ${-frac1.abs()}") println("inc(frac2) = ${++frac2}") println("dec(frac2) = ${--frac2}") println("dbl(frac2) = ${frac2.toDouble()}") println("lng(frac2) = ${frac2.toLong()}") println("\nThe Perfect numbers less than 2^19 are:") // We can skip odd numbers as no known perfect numbers are odd for (i in 2 until (1 shl 19) step 2) { if (isPerfect(i.toLong())) print(" $i") } println() }
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   numeric digits 18 parse arg a_ g_ . if a_ = '' | a_ = '.' then a0 = 1 else a0 = a_ if g_ = '' | g_ = '.' then g0 = 1 / Math.sqrt(2) else g0 = g_   say agm(a0, g0)   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method agm(a0, g0) public static returns Rexx a1 = a0 g1 = g0 loop while (a1 - g1).abs() >= Math.pow(10, -14) temp = (a1 + g1) / 2 g1 = Math.sqrt(a1 * g1) a1 = temp end return a1 + 0  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#8th
8th
  0 0 ^ .  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   PROC Main() REAL z,res   Put(125) PutE() ;clear the screen   IntToReal(0,z) Power(z,z,res)   PrintR(z) Print("^") PrintR(z) Print("=") PrintRE(res) RETURN
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Icon_and_Unicon
Icon and Unicon
procedure main() #: simple arithmetical parser / evaluator write("Usage: Input expression = Abstract Syntax Tree = Value, ^Z to end.") repeat { writes("Input expression : ") if not writes(line := read()) then break if map(line) ? { (x := E()) & pos(0) } then write(" = ", showAST(x), " = ", evalAST(x)) else write(" rejected") } end   procedure evalAST(X) #: return the evaluated AST local x   if type(X) == "list" then { x := evalAST(get(X)) while x := get(X)(x, evalAST(get(X) | stop("Malformed AST."))) } return \x | X end   procedure showAST(X) #: return a string representing the AST local x,s   s := "" every x := !X do s ||:= if type(x) == "list" then "(" || showAST(x) || ")" else x return s end   ######## # When you're writing a big parser, a few utility recognisers are very useful # procedure ws() # skip optional whitespace suspend tab(many(' \t')) | "" end   procedure digits() suspend tab(many(&digits)) end   procedure radixNum(r) # r sets the radix static chars initial chars := &digits || &lcase suspend tab(many(chars[1 +: r])) end ########   global token record HansonsDevice(precedence,associativity)   procedure opinfo() static O initial { O := HansonsDevice([], table(&null)) # parsing table put(O.precedence, ["+", "-"], ["*", "/", "%"], ["^"]) # Lowest to Highest precedence every O.associativity[!!O.precedence] := 1 # default to 1 for LEFT associativity O.associativity["^"] := 0 # RIGHT associativity } return O end   procedure E(k) #: Expression local lex, pL static opT initial opT := opinfo()   /k := 1 lex := [] if not (pL := opT.precedence[k]) then # this op at this level? put(lex, F()) else { put(lex, E(k + 1)) while ws() & put(lex, token := =!pL) do put(lex, E(k + opT.associativity[token])) } suspend if *lex = 1 then lex[1] else lex # strip useless [] end   procedure F() #: Factor suspend ws() & ( # skip optional whitespace, and ... (="+" & F()) | # unary + and a Factor, or ... (="-" || V()) | # unary - and a Value, or ... (="-" & [-1, "*", F()]) | # unary - and a Factor, or ... 2(="(", E(), ws(), =")") | # parenthesized subexpression, or ... V() # just a value ) end   procedure V() #: Value local r suspend ws() & numeric( # skip optional whitespace, and ... =(r := 1 to 36) || ="r" || radixNum(r) | # N-based number, or ... digits() || (="." || digits() | "") || exponent() # plain number with optional fraction ) end   procedure exponent() suspend tab(any('eE')) || =("+" | "-" | "") || digits() | "" end
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Maple
Maple
  plots[polarplot](1+2*theta, theta = 0 .. 6*Pi)  
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
With[{a = 5, b = 4}, PolarPlot[a + b t, {t, 0, 10 Pi}]]
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#MATLAB
MATLAB
a = 1; b = 1; turns = 2; theta = 0:0.1:2*turns*pi; polarplot(theta, a + b*theta);
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program 100doors.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall .equ NBDOORS, 100 /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .ascii "The door " sMessValeur: .fill 11, 1, ' ' @ size => 11 .asciz "is open.\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss stTableDoors: .skip 4 * NBDOORS /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program push {fp,lr} @ saves 2 registers @ display first line ldr r3,iAdrstTableDoors @ table address mov r5,#1 1: mov r4,r5 2: @ begin loop ldr r2,[r3,r4,lsl #2] @ read doors index r4 cmp r2,#0 moveq r2,#1 @ if r2 = 0 1 -> r2 movne r2,#0 @ if r2 = 1 0 -> r2 str r2,[r3,r4,lsl #2] @ store value of doors add r4,r5 @ increment r4 with r5 value cmp r4,#NBDOORS @ number of doors ? ble 2b @ no -> loop add r5,#1 @ increment the increment !! cmp r5,#NBDOORS @ number of doors ? ble 1b @ no -> loop   @ loop display state doors mov r4,#0 3: ldr r2,[r3,r4,lsl #2] @ read state doors r4 index cmp r2,#0 beq 4f mov r0,r4 @ open -> display message ldr r1,iAdrsMessValeur @ display value index bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message 4: add r4,#1 cmp r4,#NBDOORS ble 3b @ loop     100: @ standard end of the program mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrsMessValeur: .int sMessValeur iAdrstTableDoors: .int stTableDoors iAdrsMessResult: .int sMessResult   /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* r0 contains value and r1 address area */ /* r0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL   1: @ start loop bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ else previous position bne 1b @ and loop // and move digit from left of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] add r2,#1 add r4,#1 cmp r2,#LGZONECAL ble 2b // and move spaces in end on area mov r0,r4 @ result length mov r1,#' ' @ space 3: strb r1,[r3,r4] @ store space in area add r4,#1 @ next position cmp r4,#LGZONECAL ble 3b @ loop if r4 <= area size   100: pop {r1-r4,lr} @ restaur registres bx lr @return   /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value //mov r3,#0xCCCD @ r3 <- magic_number lower @ for Raspberry pi 3 //movt r3,#0xCCCC @ r3 <- magic_number upper @ for Raspberry pi 3 ldr r3,iMagicNumber @ for Raspberry pi 1 2 umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function iMagicNumber: .int 0xCCCCCCCD  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Clojure
Clojure
;clojure is a language built with immutable/persistent data structures. there is no concept of changing what a vector/list ;is, instead clojure creates a new array with an added value using (conj...) ;in the example below the my-list does not change.     user=> (def my-list (list 1 2 3 4 5))   user=> my-list (1 2 3 4 5)   user=> (first my-list) 1   user=> (nth my-list 3) 4   user=> (conj my-list 100) ;adding to a list always adds to the head of the list (100 1 2 3 4 5)   user=> my-list ;it is impossible to change the list pointed to by my-list (1 2 3 4 5)   user=> (def my-new-list (conj my-list 100))   user=> my-new-list (100 1 2 3 4 5)   user=> (cons 200 my-new-list) ;(cons makes a new list, (conj will make a new object of the same type as the one it is given (200 100 1 2 3 4 5)   user=> (def my-vec [1 2 3 4 5 6])   user=> (conj my-vec 300) ;adding to a vector always adds to the end of the vector [1 2 3 4 5 6 300]
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#IDL
IDL
x=complex(1,1) y=complex(!pi,1.2) print,x+y ( 4.14159, 2.20000) print,x*y ( 1.94159, 4.34159) print,-x ( -1.00000, -1.00000) print,1/x ( 0.500000, -0.500000)
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Liberty_BASIC
Liberty BASIC
  n=2^19 for testNumber=1 to n sum$=castToFraction$(0) for factorTest=1 to sqr(testNumber) if GCD(factorTest,testNumber)=factorTest then sum$=add$(sum$,add$(reciprocal$(castToFraction$(factorTest)),reciprocal$(castToFraction$(testNumber/factorTest)))) next factorTest if equal(sum$,castToFraction$(2))=1 then print testNumber next testNumber end   function abs$(a$) aNumerator=val(word$(a$,1,"/")) aDenominator=val(word$(a$,2,"/")) bNumerator=abs(aNumerator) bDenominator=abs(aDenominator) b$=str$(bNumerator)+"/"+str$(bDenominator) abs$=simplify$(b$) end function   function negate$(a$) aNumerator=val(word$(a$,1,"/")) aDenominator=val(word$(a$,2,"/")) bNumerator=-1*aNumerator bDenominator=aDenominator b$=str$(bNumerator)+"/"+str$(bDenominator) negate$=simplify$(b$) end function   function add$(a$,b$) aNumerator=val(word$(a$,1,"/")) aDenominator=val(word$(a$,2,"/")) bNumerator=val(word$(b$,1,"/")) bDenominator=val(word$(b$,2,"/")) cNumerator=(aNumerator*bDenominator+bNumerator*aDenominator) cDenominator=aDenominator*bDenominator c$=str$(cNumerator)+"/"+str$(cDenominator) add$=simplify$(c$) end function   function subtract$(a$,b$) aNumerator=val(word$(a$,1,"/")) aDenominator=val(word$(a$,2,"/")) bNumerator=val(word$(b$,1,"/")) bDenominator=val(word$(b$,2,"/")) cNumerator=(aNumerator*bDenominator-bNumerator*aDenominator) cDenominator=aDenominator*bDenominator c$=str$(cNumerator)+"/"+str$(cDenominator) subtract$=simplify$(c$) end function   function multiply$(a$,b$) aNumerator=val(word$(a$,1,"/")) aDenominator=val(word$(a$,2,"/")) bNumerator=val(word$(b$,1,"/")) bDenominator=val(word$(b$,2,"/")) cNumerator=aNumerator*bNumerator cDenominator=aDenominator*bDenominator c$=str$(cNumerator)+"/"+str$(cDenominator) multiply$=simplify$(c$) end function   function divide$(a$,b$) divide$=multiply$(a$,reciprocal$(b$)) end function   function simplify$(a$) aNumerator=val(word$(a$,1,"/")) aDenominator=val(word$(a$,2,"/")) gcd=GCD(aNumerator,aDenominator) if aNumerator<0 and aDenominator<0 then gcd=-1*gcd bNumerator=aNumerator/gcd bDenominator=aDenominator/gcd b$=str$(bNumerator)+"/"+str$(bDenominator) simplify$=b$ end function   function reciprocal$(a$) aNumerator=val(word$(a$,1,"/")) aDenominator=val(word$(a$,2,"/")) reciprocal$=str$(aDenominator)+"/"+str$(aNumerator) end function   function equal(a$,b$) if simplify$(a$)=simplify$(b$) then equal=1:else equal=0 end function   function castToFraction$(a) do exp=exp+1 a=a*10 loop until a=int(a) castToFraction$=simplify$(str$(a)+"/"+str$(10^exp)) end function   function castToReal(a$) aNumerator=val(word$(a$,1,"/")) aDenominator=val(word$(a$,2,"/")) castToReal=aNumerator/aDenominator end function   function castToInt(a$) castToInt=int(castToReal(a$)) end function   function GCD(a,b) if a=0 then GCD=1 else if a>=b then while b c = a a = b b = c mod b GCD = abs(a) wend else GCD=GCD(b,a) end if end if end function  
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#NewLISP
NewLISP
  (define (a-next a g) (mul 0.5 (add a g)))   (define (g-next a g) (sqrt (mul a g)))   (define (amg a g tolerance) (if (<= (sub a g) tolerance) a (amg (a-next a g) (g-next a g) tolerance) ) )   (define quadrillionth 0.000000000000001)   (define root-reciprocal-2 (div 1.0 (sqrt 2.0)))   (println "To the nearest one-quadrillionth, " "the arithmetic-geometric mean of " "1 and the reciprocal of the square root of 2 is " (amg 1.0 root-reciprocal-2 quadrillionth) )  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Ada
Ada
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Long_Integer_Text_IO, Ada.Long_Long_Integer_Text_IO, Ada.Float_Text_IO, Ada.Long_Float_Text_IO, Ada.Long_Long_Float_Text_IO; use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Long_Integer_Text_IO, Ada.Long_Long_Integer_Text_IO, Ada.Float_Text_IO, Ada.Long_Float_Text_IO, Ada.Long_Long_Float_Text_IO;   procedure Test5 is   I  : Integer  := 0; LI  : Long_Integer  := 0; LLI  : Long_Long_Integer := 0; F  : Float  := 0.0; LF  : Long_Float  := 0.0; LLF  : Long_Long_Float  := 0.0; Zero : Natural  := 0;   begin Put ("Integer 0^0 = "); Put (I ** Zero, 2); New_Line; Put ("Long Integer 0^0 = "); Put (LI ** Zero, 2); New_Line; Put ("Long Long Integer 0^0 = "); Put (LLI ** Zero, 2); New_Line; Put ("Float 0.0^0 = "); Put (F ** Zero); New_Line; Put ("Long Float 0.0^0 = "); Put (LF ** Zero); New_Line; Put ("Long Long Float 0.0^0 = "); Put (LLF ** Zero); New_Line; end Test5;