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/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.
#Component_Pascal
Component Pascal
  MODULE Complex; IMPORT StdLog; TYPE Complex* = POINTER TO ComplexDesc; ComplexDesc = RECORD r-,i-: REAL; END;   VAR r,x,y: Complex;   PROCEDURE New(x,y: REAL): Complex; VAR r: Complex; BEGIN NEW(r);r.r := x;r.i := y; RETURN r END New;   PROCEDURE (x: Complex) Add*(y: Complex): Complex,NEW; BEGIN RETURN New(x.r + y.r,x.i + y.i) END Add;   PROCEDURE ( x: Complex) Sub*( y: Complex): Complex, NEW; BEGIN RETURN New(x.r - y.r,x.i - y.i) END Sub;   PROCEDURE ( x: Complex) Mul*( y: Complex): Complex, NEW; BEGIN RETURN New(x.r*y.r - x.i*y.i,x.r*y.i + x.i*y.r) END Mul;   PROCEDURE ( x: Complex) Div*( y: Complex): Complex, NEW; VAR d: REAL; BEGIN d := y.r * y.r + y.i * y.i; RETURN New((x.r*y.r + x.i*y.i)/d,(x.i*y.r - x.r*y.i)/d) END Div;   (* Reciprocal *) PROCEDURE (x: Complex) Rec*(): Complex,NEW; VAR d: REAL; BEGIN d := x.r * x.r + x.i * x.i; RETURN New(x.r/d,(-1.0 * x.i)/d); END Rec;   (* Conjugate *) PROCEDURE (x: Complex) Con*(): Complex,NEW; BEGIN RETURN New(x.r, (-1.0) * x.i); END Con;   PROCEDURE (x: Complex) Out(),NEW; BEGIN StdLog.String("Complex("); StdLog.Real(x.r);StdLog.String(',');StdLog.Real(x.i); StdLog.String("i );") END Out;   PROCEDURE Do*; BEGIN x := New(1.5,3); y := New(1.0,1.0);   StdLog.String("x: ");x.Out();StdLog.Ln; StdLog.String("y: ");y.Out();StdLog.Ln; r := x.Add(y); StdLog.String("x + y: ");r.Out();StdLog.Ln; r := x.Sub(y); StdLog.String("x - y: ");r.Out();StdLog.Ln; r := x.Mul(y); StdLog.String("x * y: ");r.Out();StdLog.Ln; r := x.Div(y); StdLog.String("x / y: ");r.Out();StdLog.Ln; r := y.Rec(); StdLog.String("1 / y: ");r.Out();StdLog.Ln; r := x.Con(); StdLog.String("x': ");r.Out();StdLog.Ln; END Do;   END Complex.  
http://rosettacode.org/wiki/Arena_storage_pool
Arena storage pool
Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a reference to the object. The storage pool chosen by the allocator can be determined by either: the object type   T the type of pointer   P In the former case objects can be allocated only in one storage pool. In the latter case objects of the type can be allocated in any storage pool or on the stack. Task The task is to show how allocators and user-defined storage pools are supported by the language. In particular: define an arena storage pool.   An arena is a pool in which objects are allocated individually, but freed by groups. allocate some objects (e.g., integers) in the pool. Explain what controls the storage pool choice in the language.
#Wren
Wren
var arena = List.filled(5, 0) // allocate memory for 5 integers for (i in 0..4) arena[i] = i // insert some integers System.print(arena) // print them arena = null // make arena eligible for garbage collection System.gc() // request immediate garbage collection
http://rosettacode.org/wiki/Arena_storage_pool
Arena storage pool
Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a reference to the object. The storage pool chosen by the allocator can be determined by either: the object type   T the type of pointer   P In the former case objects can be allocated only in one storage pool. In the latter case objects of the type can be allocated in any storage pool or on the stack. Task The task is to show how allocators and user-defined storage pools are supported by the language. In particular: define an arena storage pool.   An arena is a pool in which objects are allocated individually, but freed by groups. allocate some objects (e.g., integers) in the pool. Explain what controls the storage pool choice in the language.
#zkl
zkl
var pool=List(); // pool could be any mutable container pool.append(Data(0,1234)); // allocate mem blob and add to pool pool=Void; // free the pool and everything in it.
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
#Elisa
Elisa
component RationalNumbers; type Rational; Rational(Numerator = integer, Denominater = integer) -> Rational;   Rational + Rational -> Rational; Rational - Rational -> Rational; Rational * Rational -> Rational; Rational / Rational -> Rational;   Rational == Rational -> boolean; Rational <> Rational -> boolean; Rational >= Rational -> boolean; Rational <= Rational -> boolean; Rational > Rational -> boolean; Rational < Rational -> boolean;   + Rational -> Rational; - Rational -> Rational; abs(Rational) -> Rational;   Rational(integer) -> Rational; Numerator(Rational) -> integer; Denominator(Rational) -> integer; begin Rational(A,B) = Rational:[A;B];   R1 + R2 = Normalize( R1.A * R2.B + R1.B * R2.A, R1.B * R2.B); R1 - R2 = Normalize( R1.A * R2.B - R1.B * R2.A, R1.B * R2.B); R1 * R2 = Normalize( R1.A * R2.A, R1.B * R2.B); R1 / R2 = Normalize( R1.A * R2.B, R1.B * R2.A);   R1 == R2 = [ R = (R1 - R2); R.A == 0]; R1 <> R2 = [ R = (R1 - R2); R.A <> 0]; R1 >= R2 = [ R = (R1 - R2); R.A >= 0]; R1 <= R2 = [ R = (R1 - R2); R.A <= 0]; R1 > R2 = [ R = (R1 - R2); R.A > 0]; R1 < R2 = [ R = (R1 - R2); R.A < 0];   + R = R; - R = Rational(-R.A, R.B);   abs(R) = Rational(abs(R.A), abs(R.B)); Rational(I) = Rational (I, 1); Numerator(R) = R.A; Denominator(R) = R.B;   << internal definitions >>   Normalize (A = integer, B = integer) -> Rational; Normalize (A, B) = [ exception( B == 0, "Illegal Rational Number"); Common = GCD(abs(A), abs(B)); if B < 0 then Rational(-A / Common, -B / Common) else Rational( A / Common, B / Common) ];   GCD (A = integer, B = integer) -> integer; GCD (A, B) = [ if A == 0 then return(B); if B == 0 then return(A); if A > B then GCD (B, mod(A,B)) else GCD (A, mod(B,A)) ];   end component RationalNumbers;
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
#EchoLisp
EchoLisp
  (lib 'math)   (define (agm a g) (if (~= a g) a (agm (// (+ a g ) 2) (sqrt (* a g)))))   (math-precision) → 0.000001 ;; default (agm 1 (/ 1 (sqrt 2))) → 0.8472130848351929 (math-precision 1.e-15) → 1e-15 (agm 1 (/ 1 (sqrt 2))) → 0.8472130847939792  
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.
#Verilog
Verilog
module main; integer a, b; integer suma, resta, producto; integer division, resto, expo;   initial begin a = -12; b = 7;   suma = a + b; resta = a - b; producto = a * b; division = a / b; resto = a % b; expo = a ** b;   $display("Siendo dos enteros a = -12 y b = 7"); $display(" suma de a + b = ", suma); $display(" resta de a - b = ", resta); $display(" producto de a * b = ", producto); $display(" división de a / b = ", division); $display(" resto de a mod b = ", resto); $display("exponenciación a ^ b = ", expo); $finish ; end endmodule
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.
#ALGOL_68
ALGOL 68
INT base=10; MODE FIXED = LONG REAL; # numbers in the format 9,999.999 #   #IF build abstract syntax tree and then EVAL tree # MODE AST = UNION(NODE, FIXED); MODE NUM = REF AST; MODE NODE = STRUCT(NUM a, PROC (FIXED,FIXED)FIXED op, NUM b);   OP EVAL = (NUM ast)FIXED:( CASE ast IN (FIXED num): num, (NODE fork): (op OF fork)(EVAL( a OF fork), EVAL (b OF fork)) ESAC );   OP + = (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a+b, b) ); OP - = (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a-b, b) ); OP * = (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a*b, b) ); OP / = (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a/b, b) ); OP **= (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a**b, b) );   #ELSE simply use REAL arithmetic with no abstract syntax tree at all # CO MODE NUM = FIXED, AST = FIXED; OP EVAL = (FIXED num)FIXED: num; #FI# END CO   MODE LEX = PROC (TOK)NUM; MODE MONADIC =PROC (NUM)NUM; MODE DIADIC = PROC (NUM,NUM)NUM;   MODE TOK = CHAR; MODE ACTION = UNION(STACKACTION, LEX, MONADIC, DIADIC); MODE OPVAL = STRUCT(INT prio, ACTION action); MODE OPITEM = STRUCT(TOK token, OPVAL opval);   [256]STACKITEM stack; MODE STACKITEM = STRUCT(NUM value, OPVAL op); MODE STACKACTION = PROC (REF STACKITEM)VOID;   PROC begin = (REF STACKITEM top)VOID: prio OF op OF top -:= +10; PROC end = (REF STACKITEM top)VOID: prio OF op OF top -:= -10;   OP ** = (COMPL a,b)COMPL: complex exp(complex ln(a)*b);   [8]OPITEM op list :=( # OP PRIO ACTION # ("^", (8, (NUM a,b)NUM: a**b)), ("*", (7, (NUM a,b)NUM: a*b)), ("/", (7, (NUM a,b)NUM: a/b)), ("+", (6, (NUM a,b)NUM: a+b)), ("-", (6, (NUM a,b)NUM: a-b)), ("(",(+10, begin)), (")",(-10, end)), ("?", (9, LEX:SKIP)) );   PROC op dict = (TOK op)REF OPVAL:( # This can be unrolled to increase performance # REF OPITEM candidate; FOR i TO UPB op list WHILE candidate := op list[i]; # WHILE # op /= token OF candidate DO SKIP OD; opval OF candidate );   PROC build ast = (STRING expr)NUM:(   INT top:=0;   PROC compress ast stack = (INT prio, NUM in value)NUM:( NUM out value := in value; FOR loc FROM top BY -1 TO 1 WHILE REF STACKITEM stack top := stack[loc]; # WHILE # ( top >= LWB stack | prio <= prio OF op OF stack top | FALSE ) DO top := loc - 1; out value := CASE action OF op OF stack top IN (MONADIC op): op(value OF stack top), # not implemented # (DIADIC op): op(value OF stack top,out value) ESAC OD; out value );   NUM value := NIL; FIXED num value; INT decimal places;   FOR i TO UPB expr DO TOK token = expr[i]; REF OPVAL this op := op dict(token); CASE action OF this op IN (STACKACTION action):( IF prio OF thisop = -10 THEN value := compress ast stack(0, value) FI; IF top >= LWB stack THEN action(stack[top]) FI ), (LEX):( # a crude lexer # SHORT INT digit = ABS token - ABS "0"; IF 0<= digit AND digit < base THEN IF NUM(value) IS NIL THEN # first digit # decimal places := 0; value := HEAP AST := num value := digit ELSE NUM(value) := num value := IF decimal places = 0 THEN num value * base + digit ELSE decimal places *:= base; num value + digit / decimal places FI FI ELIF token = "." THEN decimal places := 1 ELSE SKIP # and ignore spaces and any unrecognised characters # FI ), (MONADIC): SKIP, # not implemented # (DIADIC):( value := compress ast stack(prio OF this op, value); IF top=UPB stack THEN index error FI; stack[top+:=1]:=STACKITEM(value, this op); value:=NIL ) ESAC OD; compress ast stack(-max int, value) );   test:( printf(($" euler's number is about: "g(-long real width,long real width-2)l$, EVAL build ast("1+1+(1+(1+(1+(1+(1+(1+(1+(1+(1+(1+(1+(1+(1+1/15)/14)/13)/12)/11)/10)/9)/8)/7)/6)/5)/4)/3)/2"))); SKIP EXIT index error: printf(("Stack over flow")) )
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.
#8th
8th
  \ Array of doors; init to empty; accessing a non-extant member will return \ 'null', which is treated as 'false', so we don't need to initialize it: [] var, doors   \ given a door number, get the value and toggle it: : toggle-door \ n -- doors @ over a:@ not rot swap a:! drop ;   \ print which doors are open: : .doors ( doors @ over a:@ nip if . space else drop then ) 1 100 loop ;   \ iterate over the doors, skipping 'n': : main-pass \ n -- 0 true repeat drop dup toggle-door over n:+ dup 101 < while 2drop drop ;   \ calculate the first 100 doors: ' main-pass 1 100 loop \ print the results: .doors cr bye  
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π = 4 a g m ( 1 , 1 / 2 ) 2 1 − ∑ n = 1 ∞ 2 n + 1 ( a n 2 − g n 2 ) {\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}} This allows you to make the approximation, for any large   N: π ≈ 4 a N 2 1 − ∑ k = 1 N 2 k + 1 ( a k 2 − g k 2 ) {\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of π {\displaystyle \pi } .
#Ruby
Ruby
# Calculate Pi using the Arithmetic Geometric Mean of 1 and 1/sqrt(2) # # # Nigel_Galloway # March 8th., 2012. # require 'flt' Flt::BinNum.Context.precision = 8192 a = n = 1 g = 1 / Flt::BinNum(2).sqrt z = 0.25 (0..17).each{ x = [(a + g) * 0.5, (a * g).sqrt] var = x[0] - a z -= var * var * n n += n a = x[0] g = x[1] } puts a * a / z
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π = 4 a g m ( 1 , 1 / 2 ) 2 1 − ∑ n = 1 ∞ 2 n + 1 ( a n 2 − g n 2 ) {\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}} This allows you to make the approximation, for any large   N: π ≈ 4 a N 2 1 − ∑ k = 1 N 2 k + 1 ( a k 2 − g k 2 ) {\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of π {\displaystyle \pi } .
#Rust
Rust
/// calculate pi with algebraic/geometric mean pub fn pi(n: usize) -> f64 { let mut a : f64 = 1.0; let two : f64= 2.0; let mut g = 1.0 / two.sqrt(); let mut s = 0.0; let mut k = 1; while k<=n {   let a1 = (a+g)/two; let g1 = (a*g).sqrt(); a = a1; g = g1; s += (a.powi(2)-g.powi(2)) * two.powi((k+1) as i32); k += 1;     }   4.0 * a.powi(2) / (1.0-s) }  
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)
#Babel
Babel
[1 2 3]
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.
#D
D
import std.stdio, std.complex;   void main() { auto x = complex(1, 1); // complex of doubles on default auto y = complex(3.14159, 1.2);   writeln(x + y); // addition writeln(x * y); // multiplication writeln(1.0 / x); // inversion writeln(-x); // negation }
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
#Elixir
Elixir
defmodule Rational do import Kernel, except: [div: 2]   defstruct numerator: 0, denominator: 1   def new(numerator), do: %Rational{numerator: numerator, denominator: 1}   def new(numerator, denominator) do sign = if numerator * denominator < 0, do: -1, else: 1 {numerator, denominator} = {abs(numerator), abs(denominator)} gcd = gcd(numerator, denominator)  %Rational{numerator: sign * Kernel.div(numerator, gcd), denominator: Kernel.div(denominator, gcd)} end   def add(a, b) do {a, b} = convert(a, b) new(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator) end   def sub(a, b) do {a, b} = convert(a, b) new(a.numerator * b.denominator - b.numerator * a.denominator, a.denominator * b.denominator) end   def mult(a, b) do {a, b} = convert(a, b) new(a.numerator * b.numerator, a.denominator * b.denominator) end   def div(a, b) do {a, b} = convert(a, b) new(a.numerator * b.denominator, a.denominator * b.numerator) end   defp convert(a), do: if is_integer(a), do: new(a), else: a   defp convert(a, b), do: {convert(a), convert(b)}   defp gcd(a, 0), do: a defp gcd(a, b), do: gcd(b, rem(a, b)) end   defimpl Inspect, for: Rational do def inspect(r, _opts) do "%Rational<#{r.numerator}/#{r.denominator}>" end end   Enum.each(2..trunc(:math.pow(2,19)), fn candidate -> sum = 2 .. round(:math.sqrt(candidate)) |> Enum.reduce(Rational.new(1, candidate), fn factor,sum -> if rem(candidate, factor) == 0 do Rational.add(sum, Rational.new(1, factor)) |> Rational.add(Rational.new(1, div(candidate, factor))) else sum end end) if sum.denominator == 1 do  :io.format "Sum of recipr. factors of ~6w = ~w exactly ~s~n", [candidate, sum.numerator, (if sum.numerator == 1, do: "perfect!", else: "")] end 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
#Elixir
Elixir
defmodule ArithhGeom do def mean(a,g,tol) when abs(a-g) <= tol, do: a def mean(a,g,tol) do mean((a+g)/2,:math.pow(a*g, 0.5),tol) end end   IO.puts ArithhGeom.mean(1,1/:math.sqrt(2),0.0000000001)
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
#Erlang
Erlang
%% Arithmetic Geometric Mean of 1 and 1 / sqrt(2) %% Author: Abhay Jain   -module(agm_calculator). -export([find_agm/0]). -define(TOLERANCE, 0.0000000001).   find_agm() -> A = 1, B = 1 / (math:pow(2, 0.5)), AGM = agm(A, B), io:format("AGM = ~p", [AGM]).   agm (A, B) when abs(A-B) =< ?TOLERANCE -> A; agm (A, B) -> A1 = (A+B) / 2, B1 = math:pow(A*B, 0.5), agm(A1, B1).
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.
#Vim_Script
Vim Script
let a = float2nr(input("Number 1: ") + 0) let b = float2nr(input("Number 2: ") + 0) echo "\nSum: " . (a + b) echo "Difference: " . (a - b) echo "Product: " . (a * b) " The result of an integer division is truncated echo "Quotient: " . (a / b) " The sign of the result of the remainder operation matches the sign of " the first operand echo "Remainder: " . (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.
#AutoHotkey
AutoHotkey
/* hand coded recursive descent parser expr : term ( ( PLUS | MINUS ) term )* ; term : factor ( ( MULT | DIV ) factor )* ; factor : NUMBER | '(' expr ')'; */   calcLexer := makeCalcLexer() string := "((3+4)*(7*9)+3)+4" tokens := tokenize(string, calcLexer) msgbox % printTokens(tokens) ast := expr() msgbox % printTree(ast) msgbox % expression := evalTree(ast) filedelete expression.ahk fileappend, % "msgbox % " expression, expression.ahk run, expression.ahk return     expr() { global tokens ast := object(1, "expr") if node := term() ast._Insert(node) loop { if peek("PLUS") or peek("MINUS") { op := getsym() newop := object(1, op.type, 2, op.value) node := term() ast._Insert(newop) ast._Insert(node) } Else Break } return ast }   term() { global tokens tree := object(1, "term") if node := factor() tree._Insert(node) loop { if peek("MULT") or peek("DIV") { op := getsym() newop := object(1, op.type, 2, op.value) node := factor() tree._Insert(newop) tree._Insert(node) } else Break } return tree }   factor() { global tokens if peek("NUMBER") { token := getsym() tree := object(1, token.type, 2, token.value) return tree } else if peek("OPEN") { getsym() tree := expr() if peek("CLOSE") { getsym() return tree } else error("miss closing parentheses ") } else error("no factor found") }   peek(type, n=1) { global tokens if (tokens[n, "type"] == type) return 1 }   getsym(n=1) { global tokens return token := tokens._Remove(n) }   error(msg) { global tokens msgbox % msg " at:`n" printToken(tokens[1]) }     printTree(ast) { if !ast return   n := 0 loop { n += 1 if !node := ast[n] break if !isobject(node) treeString .= node else treeString .= printTree(node) } return ("(" treeString ")" ) }   evalTree(ast) { if !ast return   n := 1 loop { n += 1 if !node := ast[n] break if !isobject(node) treeString .= node else treeString .= evalTree(node) } if (n == 3) return treeString return ("(" treeString ")" ) }   #include calclex.ahk
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program 100doors64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ NBDOORS, 100 /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "The door @ is open.\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss stTableDoors: .skip 8 * NBDOORS sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program // display first line ldr x3,qAdrstTableDoors // table address mov x5,1 1: mov x4,x5 2: // begin loop ldr x2,[x3,x4,lsl #3] // read doors index x4 cmp x2,#0 cset x2,eq //moveq x2,#1 // if x2 = 0 1 -> x2 //movne x2,#0 // if x2 = 1 0 -> x2 str x2,[x3,x4,lsl #3] // store value of doors add x4,x4,x5 // increment x4 with x5 value cmp x4,NBDOORS // number of doors ? ble 2b // no -> loop add x5,x5,#1 // increment the increment !! cmp x5,NBDOORS // number of doors ? ble 1b // no -> loop   // loop display state doors mov x4,#0 3: ldr x2,[x3,x4,lsl #3] // read state doors x4 index cmp x2,#0 beq 4f mov x0,x4 // open -> display message ldr x1,qAdrsZoneConv // display value index bl conversion10 // call function ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at first @ character bl affichageMess // display message 4: add x4,x4,1 cmp x4,NBDOORS ble 3b // loop     100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrstTableDoors: .quad stTableDoors qAdrsMessResult: .quad sMessResult qAdrsZoneConv: .quad sZoneConv /***********************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π = 4 a g m ( 1 , 1 / 2 ) 2 1 − ∑ n = 1 ∞ 2 n + 1 ( a n 2 − g n 2 ) {\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}} This allows you to make the approximation, for any large   N: π ≈ 4 a N 2 1 − ∑ k = 1 N 2 k + 1 ( a k 2 − g k 2 ) {\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of π {\displaystyle \pi } .
#Scala
Scala
import java.math.MathContext   import scala.annotation.tailrec import scala.compat.Platform.currentTime import scala.math.BigDecimal   object Calculate_Pi extends App { val precision = new MathContext(32768 /*65536*/) val (bigZero, bigOne, bigTwo, bigFour) = (BigDecimal(0, precision), BigDecimal(1, precision), BigDecimal(2, precision), BigDecimal(4, precision))   def bigSqrt(bd: BigDecimal) = { @tailrec def iter(x0: BigDecimal, x1: BigDecimal): BigDecimal = if (x0 == x1) x1 else iter(x1, (bd / x1 + x1) / bigTwo)   iter(bigZero, BigDecimal(Math.sqrt(bd.toDouble), precision)) }   @tailrec private def loop(a: BigDecimal, g: BigDecimal, sum: BigDecimal, pow: BigDecimal): BigDecimal = { if (a == g) (bigFour * (a * a)) / (bigOne - sum) else { val (_a, _g, _pow) = ((a + g) / bigTwo, bigSqrt(a * g), pow * bigTwo) loop(_a, _g, sum + ((_a * _a - (_g * _g)) * _pow), _pow) } }   println(precision) val pi = loop(bigOne, bigOne / bigSqrt(bigTwo), bigZero, bigTwo) println(s"This are ${pi.toString.length - 1} digits of π:") val lines = pi.toString().sliding(103, 103).mkString("\n") println(lines)   println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]") }
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)
#BaCon
BaCon
  DATA "January", "February", "March", "April", "May", "June", "July" DATA "August", "September", "October", "November", "December"   LOCAL dat$[11] FOR i = 0 TO 11 READ dat$[i] PRINT dat$[i] NEXT  
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.
#Dart
Dart
    class complex {   num real=0; num imag=0;   complex(num r,num i){ this.real=r; this.imag=i; }     complex add(complex b){ return new complex(this.real + b.real, this.imag + b.imag); }   complex mult(complex b){ //FOIL of (a+bi)(c+di) with i*i = -1 return new complex(this.real * b.real - this.imag * b.imag, this.real * b.imag + this.imag * b.real); }   complex inv(){ //1/(a+bi) * (a-bi)/(a-bi) = 1/(a+bi) but it's more workable num denom = real * real + imag * imag; double r =real/denom; double i= -imag/denom; return new complex( r,-i); }   complex neg(){ return new complex(-real, -imag); }   complex conj(){ return new complex(real, -imag); }     String toString(){ return this.real.toString()+' + '+ this.imag.toString()+'*i'; } } void main() { var cl= new complex(1,2); var cl2= new complex(3,-1); print(cl.toString()); print(cl2.toString()); print(cl.inv().toString()); print(cl2.mult(cl).toString());   }  
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
#ERRE
ERRE
PROGRAM RATIONAL_ARITH   ! ! for rosettacode.org !   TYPE RATIONAL=(NUM,DEN)   DIM SUM:RATIONAL,ONE:RATIONAL,KF:RATIONAL   DIM A:RATIONAL,B:RATIONAL PROCEDURE ABS(A.->A.) A.NUM=ABS(A.NUM) END PROCEDURE   PROCEDURE NEG(A.->A.) A.NUM=-A.NUM END PROCEDURE   PROCEDURE ADD(A.,B.->A.) LOCAL T T=A.DEN*B.DEN A.NUM=A.NUM*B.DEN+B.NUM*A.DEN A.DEN=T END PROCEDURE   PROCEDURE SUB(A.,B.->A.) LOCAL T T=A.DEN*B.DEN A.NUM=A.NUM*B.DEN-B.NUM*A.DEN A.DEN=T END PROCEDURE   PROCEDURE MULT(A.,B.->A.) A.NUM*=B.NUM A.DEN*=B.DEN END PROCEDURE   PROCEDURE DIVIDE(A.,B.->A.) A.NUM*=B.DEN A.DEN*=B.NUM END PROCEDURE   PROCEDURE EQ(A.,B.->RES%) RES%=A.NUM*B.DEN=B.NUM*A.DEN END PROCEDURE   PROCEDURE LT(A.,B.->RES%) RES%=A.NUM*B.DEN<B.NUM*A.DEN END PROCEDURE   PROCEDURE GT(A.,B.->RES%) RES%=A.NUM*B.DEN>B.NUM*A.DEN END PROCEDURE   PROCEDURE NE(A.,B.->RES%) RES%=A.NUM*B.DEN<>B.NUM*A.DEN END PROCEDURE   PROCEDURE LE(A.,B.->RES%) RES%=A.NUM*B.DEN<=B.NUM*A.DEN END PROCEDURE   PROCEDURE GE(A.,B.->RES%) RES%=A.NUM*B.DEN>=B.NUM*A.DEN END PROCEDURE   PROCEDURE NORMALIZE(A.->A.) LOCAL A,B,T A=A.NUM B=A.DEN WHILE B<>0 DO T=A A=B B=T-B*INT(T/B) END WHILE A.NUM/=A A.DEN/=A IF A.DEN<0 THEN A.NUM*=-1 A.DEN*=-1 END IF END PROCEDURE   BEGIN ONE.NUM=1 ONE.DEN=1 FOR N=2 TO 2^19-1 DO SUM.NUM=1 SUM.DEN=N FOR K=2 TO SQR(N) DO IF N=K*INT(N/K) THEN KF.NUM=1 KF.DEN=K ADD(SUM.,KF.->SUM.) NORMALIZE(SUM.->SUM.) KF.DEN=INT(N/K) ADD(SUM.,KF.->SUM.) NORMALIZE(SUM.->SUM.) END IF END FOR EQ(SUM.,ONE.->RES%) IF RES% THEN PRINT(N;" is perfect") END IF END FOR END PROGRAM
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
#ERRE
ERRE
  PROGRAM AGM   ! ! for rosettacode.org !   !$DOUBLE   PROCEDURE AGM(A,G->A) LOCAL TA REPEAT TA=A A=(A+G)/2 G=SQR(TA*G) UNTIL A=TA END PROCEDURE   BEGIN AGM(1.0,1/SQR(2)->A) PRINT(A) END PROGRAM  
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
#F.23
F#
let rec agm a g precision = if precision > abs(a - g) then a else agm (0.5 * (a + g)) (sqrt (a * g)) precision   printfn "%g" (agm 1. (sqrt(0.5)) 1e-15)
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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Console Module Module1 Sub Main Dim a = CInt(ReadLine) Dim b = CInt(ReadLine) WriteLine("Sum " & a + b) WriteLine("Difference " & a - b) WriteLine("Product " & a - b) WriteLine("Quotient " & a / b) WriteLine("Integer Quotient " & a \ b) WriteLine("Remainder " & a Mod b) WriteLine("Exponent " & a ^ b) End Sub End Module
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.
#BBC_BASIC
BBC BASIC
Expr$ = "1 + 2 * (3 + (4 * 5 + 6 * 7 * 8) - 9) / 10" PRINT "Input = " Expr$ AST$ = FNast(Expr$) PRINT "AST = " AST$ PRINT "Value = " ;EVAL(AST$) END   DEF FNast(RETURN in$) LOCAL ast$, oper$ REPEAT ast$ += FNast1(in$) WHILE ASC(in$)=32 in$ = MID$(in$,2) : ENDWHILE oper$ = LEFT$(in$,1) IF oper$="+" OR oper$="-" THEN ast$ += oper$ in$ = MID$(in$,2) ELSE EXIT REPEAT ENDIF UNTIL FALSE = "(" + ast$ + ")"   DEF FNast1(RETURN in$) LOCAL ast$, oper$ REPEAT ast$ += FNast2(in$) WHILE ASC(in$)=32 in$ = MID$(in$,2) : ENDWHILE oper$ = LEFT$(in$,1) IF oper$="*" OR oper$="/" THEN ast$ += oper$ in$ = MID$(in$,2) ELSE EXIT REPEAT ENDIF UNTIL FALSE = "(" + ast$ + ")"   DEF FNast2(RETURN in$) LOCAL ast$ WHILE ASC(in$)=32 in$ = MID$(in$,2) : ENDWHILE IF ASC(in$)<>40 THEN = FNnumber(in$) in$ = MID$(in$,2) ast$ = FNast(in$) in$ = MID$(in$,2) = ast$   DEF FNnumber(RETURN in$) LOCAL ch$, num$ REPEAT ch$ = LEFT$(in$,1) IF INSTR("0123456789.", ch$) THEN num$ += ch$ in$ = MID$(in$,2) ELSE EXIT REPEAT ENDIF UNTIL FALSE = num$
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.
#C
C
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream>   using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p;   using boost::spirit::tree_node; using boost::spirit::node_val_data;   // The grammar struct parser: public boost::spirit::grammar<parser> { enum rule_ids { addsub_id, multdiv_id, value_id, real_id };   struct set_value { set_value(parser const& p): self(p) {} void operator()(tree_node<node_val_data<std::string::iterator, double> >& node, std::string::iterator begin, std::string::iterator end) const { node.value.value(self.tmp); } parser const& self; };   mutable double tmp;   template<typename Scanner> struct definition { rule<Scanner, parser_tag<addsub_id> > addsub; rule<Scanner, parser_tag<multdiv_id> > multdiv; rule<Scanner, parser_tag<value_id> > value; rule<Scanner, parser_tag<real_id> > real;   definition(parser const& self) { using namespace boost::spirit; addsub = multdiv >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv); multdiv = value >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value); value = real | inner_node_d[('(' >> addsub >> ')')]; real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]]; }   rule<Scanner, parser_tag<addsub_id> > const& start() const { return addsub; } }; };   template<typename TreeIter> double evaluate(TreeIter const& i) { double op1, op2; switch (i->value.id().to_long()) { case parser::real_id: return i->value.value(); case parser::value_id: case parser::addsub_id: case parser::multdiv_id: op1 = evaluate(i->children.begin()); op2 = evaluate(i->children.begin()+1); switch(*i->value.begin()) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: assert(!"Should not happen"); } default: assert(!"Should not happen"); } return 0; }   // the read/eval/write loop int main() { parser eval; std::string line; while (std::cout << "Expression: " && std::getline(std::cin, line) && !line.empty()) { typedef boost::spirit::node_val_data_factory<double> factory_t; boost::spirit::tree_parse_info<std::string::iterator, factory_t> info = boost::spirit::ast_parse<factory_t>(line.begin(), line.end(), eval, boost::spirit::space_p); if (info.full) { std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl; } else { std::cout << "Error in expression." << std::endl; } } };
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.
#ABAP
ABAP
form open_doors_unopt. data: lv_door type i, lv_count type i value 1. data: lt_doors type standard table of c initial size 100. field-symbols: <wa_door> type c. do 100 times. append initial line to lt_doors assigning <wa_door>. <wa_door> = 'X'. enddo.   while lv_count < 100. lv_count = lv_count + 1. lv_door = lv_count. while lv_door < 100. read table lt_doors index lv_door assigning <wa_door>. if <wa_door> = ' '. <wa_door> = 'X'. else. <wa_door> = ' '. endif. add lv_count to lv_door. endwhile. endwhile.   loop at lt_doors assigning <wa_door>. if <wa_door> = 'X'. write : / 'Door', (4) sy-tabix right-justified, 'is open' no-gap. endif. endloop. endform.
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π = 4 a g m ( 1 , 1 / 2 ) 2 1 − ∑ n = 1 ∞ 2 n + 1 ( a n 2 − g n 2 ) {\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}} This allows you to make the approximation, for any large   N: π ≈ 4 a N 2 1 − ∑ k = 1 N 2 k + 1 ( a k 2 − g k 2 ) {\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of π {\displaystyle \pi } .
#Sidef
Sidef
func agm_pi(digits) { var acc = (digits + 8);   local Num!PREC = 4*digits;   var an = 1; var bn = sqrt(0.5); var tn = 0.5**2; var pn = 1;   while (pn < acc) { var prev_an = an; an = (bn+an / 2); bn = sqrt(bn * prev_an); prev_an -= an; tn -= (pn * prev_an**2); pn *= 2; }   ((an+bn)**2 / 4*tn).to_s }   say agm_pi(100);
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π = 4 a g m ( 1 , 1 / 2 ) 2 1 − ∑ n = 1 ∞ 2 n + 1 ( a n 2 − g n 2 ) {\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}} This allows you to make the approximation, for any large   N: π ≈ 4 a N 2 1 − ∑ k = 1 N 2 k + 1 ( a k 2 − g k 2 ) {\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of π {\displaystyle \pi } .
#Tcl
Tcl
package require math::bigfloat namespace import math::bigfloat::*   proc agm/π {N {precision 8192}} { set 1 [int2float 1 $precision] set 2 [int2float 2 $precision] set n 1 set a $1 set g [div $1 [sqrt $2]] set z [div $1 [int2float 4 $precision]] for {set i 0} {$i <= $N} {incr i} { set x0 [div [add $a $g] $2] set x1 [sqrt [mul $a $g]] set var [sub $x0 $a] set z [sub $z [mul [mul $var $n] $var]] incr n $n set a $x0 set g $x1 } return [tostr [div [mul $a $a] $z]] }   puts [agm/π 17]
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)
#BASIC
BASIC
OPTION BASE 1 DIM myArray(100) AS INTEGER
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.
#Delphi
Delphi
  program Arithmetic_Complex;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.VarCmplx;   var a, b: Variant;   begin a := VarComplexCreate(5, 3); b := VarComplexCreate(0.5, 6.0);   writeln(format('(%s) + (%s) = %s',[a,b, a+b]));   writeln(format('(%s) * (%s) = %s',[a,b, a*b]));   writeln(format('-(%s) = %s',[a,- a]));   writeln(format('1/(%s) = %s',[a,1/a]));   writeln(format('conj(%s) = %s',[a,VarComplexConjugate(a)]));   Readln; 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
#F.23
F#
type frac = Microsoft.FSharp.Math.BigRational   let perf n = 1N = List.fold (+) 0N (List.map (fun i -> if n % i = 0 then 1N/frac.FromInt(i) else 0N) [2..n])   for i in 1..(1<<<19) do if (perf i) then printfn "%i is perfect" i
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
#Factor
Factor
USING: kernel math math.functions prettyprint ; IN: rosetta-code.arithmetic-geometric-mean   : agm ( a g -- a' g' ) 2dup [ + 0.5 * ] 2dip * sqrt ;   1 1 2 sqrt / [ 2dup - 1e-15 > ] [ agm ] while drop .
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
#Forth
Forth
: agm ( a g -- m ) begin fover fover f+ 2e f/ frot frot f* fsqrt fover fover 1e-15 f~ until fdrop ;   1e 2e -0.5e f** agm f. \ 0.847213084793979
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.
#Vlang
Vlang
// Arithmetic-integer in V // Tectonics: v run arithmetic-integer.v module main import math import os   // starts here pub fn main() { mut a := 0 mut b := 0   // get numbers from console print("Enter two integer numbers, separated by a space: ") text := os.get_raw_line() values := text.split(' ') a = values[0].int() b = values[1].int()   // 4 basics, remainder, no exponentiation operator println("values: a $a, b $b") println("sum: a + b = ${a + b}") println("difference: a - b = ${a - b}") println("product: a * b = ${a * b}") println("integer quotient: a / b = ${a / b}, truncation") println("remainder: a % b = ${a % b}, sign follows dividend")   println("no exponentiation operator") println(" math.pow: pow(a,b) = ${math.pow(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.
#C.2B.2B
C++
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream>   using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p;   using boost::spirit::tree_node; using boost::spirit::node_val_data;   // The grammar struct parser: public boost::spirit::grammar<parser> { enum rule_ids { addsub_id, multdiv_id, value_id, real_id };   struct set_value { set_value(parser const& p): self(p) {} void operator()(tree_node<node_val_data<std::string::iterator, double> >& node, std::string::iterator begin, std::string::iterator end) const { node.value.value(self.tmp); } parser const& self; };   mutable double tmp;   template<typename Scanner> struct definition { rule<Scanner, parser_tag<addsub_id> > addsub; rule<Scanner, parser_tag<multdiv_id> > multdiv; rule<Scanner, parser_tag<value_id> > value; rule<Scanner, parser_tag<real_id> > real;   definition(parser const& self) { using namespace boost::spirit; addsub = multdiv >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv); multdiv = value >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value); value = real | inner_node_d[('(' >> addsub >> ')')]; real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]]; }   rule<Scanner, parser_tag<addsub_id> > const& start() const { return addsub; } }; };   template<typename TreeIter> double evaluate(TreeIter const& i) { double op1, op2; switch (i->value.id().to_long()) { case parser::real_id: return i->value.value(); case parser::value_id: case parser::addsub_id: case parser::multdiv_id: op1 = evaluate(i->children.begin()); op2 = evaluate(i->children.begin()+1); switch(*i->value.begin()) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: assert(!"Should not happen"); } default: assert(!"Should not happen"); } return 0; }   // the read/eval/write loop int main() { parser eval; std::string line; while (std::cout << "Expression: " && std::getline(std::cin, line) && !line.empty()) { typedef boost::spirit::node_val_data_factory<double> factory_t; boost::spirit::tree_parse_info<std::string::iterator, factory_t> info = boost::spirit::ast_parse<factory_t>(line.begin(), line.end(), eval, boost::spirit::space_p); if (info.full) { std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl; } else { std::cout << "Error in expression." << std::endl; } } };
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.
#ACL2
ACL2
(defun rep (n x) (if (zp n) nil (cons x (rep (- n 1) x))))   (defun toggle-every-r (n i bs) (if (endp bs) nil (cons (if (zp i) (not (first bs)) (first bs)) (toggle-every-r n (mod (1- i) n) (rest bs)))))   (defun toggle-every (n bs) (toggle-every-r n (1- n) bs))   (defun 100-doors (i doors) (if (zp i) doors (100-doors (1- i) (toggle-every i doors))))
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π = 4 a g m ( 1 , 1 / 2 ) 2 1 − ∑ n = 1 ∞ 2 n + 1 ( a n 2 − g n 2 ) {\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}} This allows you to make the approximation, for any large   N: π ≈ 4 a N 2 1 − ∑ k = 1 N 2 k + 1 ( a k 2 − g k 2 ) {\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of π {\displaystyle \pi } .
#Visual_Basic_.NET
Visual Basic .NET
Imports System, System.Numerics   Module Program Function IntSqRoot(ByVal valu As BigInteger, ByVal guess As BigInteger) As BigInteger Dim term As BigInteger : Do term = valu / guess If BigInteger.Abs(term - guess) <= 1 Then Exit Do guess += term : guess >>= 1 Loop While True : Return guess End Function   Function ISR(ByVal term As BigInteger, ByVal guess As BigInteger) As BigInteger Dim valu As BigInteger = term * guess : Do If BigInteger.Abs(term - guess) <= 1 Then Exit Do guess += term : guess >>= 1 : term = valu / guess Loop While True : Return guess End Function   Function CalcAGM(ByVal lam As BigInteger, ByVal gm As BigInteger, ByRef z As BigInteger, ByVal ep As BigInteger) As BigInteger Dim am, zi As BigInteger : Dim n As ULong = 1 : Do am = (lam + gm) >> 1 : gm = ISR(lam, gm) Dim v As BigInteger = am - lam zi = v * v * n : If zi < ep Then Exit Do z -= zi : n <<= 1 : lam = am Loop While True : Return am End Function   Function BIP(ByVal exp As Integer, ByVal Optional man As ULong = 1) As BigInteger Dim rv As BigInteger = BigInteger.Pow(10, exp) : Return If(man = 1, rv, man * rv) End Function   Sub Main(args As String()) Dim d As Integer = 25000 If args.Length > 0 Then Integer.TryParse(args(0), d) If d < 1 OrElse d > 999999 Then d = 25000 End If Dim st As DateTime = DateTime.Now Dim am As BigInteger = BIP(d), gm As BigInteger = IntSqRoot(BIP(d + d - 1, 5), BIP(d - 15, Math.Sqrt(0.5) * 1.0E+15)), z As BigInteger = BIP(d + d - 2, 25), agm As BigInteger = CalcAGM(am, gm, z, BIP(d + 1)), pi As BigInteger = agm * agm * BIP(d - 2) / z Console.WriteLine("Computation time: {0:0.0000} seconds ", (DateTime.Now - st).TotalMilliseconds / 1000) If args.Length > 1 OrElse d <= 1000 Then Dim s As String = pi.ToString() Console.WriteLine("{0}.{1}", s(0), s.Substring(1)) End If If Diagnostics.Debugger.IsAttached Then Console.ReadKey() End Sub End Module  
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)
#BASIC256
BASIC256
# numeric array dim numbers(10) for t = 0 to 9 numbers[t] = t + 1 next t   # string array dim words$(10) # assigning an array with a list words$ = {"one","two","three","four","five","six","seven","eight","nine","ten"}   gosub display   # resize arrays (always preserves values if larger) redim numbers(11) redim words$(11) numbers[10] = 11 words$[10] = "eleven" gosub display   end   display: # display arrays # using ? to get size of array for t = 0 to numbers[?]-1 print numbers[t] + "=" + words$[t] next t return
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.
#EchoLisp
EchoLisp
  (define a 42+666i) → a (define b 1+i) → b (- a) → -42-666i ; negate (+ a b) → 43+667i ; add (* a b) → -624+708i ; multiply (/ b) → 0.5-0.5i ; invert (conjugate b) → 1-i (angle b) → 0.7853981633974483 ; = PI/4 (magnitude b) → 1.4142135623730951 ; = sqrt(2) (exp (* I PI)) → -1+0i ; Euler = e^(I*PI) = -1  
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
#Factor
Factor
USING: generalizations io kernel math math.functions math.primes.factors math.ranges prettyprint sequences ; IN: rosetta-code.arithmetic-rational   2/5  ! literal syntax 2/5 2/4  ! automatically simplifies to 1/2 5/1  ! automatically coerced to 5 26/5  ! mixed fraction 5+1/5 13/178 >fraction ! get the numerator and denominator 13 178 8 recip  ! get the reciprocal 1/8   ! ratios can be any size 12417829731289312/61237812937138912735712 8 ndrop ! clear the stack ! arithmetic works the same as any other number.   : perfect? ( n -- ? ) divisors rest [ recip ] map-sum 1 = ;   "Perfect numbers <= 2^19: " print 2 19 ^ [1,b] [ perfect? ] filter .
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
#Fortran
Fortran
function agm(a,b) implicit none double precision agm,a,b,eps,c parameter(eps=1.0d-15) 10 c=0.5d0*(a+b) b=sqrt(a*b) a=c if(a-b.gt.eps*a) go to 10 agm=0.5d0*(a+b) end program test implicit none double precision agm print*,agm(1.0d0,1.0d0/sqrt(2.0d0)) 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
#FreeBASIC
FreeBASIC
' version 16-09-2015 ' compile with: fbc -s console   Function agm(a As Double, g As Double) As Double   Dim As Double t_a   Do t_a = (a + g) / 2 g = Sqr(a * g) Swap a, t_a Loop Until a = t_a   Return a   End Function   ' ------=< MAIN >=------   Print agm(1, 1 / Sqr(2) )   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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.
#Wart
Wart
a <- (read) b <- (read) prn "sum: " a+b prn "difference: " a-b prn "product: " a*b prn "quotient: " a/b prn "integer quotient: " (int a/b) prn "remainder: " a%b prn "exponent: " a^b
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.
#Wren
Wren
import "io" for Stdin, Stdout System.write("first number: ") Stdout.flush() var a = Num.fromString(Stdin.readLine()) System.write("second number: ") Stdout.flush() var b = Num.fromString(Stdin.readLine()) System.print("sum:  %(a + b)") System.print("difference:  %(a - b)") System.print("product:  %(a * b)") System.print("integer quotient: %((a / b).floor)") System.print("remainder:  %(a % b)") System.print("exponentiation:  %(a.pow(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.
#Clojure
Clojure
(def precedence '{* 0, / 0 + 1, - 1})   (defn order-ops "((A x B) y C) or (A x (B y C)) depending on precedence of x and y" [[A x B y C & more]] (let [ret (if (<= (precedence x) (precedence y)) (list (list A x B) y C) (list A x (list B y C)))] (if more (recur (concat ret more)) ret)))   (defn add-parens "Tree walk to add parens. All lists are length 3 afterwards." [s] (clojure.walk/postwalk #(if (seq? %) (let [c (count %)] (cond (even? c) (throw (Exception. "Must be an odd number of forms")) (= c 1) (first %) (= c 3) % (>= c 5) (order-ops %))) %) s))   (defn make-ast "Parse a string into a list of numbers, ops, and lists" [s] (-> (format "'(%s)" s) (.replaceAll , "([*+-/])" " $1 ") load-string add-parens))   (def ops {'* * '+ + '- - '/ /})   (def eval-ast (partial clojure.walk/postwalk #(if (seq? %) (let [[a o b] %] ((ops o) a b)) %)))   (defn evaluate [s] "Parse and evaluate an infix arithmetic expression" (eval-ast (make-ast s)))   user> (evaluate "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1") 60
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.
#Action.21
Action!
DEFINE COUNT="100"   PROC Main() BYTE ARRAY doors(COUNT+1) BYTE door,pass   FOR door=1 TO COUNT DO doors(door)=0 OD   PrintE("Following doors are open:") FOR pass=1 TO COUNT DO FOR door=pass TO COUNT STEP pass DO doors(door)==!$FF OD IF doors(pass)=$FF THEN PrintB(pass) Put(32) FI OD RETURN
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π = 4 a g m ( 1 , 1 / 2 ) 2 1 − ∑ n = 1 ∞ 2 n + 1 ( a n 2 − g n 2 ) {\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}} This allows you to make the approximation, for any large   N: π ≈ 4 a N 2 1 − ∑ k = 1 N 2 k + 1 ( a k 2 − g k 2 ) {\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of π {\displaystyle \pi } .
#Wren
Wren
import "/big" for BigRat   var digits = 500 var an = BigRat.one var bn = BigRat.half.sqrt(digits) var tn = BigRat.half.square var pn = BigRat.one while (pn <= digits) { var prevAn = an an = (bn + an) * BigRat.half bn = (bn * prevAn).sqrt(digits) prevAn = prevAn - an tn = tn - (prevAn.square * pn) pn = pn + pn } var pi = (an + bn).square / (tn * 4) System.print(pi.toDecimal(digits, false))
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)
#Batch_File
Batch File
::arrays.cmd @echo off setlocal ENABLEDELAYEDEXPANSION set array.1=1 set array.2=2 set array.3=3 set array.4=4 for /L %%i in (1,1,4) do call :showit array.%%i !array.%%i! set c=-27 call :mkarray marry 5 6 7 8 for /L %%i in (-27,1,-24) do call :showit "marry^&%%i" !marry^&%%i! endlocal goto :eof   :mkarray set %1^&%c%=%2 set /a c += 1 shift /2 if "%2" neq "" goto :mkarray goto :eof   :showit echo %1 = %2 goto :eof  
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.
#Elixir
Elixir
defmodule Complex do import Kernel, except: [abs: 1, div: 2]   defstruct real: 0, imag: 0   def new(real, imag) do  %__MODULE__{real: real, imag: imag} end   def add(a, b) do {a, b} = convert(a, b) new(a.real + b.real, a.imag + b.imag) end   def sub(a, b) do {a, b} = convert(a, b) new(a.real - b.real, a.imag - b.imag) end   def mul(a, b) do {a, b} = convert(a, b) new(a.real*b.real - a.imag*b.imag, a.imag*b.real + a.real*b.imag) end   def div(a, b) do {a, b} = convert(a, b) divisor = abs2(b) new((a.real*b.real + a.imag*b.imag) / divisor, (a.imag*b.real - a.real*b.imag) / divisor) end   def neg(a) do a = convert(a) new(-a.real, -a.imag) end   def inv(a) do a = convert(a) divisor = abs2(a) new(a.real / divisor, -a.imag / divisor) end   def conj(a) do a = convert(a) new(a.real, -a.imag) end   def abs(a) do  :math.sqrt(abs2(a)) end   defp abs2(a) do a = convert(a) a.real*a.real + a.imag*a.imag end   defp convert(a) when is_number(a), do: new(a, 0) defp convert(%__MODULE__{} = a), do: a   defp convert(a, b), do: {convert(a), convert(b)}   def task do a = new(1, 3) b = new(5, 2) IO.puts "a = #{a}" IO.puts "b = #{b}" IO.puts "add(a,b): #{add(a, b)}" IO.puts "sub(a,b): #{sub(a, b)}" IO.puts "mul(a,b): #{mul(a, b)}" IO.puts "div(a,b): #{div(a, b)}" IO.puts "div(b,a): #{div(b, a)}" IO.puts "neg(a)  : #{neg(a)}" IO.puts "inv(a)  : #{inv(a)}" IO.puts "conj(a) : #{conj(a)}" end end   defimpl String.Chars, for: Complex do def to_string(%Complex{real: real, imag: imag}) do if imag >= 0, do: "#{real}+#{imag}j", else: "#{real}#{imag}j" end end   Complex.task
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.
#Erlang
Erlang
%% Task: Complex Arithmetic %% Author: Abhay Jain   -module(complex_number). -export([calculate/0]).   -record(complex, {real, img}).   calculate() -> A = #complex{real=1, img=3}, B = #complex{real=5, img=2},   Sum = add (A, B), print (Sum),   Product = multiply (A, B), print (Product),   Negation = negation (A), print (Negation),   Inversion = inverse (A), print (Inversion),   Conjugate = conjugate (A), print (Conjugate).   add (A, B) -> RealPart = A#complex.real + B#complex.real, ImgPart = A#complex.img + B#complex.img, #complex{real=RealPart, img=ImgPart}.   multiply (A, B) -> RealPart = (A#complex.real * B#complex.real) - (A#complex.img * B#complex.img), ImgPart = (A#complex.real * B#complex.img) + (B#complex.real * A#complex.img), #complex{real=RealPart, img=ImgPart}.   negation (A) -> #complex{real=-A#complex.real, img=-A#complex.img}.   inverse (A) -> C = conjugate (A), Mod = (A#complex.real * A#complex.real) + (A#complex.img * A#complex.img), RealPart = C#complex.real / Mod, ImgPart = C#complex.img / Mod, #complex{real=RealPart, img=ImgPart}.   conjugate (A) -> RealPart = A#complex.real, ImgPart = -A#complex.img, #complex{real=RealPart, img=ImgPart}.   print (A) -> if A#complex.img < 0 -> io:format("Ans = ~p~pi~n", [A#complex.real, A#complex.img]); true -> io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img]) 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
#Fermat
Fermat
  for n=2 to 2^19 by 2 do s:=3/n; m:=1; while m<=n/3 do if Divides(m,n) then s:=s+1/m; fi; m:=m+1; od; if s=2 then !!n fi; od;
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
#Futhark
Futhark
  import "futlib/math"   fun agm(a: f64, g: f64): f64 = let eps = 1.0E-16 loop ((a,g)) = while f64.abs(a-g) > eps do ((a+g) / 2.0, f64.sqrt (a*g)) in a   fun main(x: f64, y: f64): f64 = agm(x,y)  
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
#Go
Go
package main   import ( "fmt" "math" )   const ε = 1e-14   func agm(a, g float64) float64 { for math.Abs(a-g) > math.Abs(a)*ε { a, g = (a+g)*.5, math.Sqrt(a*g) } return a }   func main() { fmt.Println(agm(1, 1/math.Sqrt2)) }
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.
#x86_Assembly
x86 Assembly
arithm: mov cx, a mov bx, b xor dx, dx   mov ax, cx add ax, bx mov sum, ax   mov ax, cx imul bx mov product, ax   mov ax, cx sub ax, bx mov difference, ax   mov ax, cx idiv bx mov quotient, ax mov remainder, dx   ret
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.
#Common_Lisp
Common Lisp
(defun tokenize-stream (stream) (labels ((whitespace-p (char) (find char #(#\space #\newline #\return #\tab))) (consume-whitespace () (loop while (whitespace-p (peek-char nil stream nil #\a)) do (read-char stream))) (read-integer () (loop while (digit-char-p (peek-char nil stream nil #\space)) collect (read-char stream) into digits finally (return (parse-integer (coerce digits 'string)))))) (consume-whitespace) (let* ((c (peek-char nil stream nil nil))) (token (case c (nil nil) (#\( :lparen) (#\) :rparen) (#\* '*) (#\/ '/) (#\+ '+) (#\- '-) (otherwise (unless (digit-char-p c) (cerror "Skip it." "Unexpected character ~w." c) (read-char stream) (return-from tokenize-stream (tokenize-stream stream))) (read-integer))))) (unless (or (null token) (integerp token)) (read-char stream)) token)))   (defun group-parentheses (tokens &optional (delimited nil)) (do ((new-tokens '())) ((endp tokens) (when delimited (cerror "Insert it." "Expected right parenthesis.")) (values (nreverse new-tokens) '())) (let ((token (pop tokens))) (case token (:lparen (multiple-value-bind (group remaining-tokens) (group-parentheses tokens t) (setf new-tokens (cons group new-tokens) tokens remaining-tokens))) (:rparen (if (not delimited) (cerror "Ignore it." "Unexpected right parenthesis.") (return (values (nreverse new-tokens) tokens)))) (otherwise (push token new-tokens))))))   (defun group-operations (expression) (flet ((gop (exp) (group-operations exp))) (if (integerp expression) expression (destructuring-bind (a &optional op1 b op2 c &rest others) expression (unless (member op1 '(+ - * / nil)) (error "syntax error: in expr ~a expecting operator, not ~a" expression op1)) (unless (member op2 '(+ - * / nil)) (error "syntax error: in expr ~a expecting operator, not ~a" expression op2)) (cond ((not op1) (gop a)) ((not op2) `(,(gop a) ,op1 ,(gop b))) (t (let ((a (gop a)) (b (gop b)) (c (gop c))) (if (and (member op1 '(+ -)) (member op2 '(* /))) (gop `(,a ,op1 (,b ,op2 ,c) ,@others)) (gop `((,a ,op1 ,b) ,op2 ,c ,@others))))))))))   (defun infix-to-prefix (expression) (if (integerp expression) expression (destructuring-bind (a op b) expression `(,op ,(infix-to-prefix a) ,(infix-to-prefix b)))))   (defun evaluate (string) (with-input-from-string (in string) (eval (infix-to-prefix (group-operations (group-parentheses (loop for token = (tokenize-stream in) until (null token) collect token)))))))
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.
#Action.21
Action!
INT ARRAY SinTab=[ 0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83 88 92 96 100 104 108 112 116 120 124 128 132 136 139 143 147 150 154 158 161 165 168 171 175 178 181 184 187 190 193 196 199 202 204 207 210 212 215 217 219 222 224 226 228 230 232 234 236 237 239 241 242 243 245 246 247 248 249 250 251 252 253 254 254 255 255 255 256 256 256 256]   INT FUNC Sin(INT a) WHILE a<0 DO a==+360 OD WHILE a>360 DO a==-360 OD IF a<=90 THEN RETURN (SinTab(a)) ELSEIF a<=180 THEN RETURN (SinTab(180-a)) ELSEIF a<=270 THEN RETURN (-SinTab(a-180)) ELSE RETURN (-SinTab(360-a)) FI RETURN (0)   INT FUNC Cos(INT a) RETURN (Sin(a-90))   PROC DrawSpiral(INT x0,y0) INT angle,radius,x,y   Plot(x0,y0) FOR angle=0 TO 1800 STEP 5 DO radius=angle/20 x=radius*Cos(angle)/256+x0 y=radius*Sin(angle)/256+y0 DrawTo(x,y) OD RETURN   PROC Main() BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   DrawSpiral(160,96)   DO UNTIL CH#$FF OD CH=$FF RETURN
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.
#ActionScript
ActionScript
package { import flash.display.Sprite;   public class Doors extends Sprite { public function Doors() {   // Initialize the array var doors:Array = new Array(100); for (var i:Number = 0; i < 100; i++) { doors[i] = false;   // Do the work for (var pass:Number = 0; pass < 100; pass++) { for (var j:Number = pass; j < 100; j += (pass+1)) { doors[j] = !doors[j]; } } trace(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)
#BBC_BASIC
BBC BASIC
REM Declare arrays, dimension is maximum index: DIM array(6), array%(6), array$(6)   REM Entire arrays may be assigned in one statement: array() = 0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7 array%() = 0, 1, 2, 3, 4, 5, 6 array$() = "Zero", "One", "Two", "Three", "Four", "Five", "Six"   REM Or individual elements may be assigned: array(2) = PI array%(3) = RND array$(4) = "Hello world!"   REM Print out sample array elements: PRINT array(2) TAB(16) array(3) TAB(32) array(4) PRINT array%(2) TAB(16) array%(3) TAB(32) array%(4) PRINT array$(2) TAB(16) array$(3) TAB(32) array$(4)
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.
#ERRE
ERRE
  PROGRAM COMPLEX_ARITH   TYPE COMPLEX=(REAL#,IMAG#)   DIM X:COMPLEX,Y:COMPLEX,Z:COMPLEX   ! ! complex arithmetic routines ! DIM A:COMPLEX,B:COMPLEX,C:COMPLEX   PROCEDURE ADD(A.,B.->C.) C.REAL#=A.REAL#+B.REAL# C.IMAG#=A.IMAG#+B.IMAG# END PROCEDURE   PROCEDURE INV(A.->B.) LOCAL DENOM# DENOM#=A.REAL#^2+A.IMAG#^2 B.REAL#=A.REAL#/DENOM# B.IMAG#=-A.IMAG#/DENOM# END PROCEDURE   PROCEDURE MULT(A.,B.->C.) C.REAL#=A.REAL#*B.REAL#-A.IMAG#*B.IMAG# C.IMAG#=A.REAL#*B.IMAG#+A.IMAG#*B.REAL# END PROCEDURE   PROCEDURE NEG(A.->B.) B.REAL#=-A.REAL# B.IMAG#=-A.IMAG# END PROCEDURE   BEGIN PRINT(CHR$(12);) !CLS X.REAL#=1 X.IMAG#=1 Y.REAL#=2 Y.IMAG#=2 ADD(X.,Y.->Z.) PRINT(Z.REAL#;" + ";Z.IMAG#;"i") MULT(X.,Y.->Z.) PRINT(Z.REAL#;" + ";Z.IMAG#;"i") INV(X.->Z.) PRINT(Z.REAL#;" + ";Z.IMAG#;"i") NEG(X.->Z.) PRINT(Z.REAL#;" + ";Z.IMAG#;"i") END PROGRAM  
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.
#Euler_Math_Toolbox
Euler Math Toolbox
  >a=1+4i; b=5-3i; >a+b 6+1i >a-b -4+7i >a*b 17+17i >a/b -0.205882352941+0.676470588235i >fraction a/b -7/34+23/34i >conj(a) 1-4i  
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
#Forth
Forth
\ Rationals can use any double cell operations: 2!, 2@, 2dup, 2swap, etc. \ Uses the stack convention of the built-in "*/" for int * frac -> int   : numerator drop ; : denominator nip ;   : s>rat 1 ; \ integer to rational (n/1) : rat>s / ; \ integer : rat>frac mod ; \ fractional part : rat>float swap s>f s>f f/ ;   : rat. swap 1 .r [char] / emit . ;   \ normalize: factors out gcd and puts sign into numerator : gcd ( a b -- gcd ) begin ?dup while tuck mod repeat ; : rat-normalize ( rat -- rat ) 2dup gcd tuck / >r / r> ;   : rat-abs swap abs swap ; : rat-negate swap negate swap ; : 1/rat over 0< if negate swap negate else swap then ;   : rat+ ( a b c d -- ad+bc bd ) rot 2dup * >r rot * >r * r> + r> rat-normalize ; : rat- rat-negate rat+ ;   : rat* ( a b c d -- ac bd ) rot * >r * r> rat-normalize ; : rat/ swap rat* ;   : rat-equal d= ; : rat-less ( a b c d -- ad<bc ) -rot * >r * r> < ; : rat-more 2swap rat-less ;   : rat-inc tuck + swap ; : rat-dec tuck - swap ;
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
#Groovy
Groovy
double agm (double a, double g) { double an = a, gn = g while ((an-gn).abs() >= 10.0**-14) { (an, gn) = [(an+gn)*0.5, (an*gn)**0.5] } an }
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
#Haskell
Haskell
-- Return an approximation to the arithmetic-geometric mean of two numbers. -- The result is considered accurate when two successive approximations are -- sufficiently close, as determined by "eq". agm :: (Floating a) => a -> a -> ((a, a) -> Bool) -> a agm a g eq = snd $ until eq step (a, g) where step (a, g) = ((a + g) / 2, sqrt (a * g))   -- Return the relative difference of the pair. We assume that at least one of -- the values is far enough from 0 to not cause problems. relDiff :: (Fractional a) => (a, a) -> a relDiff (x, y) = let n = abs (x - y) d = (abs x + abs y) / 2 in n / d   main :: IO () main = do let equal = (< 0.000000001) . relDiff print $ agm 1 (1 / sqrt 2) equal
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.
#XLISP
XLISP
(DEFUN INTEGER-ARITHMETIC () (DISPLAY "Enter two integers separated by a space.") (NEWLINE) (DISPLAY "> ") (DEFINE A (READ)) (DEFINE B (READ)) (DISPLAY `(SUM ,(+ A B))) (NEWLINE) (DISPLAY `(DIFFERENCE ,(- A B))) (NEWLINE) (DISPLAY `(PRODUCT ,(* A B))) (NEWLINE) (DISPLAY `(QUOTIENT ,(QUOTIENT A B))) ; truncates towards zero (NEWLINE) (DISPLAY `(REMAINDER ,(REM A B))) ; takes sign of first operand (NEWLINE) (DISPLAY `(EXPONENTIATION ,(EXPT A B))))
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.
#XPL0
XPL0
include c:\cxpl\codes; int A, B; [A:= IntIn(0); B:= IntIn(0); IntOut(0, A+B); CrLf(0); IntOut(0, A-B); CrLf(0); IntOut(0, A*B); CrLf(0); IntOut(0, A/B); CrLf(0); \truncates toward zero IntOut(0, rem(0)); CrLf(0); \remainder's sign matches first operand (A) ]
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.
#D
D
import std.stdio, std.string, std.ascii, std.conv, std.array, std.exception, std.traits;   struct Stack(T) { T[] data; alias data this; void push(T top) pure nothrow @safe { data ~= top; }   T pop(bool discard = true)() pure @nogc @safe { immutable static exc = new immutable(Exception)("Stack Empty"); if (data.empty) throw exc; auto top = data[$ - 1]; static if (discard) data.popBack; return top; } }   enum Type { Num, OBkt, CBkt, Add, Sub, Mul, Div } immutable opChar = ["#", "(", ")", "+", "-", "*", "/"]; immutable opPrec = [ 0, -9, -9, 1, 1, 2, 2];   abstract class Visitor { void visit(XP e) pure @safe; }   final class XP { immutable Type type; immutable string str; immutable int pos; // Optional, to display AST struct. XP LHS, RHS;   this(string s=")", int p = -1) pure nothrow @safe { str = s; pos = p; auto localType = Type.Num; foreach_reverse (immutable t; [EnumMembers!Type[1 .. $]]) if (opChar[t] == s) localType = t; this.type = localType; }   override int opCmp(Object other) pure @safe { auto rhs = cast(XP)other; enforce(rhs !is null); return opPrec[type] - opPrec[rhs.type]; }   void accept(Visitor v) pure @safe { v.visit(this); } }   final class AST { XP root; Stack!XP opr, num; string xpr, token; int xpHead, xpTail;   void joinXP(XP x) pure @safe { x.RHS = num.pop; x.LHS = num.pop; num.push(x); }   string nextToken() pure @safe { while (xpHead < xpr.length && xpr[xpHead] == ' ') xpHead++; // Skip spc. xpTail = xpHead; if (xpHead < xpr.length) { token = xpr[xpTail .. xpTail + 1]; switch (token) { case "(", ")", "+", "-", "*", "/": // Valid non-number. xpTail++; return token; default: // Should be number. if (token[0].isDigit) { while (xpTail < xpr.length && xpr[xpTail].isDigit()) xpTail++; return xpr[xpHead .. xpTail]; } // Else may be error. } // End switch. } if (xpTail < xpr.length) throw new Exception("Invalid Char <" ~ xpr[xpTail] ~ ">"); return null; } // End nextToken.   AST parse(in string s) /*@safe*/ { bool expectingOP; xpr = s; try { xpHead = xpTail = 0; num = opr = null; root = null; opr.push(new XP); // CBkt, prevent evaluate null OP precedence. while ((token = nextToken) !is null) { XP tokenXP = new XP(token, xpHead); if (expectingOP) { // Process OP-alike XP. switch (token) { case ")": while (opr.pop!false.type != Type.OBkt) joinXP(opr.pop); opr.pop; expectingOP = true; break; case "+", "-", "*", "/": while (tokenXP <= opr.pop!false) joinXP(opr.pop()); opr.push(tokenXP); expectingOP = false; break; default: throw new Exception("Expecting Operator or ), not <" ~ token ~ ">"); } } else { // Process Num-alike XP. switch (token) { case "+", "-", "*", "/", ")": throw new Exception("Expecting Number or (, not <" ~ token ~ ">"); case "(": opr.push(tokenXP); expectingOP = false; break; default: // Number. num.push(tokenXP); expectingOP = true; } } xpHead = xpTail; } // End while.   while (opr.length > 1) // Join pending Op. joinXP(opr.pop); } catch(Exception e) { writefln("%s\n%s\n%s^", e.msg, xpr, " ".replicate(xpHead)); root = null; return this; }   if (num.length != 1) { // Should be one XP left. "Parse Error...".writefln; root = null; } else { root = num.pop; } return this; } // End Parse. } // End class AST.   // To display AST fancy struct. void ins(ref char[][] s, in string v, in int p, in int l) pure nothrow @safe { if (l + 1 > s.length) s.length++; while (s[l].length < p + v.length + 1) s[l] ~= " "; s[l][p .. p + v.length] = v[]; }   final class CalcVis : Visitor { int result, level; string resultStr; char[][] Tree;   static void opCall(AST a) @safe { if (a && a.root) { auto c = new CalcVis; a.root.accept(c); foreach (immutable i; 1 .. c.Tree.length) { // More fancy. bool flipflop = false; enum char mk = '.'; foreach (immutable j; 0 .. c.Tree[i].length) { while (j >= c.Tree[i - 1].length) c.Tree[i - 1] ~= " "; immutable c1 = c.Tree[i][j]; immutable c2 = c.Tree[i - 1][j]; if (flipflop && (c1 == ' ') && c2 == ' ') c.Tree[i - 1][j] = mk; if (c1 != mk && c1 != ' ' && (j == 0 || !isDigit(c.Tree[i][j - 1]))) flipflop = !flipflop; } } foreach (const t; c.Tree) t.writefln; writefln("\n%s ==>\n%s = %s", a.xpr, c.resultStr, c.result); } else "Evalute invalid or null Expression.".writefln; }   // Calc. the value, display AST struct and eval order. override void visit(XP xp) @safe { ins(Tree, xp.str, xp.pos, level); level++; if (xp.type == Type.Num) { resultStr ~= xp.str; result = xp.str.to!int; } else { resultStr ~= "("; xp.LHS.accept(this); immutable int lhs = result; resultStr ~= opChar[xp.type]; xp.RHS.accept(this); resultStr ~= ")"; switch (xp.type) { case Type.Add: result = lhs + result; break; case Type.Sub: result = lhs - result; break; case Type.Mul: result = lhs * result; break; case Type.Div: result = lhs / result; break; default: throw new Exception("Invalid type"); } } level--; } }   void main(string[] args) /*@safe*/ { immutable exp0 = "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5" ~ " - 22/(7 + 2*(3 - 1)) - 1)) + 1"; immutable exp = (args.length > 1) ? args[1 .. $].join(' ') : exp0; new AST().parse(exp).CalcVis; // Should be 60. }
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.
#Ada
Ada
with Ada.Numerics.Elementary_Functions;   with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Events.Events;   procedure Archimedean_Spiral is   Width  : constant := 800; Height  : constant := 800; A  : constant := 4.2; B  : constant := 3.2; T_First  : constant := 4.0; T_Last  : constant := 100.0;   Window  : SDL.Video.Windows.Window; Renderer : SDL.Video.Renderers.Renderer; Event  : SDL.Events.Events.Events;   procedure Draw_Archimedean_Spiral is use type SDL.C.int; use Ada.Numerics.Elementary_Functions; Pi  : constant := Ada.Numerics.Pi; Step : constant := 0.002; T  : Float; R  : Float; begin T := T_First; loop R := A + B * T; Renderer.Draw (Point => (X => Width / 2 + SDL.C.int (R * Cos (T, 2.0 * Pi)), Y => Height / 2 - SDL.C.int (R * Sin (T, 2.0 * Pi)))); exit when T >= T_Last; T := T + Step; end loop; end Draw_Archimedean_Spiral;   procedure Wait is use type SDL.Events.Event_Types; begin loop while SDL.Events.Events.Poll (Event) loop if Event.Common.Event_Type = SDL.Events.Quit then return; end if; end loop; end loop; end Wait;   begin if not SDL.Initialise (Flags => SDL.Enable_Screen) then return; end if;   SDL.Video.Windows.Makers.Create (Win => Window, Title => "Archimedean spiral", Position => SDL.Natural_Coordinates'(X => 10, Y => 10), Size => SDL.Positive_Sizes'(Width, Height), Flags => 0); SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); Renderer.Set_Draw_Colour ((0, 0, 0, 255)); Renderer.Fill (Rectangle => (0, 0, Width, Height)); Renderer.Set_Draw_Colour ((0, 220, 0, 255));   Draw_Archimedean_Spiral; Window.Update_Surface;   Wait; Window.Finalize; SDL.Finalise; end 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.
#Acurity_Architect
Acurity Architect
Using #HASH-OFF, OPTION OICC ="^" , CICC ="^"
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)
#bc
bc
/* Put the value 42 into array g at index 3 */ g[3] = 42 /* Look at some other elements in g */ g[2] 0 g[4342] 0 /* Look at the elements of another array */ a[543] 0 /* Array names don't conflict with names of ordinary (scalar) identifiers */ g 0 g = 123 g 123 g[3] 42
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.
#Euphoria
Euphoria
constant REAL = 1, IMAG = 2 type complex(sequence s) return length(s) = 2 and atom(s[REAL]) and atom(s[IMAG]) end type   function add(complex a, complex b) return a + b end function   function mult(complex a, complex b) return {a[REAL] * b[REAL] - a[IMAG] * b[IMAG], a[REAL] * b[IMAG] + a[IMAG] * b[REAL]} end function   function inv(complex a) atom denom denom = a[REAL] * a[REAL] + a[IMAG] * a[IMAG] return {a[REAL] / denom, -a[IMAG] / denom} end function   function neg(complex a) return -a end function   function scomplex(complex a) sequence s if a[REAL] != 0 then s = sprintf("%g",a) else s = {} end if   if a[IMAG] != 0 then if a[IMAG] = 1 then s &= "+i" elsif a[IMAG] = -1 then s &= "-i" else s &= sprintf("%+gi",a[IMAG]) end if end if   if length(s) = 0 then return "0" else return s end if end function   complex a, b a = { 1.0, 1.0 } b = { 3.14159, 1.2 } printf(1,"a = %s\n",{scomplex(a)}) printf(1,"b = %s\n",{scomplex(b)}) printf(1,"a+b = %s\n",{scomplex(add(a,b))}) printf(1,"a*b = %s\n",{scomplex(mult(a,b))}) printf(1,"1/a = %s\n",{scomplex(inv(a))}) printf(1,"-a = %s\n",{scomplex(neg(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
#Fortran
Fortran
module module_rational   implicit none private public :: rational public :: rational_simplify public :: assignment (=) public :: operator (//) public :: operator (+) public :: operator (-) public :: operator (*) public :: operator (/) public :: operator (<) public :: operator (<=) public :: operator (>) public :: operator (>=) public :: operator (==) public :: operator (/=) public :: abs public :: int public :: modulo type rational integer :: numerator integer :: denominator end type rational interface assignment (=) module procedure assign_rational_int, assign_rational_real end interface interface operator (//) module procedure make_rational end interface interface operator (+) module procedure rational_add end interface interface operator (-) module procedure rational_minus, rational_subtract end interface interface operator (*) module procedure rational_multiply end interface interface operator (/) module procedure rational_divide end interface interface operator (<) module procedure rational_lt end interface interface operator (<=) module procedure rational_le end interface interface operator (>) module procedure rational_gt end interface interface operator (>=) module procedure rational_ge end interface interface operator (==) module procedure rational_eq end interface interface operator (/=) module procedure rational_ne end interface interface abs module procedure rational_abs end interface interface int module procedure rational_int end interface interface modulo module procedure rational_modulo end interface   contains   recursive function gcd (i, j) result (res) integer, intent (in) :: i integer, intent (in) :: j integer :: res if (j == 0) then res = i else res = gcd (j, modulo (i, j)) end if end function gcd   function rational_simplify (r) result (res) type (rational), intent (in) :: r type (rational) :: res integer :: g g = gcd (r % numerator, r % denominator) res = r % numerator / g // r % denominator / g end function rational_simplify   function make_rational (numerator, denominator) result (res) integer, intent (in) :: numerator integer, intent (in) :: denominator type (rational) :: res res = rational (numerator, denominator) end function make_rational   subroutine assign_rational_int (res, i) type (rational), intent (out), volatile :: res integer, intent (in) :: i res = i // 1 end subroutine assign_rational_int   subroutine assign_rational_real (res, x) type (rational), intent(out), volatile :: res real, intent (in) :: x integer :: x_floor real :: x_frac x_floor = floor (x) x_frac = x - x_floor if (x_frac == 0) then res = x_floor // 1 else res = (x_floor // 1) + (1 // floor (1 / x_frac)) end if end subroutine assign_rational_real   function rational_add (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s type (rational) :: res res = r % numerator * s % denominator + r % denominator * s % numerator // & & r % denominator * s % denominator end function rational_add   function rational_minus (r) result (res) type (rational), intent (in) :: r type (rational) :: res res = - r % numerator // r % denominator end function rational_minus   function rational_subtract (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s type (rational) :: res res = r % numerator * s % denominator - r % denominator * s % numerator // & & r % denominator * s % denominator end function rational_subtract   function rational_multiply (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s type (rational) :: res res = r % numerator * s % numerator // r % denominator * s % denominator end function rational_multiply   function rational_divide (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s type (rational) :: res res = r % numerator * s % denominator // r % denominator * s % numerator end function rational_divide   function rational_lt (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s type (rational) :: r_simple type (rational) :: s_simple logical :: res r_simple = rational_simplify (r) s_simple = rational_simplify (s) res = r_simple % numerator * s_simple % denominator < & & s_simple % numerator * r_simple % denominator end function rational_lt   function rational_le (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s type (rational) :: r_simple type (rational) :: s_simple logical :: res r_simple = rational_simplify (r) s_simple = rational_simplify (s) res = r_simple % numerator * s_simple % denominator <= & & s_simple % numerator * r_simple % denominator end function rational_le   function rational_gt (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s type (rational) :: r_simple type (rational) :: s_simple logical :: res r_simple = rational_simplify (r) s_simple = rational_simplify (s) res = r_simple % numerator * s_simple % denominator > & & s_simple % numerator * r_simple % denominator end function rational_gt   function rational_ge (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s type (rational) :: r_simple type (rational) :: s_simple logical :: res r_simple = rational_simplify (r) s_simple = rational_simplify (s) res = r_simple % numerator * s_simple % denominator >= & & s_simple % numerator * r_simple % denominator end function rational_ge   function rational_eq (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s logical :: res res = r % numerator * s % denominator == s % numerator * r % denominator end function rational_eq   function rational_ne (r, s) result (res) type (rational), intent (in) :: r type (rational), intent (in) :: s logical :: res res = r % numerator * s % denominator /= s % numerator * r % denominator end function rational_ne   function rational_abs (r) result (res) type (rational), intent (in) :: r type (rational) :: res res = sign (r % numerator, r % denominator) // r % denominator end function rational_abs   function rational_int (r) result (res) type (rational), intent (in) :: r integer :: res res = r % numerator / r % denominator end function rational_int   function rational_modulo (r) result (res) type (rational), intent (in) :: r integer :: res res = modulo (r % numerator, r % denominator) end function rational_modulo   end module module_rational
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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) a := real(A[1]) | 1.0 g := real(A[2]) | (1 / 2^0.5) epsilon := real(A[3]) write("agm(",a,",",g,") = ",agm(a,g,epsilon)) end   procedure agm(an, gn, e) /e := 1e-15 while abs(an-gn) > e do { ap := (an+gn)/2.0 gn := (an*gn)^0.5 an := ap } return an 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
#J
J
mean=: +/ % # (mean , */ %:~ #)^:_] 1,%%:2 0.8472130847939792 0.8472130847939791
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.
#XSLT
XSLT
<xsl:template name="arithmetic"> <xsl:param name="a">5</xsl:param> <xsl:param name="b">2</xsl:param> <fo:block>a + b = <xsl:value-of select="$a + $b"/></fo:block> <fo:block>a - b = <xsl:value-of select="$a - $b"/></fo:block> <fo:block>a * b = <xsl:value-of select="$a * $b"/></fo:block> <fo:block>a / b = <xsl:value-of select="round($a div $b)"/></fo:block> <fo:block>a mod b = <xsl:value-of select="$a mod $b"/></fo:block> </xsl:template>
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.
#Delphi
Delphi
type Expr = Bin(op, Expr left, Expr right) or Literal(Float val) with Lookup   type Token(val, Char kind) with Lookup func Token.ToString() => this.val.ToString()   func tokenize(str) { func isSep(c) => c is '+' or '-' or '*' or '/' or ' ' or '\t' or '\n' or '\r' or '(' or ')' or '\0'   var idx = -1 let len = str.Length() let tokens = []   func next() { idx += 1 return '\0' when idx >= len str[idx] }   while true { let c = next()   match c { '\0' => { break }, '+' => tokens.Add(Token(c, '+')), '-' => tokens.Add(Token(c, '-')), '*' => tokens.Add(Token(c, '*')), '/' => tokens.Add(Token(c, '/')), '(' => tokens.Add(Token(c, '(')), ')' => tokens.Add(Token(c, ')')), _ => { let i = idx while !isSep(next()) { } idx -= 1 tokens.Add(Token(Float.Parse(str[i..idx]), 'F')) } } }   tokens }   func parse(tokens) { var idx = -1 let len = tokens.Length() let eol = Token(val: nil, kind: 'E') func pop() { idx += 1 return eol when idx == len tokens[idx] } func peek() { let t = pop() idx -=1 t } func expect(kind) { peek().kind == kind } var add_or_sub1   func literal() { return false when !expect('F') Expr.Literal(pop().val) }   func group() { return false when !expect('(') pop() var ret = add_or_sub1() throw "Invalid group" when !expect(')') pop() ret }   func mul_or_div() { var fst = group() fst = literal() when !fst return fst when !expect('*') && !expect('/') let op = pop().val var snd = group() snd = literal() when !snd Expr.Bin(op, fst, snd) }   func add_or_sub() { let fst = mul_or_div() return fst when !expect('+') && !expect('-') let op = pop().val let snd = mul_or_div() Expr.Bin(op, fst, snd) } add_or_sub1 = add_or_sub   add_or_sub() }   func exec(ast) { match ast { Bin(op, left, right) => { return exec(left) + exec(right) when op == '+' return exec(left) - exec(right) when op == '-' return exec(left) * exec(right) when op == '*' return exec(left) / exec(right) when op == '/' }, Literal(value) => value } }   func eval(str) { let tokens = tokenize(str) let ast = parse(tokens) exec(ast) }   print( eval("(1+33.23)*7") ) print( eval("1+33.23*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.
#ALGOL_W
ALGOL W
begin % draw an Archimedian spiral %  % Translation of AWK which was a trnslation of Applesoft Basic program % integer procedure max ( integer x, y ) ; begin if x > y then x else y end; integer procedure min ( integer x, y ) ; begin if x < y then x else y end; integer x_min, y_min, x_max, y_max, a, b, x, y; string(255) array arr ( 1 :: 255 ); real h, w, m, s, t; x_min := y_min := 9999; x_max := y_max := 0; h := 96; w := h + h / 2; a := 1; b := 1; m := 6 * PI; s := .02; t := s; while t <= m do begin % build spiral % real r; r := a + b * t; x := round(r * cos(t) + w); y := round(r * sin(t) + h); if x <= 0 or y <= 0 then begin end else if x >= 280 then begin end else if y >= 192 then begin end else begin arr( x )( y // 1 ) := "*"; x_min := min(x_min,x); x_max := max(x_max,x); y_min := min(y_min,y); y_max := max(y_max,y); t  := t + s end if__various_x_and_y_values__ end while__t_le_m ; for i := x_min until x_max do begin for j := y_min until y_max do begin string(1) c; c := arr( i )( j // 1 ); writeon( c, c ) end for_j ; write() end for_i 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.
#APL
APL
'InitCauseway' 'View' ⎕CY 'sharpplot' InitCauseway ⍬ ⍝ initialise current namespace sp←⎕NEW Causeway.SharpPlot sp.DrawPolarChart {⍵(360|⍵)}⌽⍳720 View sp
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.
#AutoHotkey
AutoHotkey
if !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp } OnExit, Exit SysGet, MonitorPrimary, MonitorPrimary SysGet, WA, MonitorWorkArea, %MonitorPrimary% WAWidth := WARight-WALeft WAHeight := WABottom-WATop Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs Gui, 1: Show, NA hwnd1 := WinExist() hbm := CreateDIBSection(WAWidth, WAHeight) hdc := CreateCompatibleDC() obm := SelectObject(hdc, hbm) G := Gdip_GraphicsFromHDC(hdc) Gdip_SetSmoothingMode(G, 4) pPen := Gdip_CreatePen(0xffff0000, 3) ;-------------------------------- a := 1, b := 4, th := 0.1, step := 0.1 loop, 720 { th += step r := a + b * th x1 := r * Cos(th) y1 := r * Sin(th) x1 += A_ScreenWidth/2 y1 += A_ScreenHeight/2 if (x2 && y2) Gdip_DrawLine(G, pPen, x1, y1, x2, y2) x2 := x1, y2 := y1 if GetKeyState("Esc", "P") break ; next two lines are optional to watch it draw ; Sleep 10 ; UpdateLayeredWindow(hwnd1, hdc, WALeft, WATop, WAWidth, WAHeight) } UpdateLayeredWindow(hwnd1, hdc, WALeft, WATop, WAWidth, WAHeight) ;-------------------------------- return   Exit: Gdip_DeletePen(pPen) SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) Gdip_Shutdown(pToken) ExitApp Return
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.
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Doors is type Door_State is (Closed, Open); type Door_List is array(Positive range 1..100) of Door_State; The_Doors : Door_List := (others => Closed); begin for I in 1..100 loop for J in The_Doors'range loop if J mod I = 0 then if The_Doors(J) = Closed then The_Doors(J) := Open; else The_Doors(J) := Closed; end if; end if; end loop; end loop; for I in The_Doors'range loop Put_Line(Integer'Image(I) & " is " & Door_State'Image(The_Doors(I))); end loop; end 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)
#BML
BML
  % Define an array(containing the numbers 1-3) named arr in the group $ in $ let arr hold 1 2 3   % Replace the value at index 0 in array to "Index 0" set $arr index 0 to "Index 0"   % Will display "Index 0" display $arr index 0   % There is no automatic garbage collection delete $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.
#Excel
Excel
  =IMSUM(A1;B1)  
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.
#F.23
F#
  > open Microsoft.FSharp.Math;;   > let a = complex 1.0 1.0;; val a : complex = 1r+1i   > let b = complex 3.14159 1.25;; val b : complex = 3.14159r+1.25i   > a + b;; val it : Complex = 4.14159r+2.25i {Conjugate = 4.14159r-2.25i; ImaginaryPart = 2.25; Magnitude = 4.713307515; Phase = 0.497661247; RealPart = 4.14159; i = 2.25; r = 4.14159;}   > a * b;; val it : Complex = 1.89159r+4.39159i {Conjugate = 1.89159r-4.39159i; ImaginaryPart = 4.39159; Magnitude = 4.781649868; Phase = 1.164082262; RealPart = 1.89159; i = 4.39159; r = 1.89159;}   > a / b;; val it : Complex = 0.384145932435901r+0.165463215905043i {Conjugate = 0.384145932435901r-0.165463215905043i; ImaginaryPart = 0.1654632159; Magnitude = 0.418265673; Phase = 0.4067140652; RealPart = 0.3841459324; i = 0.1654632159; r = 0.3841459324;}   > -a;; val it : complex = -1r-1i {Conjugate = -1r+1i; ImaginaryPart = -1.0; Magnitude = 1.414213562; Phase = -2.35619449; RealPart = -1.0; i = -1.0; r = -1.0;}  
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
#Frink
Frink
  1/2 + 2/3 // 7/6 (approx. 1.1666666666666667)   1/2 + 1/2 // 1   5/sextillion + 3/quadrillion // 600001/200000000000000000000 (exactly 3.000005e-15)   8^(1/3) // 2 (note the exact integer result.)  
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
#Java
Java
/* * Arithmetic-Geometric Mean of 1 & 1/sqrt(2) * Brendan Shaklovitz * 5/29/12 */ public class ArithmeticGeometricMean {   public static double agm(double a, double g) { double a1 = a; double g1 = g; while (Math.abs(a1 - g1) >= 1.0e-14) { double arith = (a1 + g1) / 2.0; double geom = Math.sqrt(a1 * g1); a1 = arith; g1 = geom; } return a1; }   public static void main(String[] args) { System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0))); } }
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.
#Yabasic
Yabasic
input "ingrese un numero? " a input "ingrese otro numero? " b   print "suma ", a, " + ", b, " = ", (a + b) print "resta ", a, " - ", b, " = ", (a - b) print "producto ", a, " * ", b, " = ", (a * b) print "division ", a, " \ ", b, " = ", int(a / b) print "modulo ", a, " % ", b, " = ", mod(a, b) print "potencia ", a, " ^ ", b, " = ", (a ^ b) end
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.
#Yorick
Yorick
x = y = 0; read, x, y; write, "x + y =", x + y; write, "x - y =", x - y; write, "x * y =", x * y; write, "x / y =", x / y; // rounds toward zero write, "x % y =", x % y; // remainder; matches sign of first operand when operands' signs differ write, "x ^ y =", x ^ y; // exponentiation
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.
#Dyalect
Dyalect
type Expr = Bin(op, Expr left, Expr right) or Literal(Float val) with Lookup   type Token(val, Char kind) with Lookup func Token.ToString() => this.val.ToString()   func tokenize(str) { func isSep(c) => c is '+' or '-' or '*' or '/' or ' ' or '\t' or '\n' or '\r' or '(' or ')' or '\0'   var idx = -1 let len = str.Length() let tokens = []   func next() { idx += 1 return '\0' when idx >= len str[idx] }   while true { let c = next()   match c { '\0' => { break }, '+' => tokens.Add(Token(c, '+')), '-' => tokens.Add(Token(c, '-')), '*' => tokens.Add(Token(c, '*')), '/' => tokens.Add(Token(c, '/')), '(' => tokens.Add(Token(c, '(')), ')' => tokens.Add(Token(c, ')')), _ => { let i = idx while !isSep(next()) { } idx -= 1 tokens.Add(Token(Float.Parse(str[i..idx]), 'F')) } } }   tokens }   func parse(tokens) { var idx = -1 let len = tokens.Length() let eol = Token(val: nil, kind: 'E') func pop() { idx += 1 return eol when idx == len tokens[idx] } func peek() { let t = pop() idx -=1 t } func expect(kind) { peek().kind == kind } var add_or_sub1   func literal() { return false when !expect('F') Expr.Literal(pop().val) }   func group() { return false when !expect('(') pop() var ret = add_or_sub1() throw "Invalid group" when !expect(')') pop() ret }   func mul_or_div() { var fst = group() fst = literal() when !fst return fst when !expect('*') && !expect('/') let op = pop().val var snd = group() snd = literal() when !snd Expr.Bin(op, fst, snd) }   func add_or_sub() { let fst = mul_or_div() return fst when !expect('+') && !expect('-') let op = pop().val let snd = mul_or_div() Expr.Bin(op, fst, snd) } add_or_sub1 = add_or_sub   add_or_sub() }   func exec(ast) { match ast { Bin(op, left, right) => { return exec(left) + exec(right) when op == '+' return exec(left) - exec(right) when op == '-' return exec(left) * exec(right) when op == '*' return exec(left) / exec(right) when op == '/' }, Literal(value) => value } }   func eval(str) { let tokens = tokenize(str) let ast = parse(tokens) exec(ast) }   print( eval("(1+33.23)*7") ) print( eval("1+33.23*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.
#AWK
AWK
  # syntax: GAWK -f ARCHIMEDEAN_SPIRAL.AWK # converted from Applesoft BASIC BEGIN { x_min = y_min = 9999 x_max = y_max = 0 h = 96 w = h + h / 2 a = 1 b = 1 m = 6 * 3.1415926 step = .02 for (t=step; t<=m; t+=step) { # build spiral r = a + b * t x = int(r * cos(t) + w) y = int(r * sin(t) + h) if (x <= 0 || y <= 0) { continue } if (x >= 280 ) { continue } if (y >= 192) { continue } arr[x,y] = "*" x_min = min(x_min,x) x_max = max(x_max,x) y_min = min(y_min,y) y_max = max(y_max,y) } for (i=x_min; i<=x_max; i++) { # print spiral rec = "" for (j=y_min; j<=y_max; j++) { rec = sprintf("%s%1s",rec,arr[i,j]) } printf("%s\n",rec) } exit(0) } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }  
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.
#BASIC
BASIC
a=1.5 b=1.5 pi=3.141592   PSET (320,100) FOR t=0 TO 40*pi STEP .1 r=a+b*t LINE -(320+2*r*SIN(t),100+r*COS(t)) NEXT
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.
#Agena
Agena
# find the first few squares via the unoptimised door flipping method scope   local doorMax := 100; local door; create register door( doorMax );   # set all doors to closed for i to doorMax do door[ i ] := false od;   # repeatedly flip the doors for i to doorMax do for j from i to doorMax by i do door[ j ] := not door[ j ] od od;   # display the results for i to doorMax do if door[ i ] then write( " ", i ) fi od; print()   epocs
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)
#Boo
Boo
  myArray as (int) = (1, 2, 3) // Size based on initialization fixedArray as (int) = array(int, 1) // Given size(1 in this case)   myArray[0] = 10   myArray = myArray + fixedArray // Append arrays   print myArray[0]  
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.
#Factor
Factor
USING: combinators kernel math math.functions prettyprint ;   C{ 1 2 } C{ 0.9 -2.78 } { [ + . ]  ! addition [ - . ]  ! subtraction [ * . ]  ! multiplication [ / . ]  ! division [ ^ . ]  ! power } 2cleave   C{ 1 2 } { [ neg . ]  ! negation [ recip . ]  ! multiplicative inverse [ conjugate . ]  ! complex conjugate [ sin . ]  ! sine [ log . ]  ! natural logarithm [ sqrt . ]  ! square root } cleave
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
#GAP
GAP
2/3 in Rationals; # true 2/3 + 3/4; # 17/12
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
#JavaScript
JavaScript
function agm(a0, g0) { var an = (a0 + g0) / 2, gn = Math.sqrt(a0 * g0); while (Math.abs(an - gn) > tolerance) { an = (an + gn) / 2, gn = Math.sqrt(an * gn) } return an; }   agm(1, 1 / Math.sqrt(2));
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.
#zkl
zkl
x,y:=ask("Two ints: ").split(" ").apply("toInt"); println("x+y = ",x + y); println("x-y = ",x - y); println("x*y = ",x * y); println("x/y = ",x / y); // rounds toward zero println("x%y = ",x % y); // remainder; matches sign of first operand when operands' signs differ println("x.divr(y) = ",x.divr(y)); // (x/y,remainder); sign as above
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.
#zonnon
zonnon
  module Main; var i,j: integer; begin write("A integer?:");readln(i); write("another?: ");readln(j); writeln("sum: ",i + j); writeln("difference: ", i - j); writeln("product: ", i * j); writeln("quotient: ", i div j); writeln("remainder: ", i mod j); end Main.  
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.
#E
E
def eParser := <elang:syntax.makeEParser> def LiteralExpr := <elang:evm.makeLiteralExpr>.asType() def arithEvaluate(expr :String) { def ast := eParser(expr)   def evalAST(ast) { return switch (ast) { match e`@a + @b` { evalAST(a) + evalAST(b) } match e`@a - @b` { evalAST(a) - evalAST(b) } match e`@a * @b` { evalAST(a) * evalAST(b) } match e`@a / @b` { evalAST(a) / evalAST(b) } match e`-@a` { -(evalAST(a)) } match l :LiteralExpr { l.getValue() } } }   return evalAST(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.
#BQN
BQN
{(•math.Sin •Plot○(⊢×↕∘≠) •math.Cos) -(2×π) × 𝕩⥊(↕÷-⟜1)100}