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/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#AutoHotkey
AutoHotkey
Fib := NStepSequence(1, 2, 2, 20) Loop, 21 { i := A_Index - 1 , Out .= i ":`t", n := "" Loop, % Fib.MaxIndex() { x := Fib.MaxIndex() + 1 - A_Index if (Fib[x] <= i) n .= 1, i -= Fib[x] else n .= 0 } Out .= (n ? LTrim(n, "0") : 0) "`n" } MsgBox, % Out   NStepSequence(v1, v2, n, k) { a := [v1, v2] Loop, % k - 2 { a[j := A_Index + 2] := 0 Loop, % j < n + 2 ? j - 1 : n a[j] += a[j - A_Index] } return, a }
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.
#B
B
main() { auto doors[100]; /* != 0 means open */ auto pass, door;   door = 0; while( door<100 ) doors[door++] = 0;   pass = 0; while( pass<100 ) { door = pass; while( door<100 ) { doors[door] = !doors[door]; door =+ pass+1; } ++pass; }   door = 0; while( door<100 ) { printf("door #%d is %s.*n", door+1, doors[door] ? "open" : "closed"); ++door; }   return(0); }
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)
#Dao
Dao
# use [] to create numeric arrays of int, float, double or complex types: a = [ 1, 2, 3 ] # a vector b = [ 1, 2; 3, 4 ] # a 2X2 matrix   # use {} to create normal arrays of any types: c = { 1, 2, 'abc' }   d = a[1] e = b[0,1] # first row, second column f = c[1]
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.
#Lua
Lua
    --defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs. complex = setmetatable({ __add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end, __sub = function(u, v) return complex(u.real - v.real, u.imag - v.imag) end, __mul = function(u, v) return complex(u.real * v.real - u.imag * v.imag, u.real * v.imag + u.imag * v.real) end, __div = function(u, v) return u * complex(v.real / v.norm, -v.imag / v.norm) end, __unm = function(u) return complex(-u.real, -u.imag) end, __concat = function(u, v) if type(u) == "table" then return u.real .. " + " .. u.imag .. "i" .. v elseif type(u) == "string" or type(u) == "number" then return u .. v.real .. " + " .. v.imag .. "i" end end, __index = function(u, index) local operations = { norm = function(u) return u.real ^ 2 + u.imag ^ 2 end, conj = function(u) return complex(u.real, -u.imag) end, } return operations[index] and operations[index](u) end, __newindex = function() error() end }, { __call = function(z, realpart, imagpart) return setmetatable({real = realpart, imag = imagpart}, complex) end } )   local i, j = complex(2, 3), complex(1, 1)   print(i .. " + " .. j .. " = " .. (i+j)) print(i .. " - " .. j .. " = " .. (i-j)) print(i .. " * " .. j .. " = " .. (i*j)) print(i .. " / " .. j .. " = " .. (i/j)) print("|" .. i .. "| = " .. math.sqrt(i.norm)) print(i .. "* = " .. i.conj)  
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
#Nim
Nim
import math   proc `^`[T](base, exp: T): T = var (base, exp) = (base, exp) result = 1   while exp != 0: if (exp and 1) != 0: result *= base exp = exp shr 1 base *= base   proc gcd[T](u, v: T): T = if v != 0: gcd(v, u mod v) else: u.abs   proc lcm[T](a, b: T): T = a div gcd(a, b) * b   type Rational* = tuple[num, den: int64]   proc fromInt*(x: SomeInteger): Rational = result.num = x result.den = 1   proc frac*(x: var Rational) = let common = gcd(x.num, x.den) x.num = x.num div common x.den = x.den div common   proc `+` *(x, y: Rational): Rational = let common = lcm(x.den, y.den) result.num = common div x.den * x.num + common div y.den * y.num result.den = common result.frac   proc `+=` *(x: var Rational, y: Rational) = let common = lcm(x.den, y.den) x.num = common div x.den * x.num + common div y.den * y.num x.den = common x.frac   proc `-` *(x: Rational): Rational = result.num = -x.num result.den = x.den   proc `-` *(x, y: Rational): Rational = x + -y   proc `-=` *(x: var Rational, y: Rational) = x += -y   proc `*` *(x, y: Rational): Rational = result.num = x.num * y.num result.den = x.den * y.den result.frac   proc `*=` *(x: var Rational, y: Rational) = x.num *= y.num x.den *= y.den x.frac   proc reciprocal*(x: Rational): Rational = result.num = x.den result.den = x.num   proc `div`*(x, y: Rational): Rational = x * y.reciprocal   proc toFloat*(x: Rational): float = x.num.float / x.den.float   proc toInt*(x: Rational): int64 = x.num div x.den   proc cmp*(x, y: Rational): int = cmp x.toFloat, y.toFloat   proc `<` *(x, y: Rational): bool = x.toFloat < y.toFloat   proc `<=` *(x, y: Rational): bool = x.toFloat <= y.toFloat   proc abs*(x: Rational): Rational = result.num = abs x.num result.den = abs x.den   for candidate in 2'i64 .. <((2'i64)^19): var sum: Rational = (1'i64, candidate) for factor in 2'i64 .. pow(candidate.float, 0.5).int64: if candidate mod factor == 0: sum += (1'i64, factor) + (1'i64, candidate div factor) if sum.den == 1: echo "Sum of recipr. factors of ",candidate," = ",sum.num," exactly ", if sum.num == 1: "perfect!" else: ""
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
#PicoLisp
PicoLisp
(scl 80)   (de agm (A G) (do 7 (prog1 (/ (+ A G) 2) (setq G (sqrt A G) A @) ) ) )   (round (agm 1.0 (*/ 1.0 1.0 (sqrt 2.0 1.0))) 70 )
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
#PL.2FI
PL/I
  arithmetic_geometric_mean: /* 31 August 2012 */ procedure options (main); declare (a, g, t) float (18);   a = 1; g = 1/sqrt(2.0q0); put skip list ('The arithmetic-geometric mean of ' || a || ' and ' || g || ':'); do until (abs(a-g) < 1e-15*a); t = (a + g)/2; g = sqrt(a*g); a = t; put skip data (a, g); end; put skip list ('The result is:', a); end arithmetic_geometric_mean;  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#C.2B.2B
C++
#include <iostream> #include <cmath> #include <complex>   int main() { std::cout << "0 ^ 0 = " << std::pow(0,0) << std::endl; std::cout << "0+0i ^ 0+0i = " << std::pow(std::complex<double>(0),std::complex<double>(0)) << std::endl; return 0; }
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Cach.C3.A9_ObjectScript
Caché ObjectScript
ZEROPOW // default behavior is incorrect: set (x,y) = 0 w !,"0 to the 0th power (wrong): "_(x**y)  ; will output 0   // if one or both of the values is a double, this works set (x,y) = $DOUBLE(0) w !,"0 to the 0th power (right): "_(x**y)   quit
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
(*parsing:*) parse[string_] := Module[{e}, StringCases[string, "+" | "-" | "*" | "/" | "(" | ")" | DigitCharacter ..] //. {a_String?DigitQ :> e[ToExpression@a], {x___, PatternSequence["(", a_e, ")"], y___} :> {x, a, y}, {x : PatternSequence[] | PatternSequence[___, "(" | "+" | "-" | "*" | "/"], PatternSequence[op : "+" | "-", a_e], y___} :> {x, e[op, a], y}, {x : PatternSequence[] | PatternSequence[___, "(" | "+" | "-"], PatternSequence[a_e, op : "*" | "/", b_e], y___} :> {x, e[op, a, b], y}, {x : PatternSequence[] | PatternSequence[___, "(" | "+" | "-"], PatternSequence[a_e, b_e], y___} :> {x, e["*", a, b], y}, {x : PatternSequence[] | PatternSequence[___, "("], PatternSequence[a_e, op : "+" | "-", b_e], y : PatternSequence[] | PatternSequence[")" | "+" | "-", ___]} :> {x, e[op, a, b], y}} //. {e -> List, {a_Integer} :> a, {a_List} :> a}]   (*evaluation*) evaluate[a_Integer] := a; evaluate[{"+", a_}] := evaluate[a]; evaluate[{"-", a_}] := -evaluate[a]; evaluate[{"+", a_, b_}] := evaluate[a] + evaluate[b]; evaluate[{"-", a_, b_}] := evaluate[a] - evaluate[b]; evaluate[{"*", a_, b_}] := evaluate[a]*evaluate[b]; evaluate[{"/", a_, b_}] := evaluate[a]/evaluate[b]; evaluate[string_String] := evaluate[parse[string]]
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#AppleScript
AppleScript
-- Params: -- List of lists (rows) of "pixel" values. -- Record indicating the values representing black and white. on ZhangSuen(matrix, {black:black, white:white}) script o property matrix : missing value property changePixels : missing value   on A(neighbours) -- Count transitions from white to black. set sum to 0 repeat with i from 1 to 8 if ((neighbours's item i is white) and (neighbours's item (i mod 8 + 1) is black)) then set sum to sum + 1 end repeat return sum end A   on B(neighbours) -- Count neighbouring black pixels. set sum to 0 repeat with p in neighbours if (p's contents is black) then set sum to sum + 1 end repeat return sum end B end script   set o's matrix to matrix set rowCount to (count o's matrix) set columnCount to (count o's matrix's beginning) -- Assumed to be the same for every row. repeat until (o's changePixels is {}) repeat with step from 1 to 2 set o's changePixels to {} repeat with r from 2 to (rowCount - 1) repeat with c from 2 to (columnCount - 1) if (o's matrix's item r's item c is black) then tell (a reference to o's matrix) to ¬ set neighbours to {item (r - 1)'s item c, item (r - 1)'s item (c + 1), ¬ item r's item (c + 1), item (r + 1)'s item (c + 1), item (r + 1)'s item c, ¬ item (r + 1)'s item (c - 1), item r's item (c - 1), item (r - 1)'s item (c - 1)} set blackCount to o's B(neighbours) if ((blackCount > 1) and (blackCount < 7) and (o's A(neighbours) is 1)) then set {P2, x, P4, x, P6, x, P8} to neighbours if (step is 1) then set toChange to ((P4 is white) or (P6 is white) or ((P2 is white) and (P8 is white))) else set toChange to ((P2 is white) or (P8 is white) or ((P4 is white) and (P6 is white))) end if if (toChange) then set end of o's changePixels to {r, c} end if end if end repeat end repeat if (o's changePixels is {}) then exit repeat repeat with pixel in o's changePixels set {r, c} to pixel set o's matrix's item r's item c to white end repeat end repeat end repeat   return o's matrix -- or: return matrix -- The input has been edited in place. end ZhangSuen   on join(lst, delim) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delim set txt to lst as text set AppleScript's text item delimiters to astid return txt end join   on demo() set pattern to "00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000" set matrix to pattern's paragraphs repeat with thisRow in matrix set thisRow's contents to thisRow's characters end repeat ZhangSuen(matrix, {black:"1", white:"0"}) repeat with thisRow in matrix set thisRow's contents to join(thisRow, "") end repeat return join(matrix, linefeed) end demo return demo()
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.
#Scheme
Scheme
  (import (scheme base) (scheme complex) (rebottled pstk))   ; settings for spiral (define *resolution* 0.01) (define *count* 2000) (define *a* 10) (define *b* 10) (define *center* (let ((size 200)) ; change this to alter size of display (* size 1+i)))   (define (draw-spiral canvas) (define (coords theta) (let ((r (+ *a* (* *b* theta)))) (make-polar r theta))) ; (do ((i 0 (+ i 1))) ; loop to draw spiral ((= i *count*) ) (let ((c (+ (coords (* i *resolution*)) *center*))) (canvas 'create 'line (real-part c) (imag-part c) (+ 1 (real-part c)) (imag-part c)))))   (let ((tk (tk-start))) (tk/wm 'title tk "Archimedean Spiral") (let ((canvas (tk 'create-widget 'canvas))) (tk/pack canvas) (canvas 'configure 'height: (* 2 (real-part *center*)) 'width: (* 2 (imag-part *center*))) (draw-spiral canvas)) (tk-event-loop tk))  
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#AutoIt
AutoIt
  For $i = 0 To 20 ConsoleWrite($i &": "& Zeckendorf($i)&@CRLF) Next   Func Zeckendorf($int, $Fibarray = "") If Not IsArray($Fibarray) Then $Fibarray = Fibonacci($int) Local $ret = "" For $i = UBound($Fibarray) - 1 To 1 Step -1 If $Fibarray[$i] > $int And $ret = "" Then ContinueLoop ; dont use Leading Zeros If $Fibarray[$i] > $int Then $ret &= "0" Else If StringRight($ret, 1) <> "1" Then $ret &= "1" $int -= $Fibarray[$i] Else $ret &= "0" EndIf EndIf Next If $ret = "" Then $ret = "0" Return $ret EndFunc ;==>Zeckendorf   Func Fibonacci($max) $AList = ObjCreate("System.Collections.ArrayList") $AList.add("0") $current = 0 While True If $current > 1 Then $count = $AList.Count $current = $AList.Item($count - 1) $current = $current + $AList.Item($count - 2) Else $current += 1 EndIf $AList.add($current) If $current > $max Then ExitLoop WEnd $Array = $AList.ToArray Return $Array EndFunc ;==>Fibonacci  
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.
#BaCon
BaCon
  OPTION BASE 1   DECLARE doors[100]   FOR size = 1 TO 100 FOR pass = 0 TO 100 STEP size doors[pass] = NOT(doors[pass]) NEXT NEXT   FOR which = 1 TO 100 IF doors[which] THEN PRINT which NEXT  
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)
#Dart
Dart
  main(){ // Dart uses Lists which dynamically resize by default final growable = [ 1, 2, 3 ];   // Add to the list using the add method growable.add(4);   print('growable: $growable');   // You can pass an int to the constructor to create a fixed sized List final fixed = List(3);   // We must assign each element individually using the Subscript operator // using .add would through an error fixed[0] = 'one'; fixed[1] = 'two'; fixed[2] = 'three';   print('fixed: $fixed');   // If we want to create a fixed list all at once we can use the of constructor // Setting growable to false is what makes it fixed final fixed2 = List.of( [ 1.5, 2.5, 3.5 ], growable: false);   print('fixed2: $fixed2');   // A potential gotcha involving the subscript operator [] might surprise JavaScripters // One cannot add new elements to a List using the subscript operator // We can only assign to existing elements, even if the List is growable   final gotcha = [ 1, 2 ]; // gotcha[2] = 3 would cause an error in Dart, but not in JavaScript // We must first add the new element using .add gotcha.add(3); // Now we can modify the existing elements with the subscript gotcha[2] = 4;   print('gotcha: $gotcha');     }    
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.
#Maple
Maple
x := 1+I; y := Pi+I*1.2;
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
x=1+2I y=3+4I   x+y => 4 + 6 I x-y => -2 - 2 I y x => -5 + 10 I y/x => 11/5 - (2 I)/5 x^3 => -11 - 2 I y^4 => -527 - 336 I x^y => (1 + 2 I)^(3 + 4 I) N[x^y] => 0.12901 + 0.0339241 I
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
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface RCRationalNumber : NSObject { @private int numerator; int denominator; BOOL autoSimplify; BOOL withSign; } +(instancetype)valueWithNumerator:(int)num andDenominator: (int)den; +(instancetype)valueWithDouble: (double)fnum; +(instancetype)valueWithInteger: (int)inum; +(instancetype)valueWithRational: (RCRationalNumber *)rnum; -(instancetype)initWithNumerator: (int)num andDenominator: (int)den; -(instancetype)initWithDouble: (double)fnum precision: (int)prec; -(instancetype)initWithInteger: (int)inum; -(instancetype)initWithRational: (RCRationalNumber *)rnum; -(NSComparisonResult)compare: (RCRationalNumber *)rnum; -(id)simplify: (BOOL)act; -(void)setAutoSimplify: (BOOL)v; -(void)setWithSign: (BOOL)v; -(BOOL)autoSimplify; -(BOOL)withSign; -(NSString *)description; // ops -(id)multiply: (RCRationalNumber *)rnum; -(id)divide: (RCRationalNumber *)rnum; -(id)add: (RCRationalNumber *)rnum; -(id)sub: (RCRationalNumber *)rnum; -(id)abs; -(id)neg; -(id)mod: (RCRationalNumber *)rnum; -(int)sign; -(BOOL)isNegative; -(id)reciprocal; // getter -(int)numerator; -(int)denominator; //setter -(void)setNumerator: (int)num; -(void)setDenominator: (int)num; // defraction -(double)number; -(int)integer; @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
#Potion
Potion
sqrt = (x) : xi = 1 7 times : xi = (xi + x / xi) / 2 . xi .   agm = (x, y) : 7 times : a = (x + y) / 2 g = sqrt(x * y) x = a y = g . x .
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
#PowerShell
PowerShell
  function agm ([Double]$a, [Double]$g) { [Double]$eps = 1E-15 [Double]$a1 = [Double]$g1 = 0 while([Math]::Abs($a - $g) -gt $eps) { $a1, $g1 = $a, $g $a = ($a1 + $g1)/2 $g = [Math]::Sqrt($a1*$g1) } [pscustomobject]@{ a = "$a" g = "$g" } } agm 1 (1/[Math]::Sqrt(2))  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Clojure
Clojure
user=> (use 'clojure.math.numeric-tower) user=> (expt 0 0) 1 ; alternative java-interop route: user=> (Math/pow 0 0) 1.0
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#CLU
CLU
start_up = proc () zz_int: int := 0 ** 0 zz_real: real := 0.0 ** 0.0   po: stream := stream$primary_output() stream$putl(po, "integer 0**0: " || int$unparse(zz_int)) stream$putl(po, "real 0**0: " || f_form(zz_real, 1, 1)) end start_up
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#COBOL
COBOL
identification division. program-id. zero-power-zero-program. data division. working-storage section. 77 n pic 9. procedure division. compute n = 0**0. display n upon console. stop run.
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.
#MiniScript
MiniScript
Expr = {} Expr.eval = 0   BinaryExpr = new Expr BinaryExpr.eval = function() if self.op == "+" then return self.lhs.eval + self.rhs.eval if self.op == "-" then return self.lhs.eval - self.rhs.eval if self.op == "*" then return self.lhs.eval * self.rhs.eval if self.op == "/" then return self.lhs.eval / self.rhs.eval end function binop = function(lhs, op, rhs) e = new BinaryExpr e.lhs = lhs e.op = op e.rhs = rhs return e end function   parseAtom = function(inp) tok = inp.pull if tok >= "0" and tok <= "9" then e = new Expr e.eval = val(tok) while inp and inp[0] >= "0" and inp[0] <= "9" e.eval = e.eval * 10 + val(inp.pull) end while else if tok == "(" then e = parseAddSub(inp) inp.pull // swallow closing ")" return e else print "Unexpected token: " + tok exit end if return e end function   parseMultDiv = function(inp) next = @parseAtom e = next(inp) while inp and (inp[0] == "*" or inp[0] == "/") e = binop(e, inp.pull, next(inp)) end while return e end function   parseAddSub = function(inp) next = @parseMultDiv e = next(inp) while inp and (inp[0] == "+" or inp[0] == "-") e = binop(e, inp.pull, next(inp)) end while return e end function   while true s = input("Enter expression: ").replace(" ","") if not s then break inp = split(s, "") ast = parseAddSub(inp) print ast.eval end while  
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#AutoHotkey
AutoHotkey
FileIn := A_ScriptDir "\Zhang-Suen.txt" FileOut := A_ScriptDir "\NewFile.txt"   if (!FileExist(FileIn)) { MsgBox, 48, File Not Found, % "File """ FileIn """ not found." ExitApp } S := {} N := [2,3,4,5,6,7,8,9,2]   Loop, Read, % FileIn { LineNum := A_Index Loop, Parse, A_LoopReadLine S[LineNum, A_Index] := A_LoopField }   Loop { FlipCount := 0 Loop, 2 { Noted := [], i := A_Index for LineNum, Line in S { for PixNum, Pix in Line { ; (0) if (Pix = 0 || (P := GetNeighbors(LineNum, PixNum, S)) = 1) continue ; (1) BP := 0 for j, Val in P BP += Val if (BP < 2 || BP > 6) continue ; (2) AP := 0 Loop, 8 if (P[N[A_Index]] = "0" && P[N[A_Index + 1]] = "1") AP++ if (AP != 1) continue ; (3 and 4) if (i = 1) { if (P[2] + P[4] + P[6] = 3 || P[4] + P[6] + P[8] = 3) continue } else if (P[2] + P[4] + P[8] = 3 || P[2] + P[6] + P[8] = 3) continue   Noted.Insert([LineNum, PixNum]) FlipCount++ } } for j, Coords in Noted S[Coords[1], Coords[2]] := 0 } if (!FlipCount) break }   for LineNum, Line in S { for PixNum, Pix in Line Out .= Pix ? "#" : " " Out .= "`n" } FileAppend, % Out, % FileOut   GetNeighbors(Y, X, S) { Neighbors := [] if ((Neighbors[8] := S[Y, X - 1]) = "") return 1 if ((Neighbors[4] := S[Y, X + 1]) = "") return 1 Loop, 3 if ((Neighbors[A_Index = 1 ? 9 : A_Index] := S[Y - 1, X - 2 + A_Index]) = "") return 1 Loop, 3 if ((Neighbors[8 - A_Index] := S[Y + 1, X - 2 + A_Index]) = "") return 1 return Neighbors }
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.
#Scilab
Scilab
a = 3; b = 2;   theta = linspace(0,10*%pi,1000); r = a + b .* theta;   //1. Plot using polar coordinates scf(1); polarplot(theta,r);   //2. Plot using rectangular coordinates //2.1 Convert coordinates using Euler's formula z = r .* exp(%i .* theta); x = real(z); y = imag(z);   scf(2); plot2d(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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "draw.s7i"; include "keybd.s7i";   const proc: main is func local const float: xCenter is 117.0; const float: yCenter is 139.0; const float: maxTheta is 10.0 * PI; const float: delta is 0.01; const float: a is 1.0; const float: b is 7.0; var float: theta is 0.0; var float: radius is 0.0; begin screen(256, 256); clear(curr_win, black); KEYBOARD := GRAPH_KEYBOARD; while theta <= maxTheta do radius := a + b * theta; point(round(xCenter + radius * cos(theta)), round(yCenter - radius * sin(theta)), white); theta +:= delta; end while; DRAW_FLUSH; ignore(getc(KEYBOARD)); end func;
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.
#Sidef
Sidef
require('Imager') define π = Num.pi   var (w, h) = (400, 400) var img = %O<Imager>.new(xsize => w, ysize => h)   for Θ in (0 .. 52*π -> by(0.025)) { img.setpixel( x => floor(cos(Θ / π)*Θ + w/2), y => floor(sin(Θ / π)*Θ + h/2), color => [255, 0, 0] ) }   img.write(file => 'Archimedean_spiral.png')
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#BBC_BASIC
BBC BASIC
FOR n% = 0 TO 20 PRINT n% RIGHT$(" " + FNzeckendorf(n%), 8) NEXT PRINT '"Checking numbers up to 10000..." FOR n% = 21 TO 10000 IF INSTR(FNzeckendorf(n%), "11") STOP NEXT PRINT "No Zeckendorf numbers contain consecutive 1's" END   DEF FNzeckendorf(n%) LOCAL i%, o$, fib%() : DIM fib%(45) fib%(0) = 1 : fib%(1) = 1 : i% = 1 REPEAT i% += 1 fib%(i%) = fib%(i%-1) + fib%(i%-2) UNTIL fib%(i%) > n% REPEAT i% -= 1 IF n% >= fib%(i%) THEN o$ += "1" n% -= fib%(i%) ELSE o$ += "0" ENDIF UNTIL i% = 1 = o$
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Befunge
Befunge
45*83p0>:::.0`"0"v v53210p 39+!:,,9+< >858+37 *66g"7Y":v >3g`#@_^ v\g39$< ^8:+1,+5_5<>-:0\`| v:-\g39_^#:<*:p39< >0\`:!"0"+#^ ,#$_^
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#BASIC
BASIC
  100 : 110 REM 100 DOORS PROBLEM 120 : 130 DIM D(100) 140 FOR P = 1 TO 100 150 FOR T = P TO 100 STEP P 160 D(T) = NOT D(T): NEXT T 170 NEXT P 180 FOR I = 1 TO 100 190 IF D(I) THEN PRINT I;" "; 200 NEXT I  
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)
#DBL
DBL
; ; Arrays for DBL version 4 by Dario B. ;   .DEFINE NR,5   RECORD   VNUM1, 5D8  ;array of number VNUM2, [5]D8  ;array of number VNUM3, [5,2]D8  ;two-dimensional array of number   VALP1, 5A10  ;array of strings VALP2, [5]A10  ;array of strings VALP3, [5,2]A10  ;two-dimensional array of strings   VALP4, [NR]A10  ;array of strings   PROC ;------------------------------------------------------------------    ;Valid uses of arrays VNUM1(1)=12345678   VNUM2(1)=VNUM1(1)  ; = 12345678 VNUM2[2]=VNUM1(1)  ; = 12345678   VNUM2[3]=VNUM2[1](3:2)  ; = 34   VNUM3[1,1]=1 VNUM3[1,2]=2 VNUM3[2,1]=3     VALP1(1)="ABCDEFGHIJ"   VALP2(2)=VALP1(1)  ; = "ABCDEFGHIJ" VALP2[2]=VALP1(1)  ; = "ABCDEFGHIJ"   VALP2[3](3:2)=VALP2[1](3:2)  ; = " CD "   VALP3[1,1]="ABCDEFGHIJ" VALP3[1,2]=VALP3[1,1]  ;= "ABCDEFGHIJ" VALP3[2,1](3:2)=VALP3[1,2](3:2) ;= " CD "   VALP4[1]="ABCDEFGHIJ"    ;Clear arrays CLEAR VNUM1(1:5*8),VNUM3(1:5*2*8) VNUM2(1:5*8)= CLEAR VALP1(1:5*8),VALP2(1:5*10) VALP3(1:5*2*10)=
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#MATLAB
MATLAB
>> a = 1+i   a =   1.000000000000000 + 1.000000000000000i   >> b = 3+7i   b =   3.000000000000000 + 7.000000000000000i   >> a+b   ans =   4.000000000000000 + 8.000000000000000i   >> a-b   ans =   -2.000000000000000 - 6.000000000000000i   >> a*b   ans =   -4.000000000000000 +10.000000000000000i   >> a/b   ans =   0.172413793103448 - 0.068965517241379i   >> -a   ans =   -1.000000000000000 - 1.000000000000000i   >> a'   ans =   1.000000000000000 - 1.000000000000000i   >> a^b   ans =   0.000808197112874 - 0.011556516327187i   >> norm(a)   ans =   1.414213562373095
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
#OCaml
OCaml
#load "nums.cma";; open Num;;   for candidate = 2 to 1 lsl 19 do let sum = ref (num_of_int 1 // num_of_int candidate) in for factor = 2 to truncate (sqrt (float candidate)) do if candidate mod factor = 0 then sum := !sum +/ num_of_int 1 // num_of_int factor +/ num_of_int 1 // num_of_int (candidate / factor) done; if is_integer_num !sum then Printf.printf "Sum of recipr. factors of %d = %d exactly %s\n%!" candidate (int_of_num !sum) (if int_of_num !sum = 1 then "perfect!" else "") done;;
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
#Prolog
Prolog
  agm(A,G,A) :- abs(A-G) < 1.0e-15, !. agm(A,G,Res) :- A1 is (A+G)/2.0, G1 is sqrt(A*G),!, agm(A1,G1,Res).   ?- agm(1,1/sqrt(2),Res). Res = 0.8472130847939792.  
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
#PureBasic
PureBasic
Procedure.d AGM(a.d, g.d, ErrLim.d=1e-15) Protected.d ta=a+1, tg While ta <> a ta=a: tg=g a=(ta+tg)*0.5 g=Sqr(ta*tg) Wend ProcedureReturn a EndProcedure   If OpenConsole() PrintN(StrD(AGM(1, 1/Sqr(2)), 16)) Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#ColdFusion
ColdFusion
  <cfset zeroPowerTag = 0^0> <cfoutput>"#zeroPowerTag#"</cfoutput>  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Commodore_BASIC
Commodore BASIC
ready. print 0↑0 1 ready. █
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.
#Nim
Nim
import strutils import os   #-- # Lexer #--   type TokenKind = enum tokNumber tokPlus = "+", tokMinus = "-", tokStar = "*", tokSlash = "/" tokLPar, tokRPar tokEnd Token = object case kind: TokenKind of tokNumber: value: float else: discard   proc lex(input: string): seq[Token] = # Here we go through the entire input string and collect all the tokens into # a sequence. var pos = 0 while pos < input.len: case input[pos] of '0'..'9': # Digits consist of three parts: the integer part, the delimiting decimal # point, and the decimal part. var numStr = "" while pos < input.len and input[pos] in Digits: numStr.add(input[pos]) inc(pos) if pos < input.len and input[pos] == '.': numStr.add('.') inc(pos) while pos < input.len and input[pos] in Digits: numStr.add(input[pos]) inc(pos) result.add(Token(kind: tokNumber, value: numStr.parseFloat())) of '+': inc(pos); result.add(Token(kind: tokPlus)) of '-': inc(pos); result.add(Token(kind: tokMinus)) of '*': inc(pos); result.add(Token(kind: tokStar)) of '/': inc(pos); result.add(Token(kind: tokSlash)) of '(': inc(pos); result.add(Token(kind: tokLPar)) of ')': inc(pos); result.add(Token(kind: tokRPar)) of ' ': inc(pos) else: raise newException(ArithmeticError, "Unexpected character '" & input[pos] & '\'') # We append an 'end' token to the end of our token sequence, to mark where the # sequence ends. result.add(Token(kind: tokEnd))   #-- # Parser #--   type ExprKind = enum exprNumber exprBinary Expr = ref object case kind: ExprKind of exprNumber: value: float of exprBinary: left, right: Expr operator: TokenKind   proc `$`(ex: Expr): string = # This proc returns a lisp representation of the expression. case ex.kind of exprNumber: $ex.value of exprBinary: '(' & $ex.operator & ' ' & $ex.left & ' ' & $ex.right & ')'   var # The input to the program is provided via command line parameters. tokens = lex(commandLineParams().join(" ")) pos = 0   # This table stores the precedence level of each infix operator. For tokens # this does not apply to, the precedence is set to 0. const Precedence: array[low(TokenKind)..high(TokenKind), int] = [ tokNumber: 0, tokPlus: 1, tokMinus: 1, tokStar: 2, tokSlash: 2, tokLPar: 0, tokRPar: 0, tokEnd: 0 ]   # We use a Pratt parser, so the two primary components are the prefix part, and # the infix part. We start with a prefix token, and when we're done, we continue # with an infix token.   proc parse(prec = 0): Expr   proc parseNumber(token: Token): Expr = result = Expr(kind: exprNumber, value: token.value)   proc parseParen(token: Token): Expr = result = parse() if tokens[pos].kind != tokRPar: raise newException(ArithmeticError, "Unbalanced parenthesis") inc(pos)   proc parseBinary(left: Expr, token: Token): Expr = result = Expr(kind: exprBinary, left: left, right: parse(), operator: token.kind)   proc parsePrefix(token: Token): Expr = case token.kind of tokNumber: result = parseNumber(token) of tokLPar: result = parseParen(token) else: discard   proc parseInfix(left: Expr, token: Token): Expr = case token.kind of tokPlus, tokMinus, tokStar, tokSlash: result = parseBinary(left, token) else: discard   proc parse(prec = 0): Expr = # This procedure is the heart of a Pratt parser, it puts the whole expression # together into one abstract syntax tree, properly dealing with precedence. var token = tokens[pos] inc(pos) result = parsePrefix(token) while prec < Precedence[tokens[pos].kind]: token = tokens[pos] if token.kind == tokEnd: # When we hit the end token, we're done. break inc(pos) result = parseInfix(result, token)   let ast = parse()   proc `==`(ex: Expr): float = # This proc recursively evaluates the given expression. result = case ex.kind of exprNumber: ex.value of exprBinary: case ex.operator of tokPlus: ==ex.left + ==ex.right of tokMinus: ==ex.left - ==ex.right of tokStar: ==ex.left * ==ex.right of tokSlash: ==ex.left / ==ex.right else: 0.0   # In the end, we print out the result. echo ==ast
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal. E.G. 6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6. 10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value. 12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14. Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0 Task Write a routine (function, procedure, whatever) to find Zumkeller numbers. Use the routine to find and display here, on this page, the first 220 Zumkeller numbers. Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers. Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5. See Also OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions OEIS:A174865 - Odd Zumkeller numbers Related Tasks Abundant odd numbers Abundant, deficient and perfect number classifications Proper divisors , Factors of an integer
#11l
11l
F getDivisors(n) V divs = [1, n] V i = 2 L i * i <= n I n % i == 0 divs [+]= i   V j = n I/ i I i != j divs [+]= j i++ R divs   F isPartSum(divs, sum) I sum == 0 R 1B   V le = divs.len I le == 0 R 0B   V last = divs.last [Int] newDivs L(i) 0 .< le - 1 newDivs [+]= divs[i]   I last > sum R isPartSum(newDivs, sum) E R isPartSum(newDivs, sum) | isPartSum(newDivs, sum - last)   F isZumkeller(n) V divs = getDivisors(n) V s = sum(divs)   I s % 2 == 1 R 0B   I n % 2 == 1 V abundance = s - 2 * n R abundance > 0 & abundance % 2 == 0   R isPartSum(divs, s I/ 2)   print(‘The first 220 Zumkeller numbers are:’) V i = 2 V count = 0 L count < 220 I isZumkeller(i) print(‘#3 ’.format(i), end' ‘’) count++ I count % 20 == 0 print() i++   print("\nThe first 40 odd Zumkeller numbers are:") i = 3 count = 0 L count < 40 I isZumkeller(i) print(‘#5 ’.format(i), end' ‘’) count++ I count % 10 == 0 print() i += 2   print("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:") i = 3 count = 0 L count < 40 I i % 10 != 5 & isZumkeller(i) print(‘#7 ’.format(i), end' ‘’) count++ I count % 8 == 0 print() i += 2
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#C
C
<Rows> <Columns> <Blank pixel character> <Image Pixel character> <Image of specified rows and columns made up of the two pixel types specified in the second line.>
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#C.2B.2B
C++
#include <iostream> #include <string> #include <sstream> #include <valarray> const std::string input { "................................" ".#########.......########......." ".###...####.....####..####......" ".###....###.....###....###......" ".###...####.....###............." ".#########......###............." ".###.####.......###....###......" ".###..####..###.####..####.###.." ".###...####.###..########..###.." "................................" }; const std::string input2 { ".........................................................." ".#################...................#############........" ".##################...............################........" ".###################............##################........" ".########.....#######..........###################........" "...######.....#######.........#######.......######........" "...######.....#######........#######......................" "...#################.........#######......................" "...################..........#######......................" "...#################.........#######......................" "...######.....#######........#######......................" "...######.....#######........#######......................" "...######.....#######.........#######.......######........" ".########.....#######..........###################........" ".########.....#######.######....##################.######." ".########.....#######.######......################.######." ".########.....#######.######.........#############.######." ".........................................................." };   class ZhangSuen;   class Image { public: friend class ZhangSuen; using pixel_t = char; static const pixel_t BLACK_PIX; static const pixel_t WHITE_PIX;   Image(unsigned width = 1, unsigned height = 1) : width_{width}, height_{height}, data_( '\0', width_ * height_) {} Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_} {} Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)} {} ~Image() = default; Image& operator=(const Image& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = i.data_; } return *this; } Image& operator=(Image&& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = std::move(i.data_); } return *this; } size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; } bool operator()(unsigned x, unsigned y) { return data_[idx(x, y)]; } friend std::ostream& operator<<(std::ostream& o, const Image& i) { o << i.width_ << " x " << i.height_ << std::endl; size_t px = 0; for(const auto& e : i.data_) { o << (e?Image::BLACK_PIX:Image::WHITE_PIX); if (++px % i.width_ == 0) o << std::endl; } return o << std::endl; } friend std::istream& operator>>(std::istream& in, Image& img) { auto it = std::begin(img.data_); const auto end = std::end(img.data_); Image::pixel_t tmp; while(in && it != end) { in >> tmp; if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX) throw "Bad character found in image"; *it = (tmp == Image::BLACK_PIX)?1:0; ++it; } return in; } unsigned width() const noexcept { return width_; } unsigned height() const noexcept { return height_; } struct Neighbours { // 9 2 3 // 8 1 4 // 7 6 5 Neighbours(const Image& img, unsigned p1_x, unsigned p1_y) : img_{img} , p1_{img.idx(p1_x, p1_y)} , p2_{p1_ - img.width()} , p3_{p2_ + 1} , p4_{p1_ + 1} , p5_{p4_ + img.width()} , p6_{p5_ - 1} , p7_{p6_ - 1} , p8_{p1_ - 1} , p9_{p2_ - 1} {} const Image& img_; const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; } const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; } const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; } const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; } const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; } const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; } const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; } const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; } const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; } const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_; }; Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); } private: unsigned height_ { 0 }; unsigned width_ { 0 }; std::valarray<pixel_t> data_; };   constexpr const Image::pixel_t Image::BLACK_PIX = '#'; constexpr const Image::pixel_t Image::WHITE_PIX = '.';   class ZhangSuen { public:   // the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2 unsigned transitions_white_black(const Image::Neighbours& a) const { unsigned sum = 0; sum += (a.p9() == 0) && a.p2(); sum += (a.p2() == 0) && a.p3(); sum += (a.p3() == 0) && a.p4(); sum += (a.p8() == 0) && a.p9(); sum += (a.p4() == 0) && a.p5(); sum += (a.p7() == 0) && a.p8(); sum += (a.p6() == 0) && a.p7(); sum += (a.p5() == 0) && a.p6(); return sum; }   // The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) unsigned black_pixels(const Image::Neighbours& a) const { unsigned sum = 0; sum += a.p9(); sum += a.p2(); sum += a.p3(); sum += a.p8(); sum += a.p4(); sum += a.p7(); sum += a.p6(); sum += a.p5(); return sum; } const Image& operator()(const Image& img) { tmp_a_ = img; size_t changed_pixels = 0; do { changed_pixels = 0; // Step 1 tmp_b_ = tmp_a_; for(size_t y = 1; y < tmp_a_.height() - 1; ++y) { for(size_t x = 1; x < tmp_a_.width() - 1; ++x) { if (tmp_a_.data_[tmp_a_.idx(x, y)]) { auto n = tmp_a_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p6() == 0) && (n.p4() * n.p6() * n.p8() == 0) ) { tmp_b_.data_[n.p1_] = 0; ++changed_pixels; } } } } } // Step 2 tmp_a_ = tmp_b_; for(size_t y = 1; y < tmp_b_.height() - 1; ++y) { for(size_t x = 1; x < tmp_b_.width() - 1; ++x) { if (tmp_b_.data_[tmp_b_.idx(x, y)]) { auto n = tmp_b_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p8() == 0) && (n.p2() * n.p6() * n.p8() == 0) ) { tmp_a_.data_[n.p1_] = 0; ++changed_pixels; } } } } } } while(changed_pixels > 0); return tmp_a_; } private: Image tmp_a_; Image tmp_b_; };   int main(int argc, char const *argv[]) { using namespace std; Image img(32, 10); istringstream iss{input}; iss >> img; cout << img; cout << "ZhangSuen" << endl; ZhangSuen zs; Image res = std::move(zs(img)); cout << res << endl;   Image img2(58,18); istringstream iss2{input2}; iss2 >> img2; cout << img2; cout << "ZhangSuen with big image" << endl; Image res2 = std::move(zs(img2)); cout << res2 << endl; return 0; }  
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Stata
Stata
clear all scalar h=_pi/40 set obs 400 gen t=_n*h gen x=(1+t)*cos(t) gen y=(1+t)*sin(t) line y x
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.
#Tcl
Tcl
package require Tk   # create widgets canvas .canvas frame .controls   ttk::label .legend -text " r = a + b θ " ttk::label .label_a -text "a =" ttk::entry .entry_a -textvariable a ttk::label .label_b -text "a =" ttk::entry .entry_b -textvariable b button .button -text "Redraw" -command draw   # layout grid .canvas .controls -sticky nsew grid .legend - -sticky ns -in .controls grid .label_a .entry_a -sticky nsew -in .controls grid .label_b .entry_b -sticky nsew -in .controls grid .button - -sticky ns -in .controls   # make the canvas resize with the window grid columnconfigure . 0 -weight 1 grid rowconfigure . 0 -weight 1   # spiral parameters: set a .2 set b .05   proc draw {} { variable a variable b   # make sure inputs are valid: if {![string is double $a] || ![string is double $b]} return if {$a == 0 || $b == 0} return   set w [winfo width .canvas] set h [winfo height .canvas] set r 0 set pi [expr {4*atan(1)}] set step [expr {$pi / $w}] for {set t 0} {$r < 2} {set t [expr {$t + $step}]} { set r [expr {$a + $b * $t}] set y [expr {sin($t) * $r}] set x [expr {cos($t) * $r}]   # transform to canvas co-ordinates set y [expr {entier((1+$y)*$h/2)}] set x [expr {entier((1+$x)*$w/2)}] lappend coords $x $y } .canvas delete all set id [.canvas create line $coords -fill red] }   # draw whenever parameters are changed # ";#" so extra trace arguments are ignored trace add variable a write {draw;#} trace add variable b write {draw;#}   wm protocol . WM_DELETE_WINDOW exit ;# exit when window is closed   update ;# lay out widgets before trying to draw draw vwait forever ;# go into event loop until window is closed
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#C
C
#include <stdio.h>   typedef unsigned long long u64;   #define FIB_INVALID (~(u64)0)   u64 fib[] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073ULL, 4807526976ULL, 7778742049ULL, 12586269025ULL, 20365011074ULL, 32951280099ULL, 53316291173ULL, 86267571272ULL, 139583862445ULL, 225851433717ULL, 365435296162ULL, 591286729879ULL, 956722026041ULL, 1548008755920ULL, 2504730781961ULL, 4052739537881ULL, 6557470319842ULL, 10610209857723ULL, 17167680177565ULL,   27777890035288ULL // this 65-th one is for range check };   u64 fibbinary(u64 n) { if (n >= fib[64]) return FIB_INVALID;   u64 ret = 0; int i; for (i = 64; i--; ) if (n >= fib[i]) { ret |= 1ULL << i; n -= fib[i]; }   return ret; }   void bprint(u64 n, int width) { if (width > 64) width = 64;   u64 b; for (b = 1ULL << (width - 1); b; b >>= 1) putchar(b == 1 && !n ? '0' : b > n ? ' ' : b & n ? '1' : '0'); putchar('\n'); }   int main(void) { int i;   for (i = 0; i <= 20; i++) printf("%2d:", i), bprint(fibbinary(i), 8);   return 0; }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Batch_File
Batch File
  @echo off setlocal enableDelayedExpansion :: 0 = closed :: 1 = open :: SET /A treats undefined variable as 0 :: Negation operator ! must be escaped because delayed expansion is enabled for /l %%p in (1 1 100) do for /l %%d in (%%p %%p 100) do set /a "door%%d=^!door%%d" for /l %%d in (1 1 100) do if !door%%d!==1 ( echo door %%d is open ) else echo door %%d is closed  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Delphi
Delphi
  procedure TForm1.Button1Click(Sender: TObject); var StaticArray: array[1..10] of Integer; // static arrays can start at any index DynamicArray: array of Integer; // dynamic arrays always start at 0 StaticArrayText, DynamicArrayText: string; ixS, ixD: Integer; begin // Setting the length of the dynamic array the same as the static one SetLength(DynamicArray, Length(StaticArray)); // Asking random numbers storing into the static array for ixS := Low(StaticArray) to High(StaticArray) do begin StaticArray[ixS] := StrToInt( InputBox('Random number', 'Enter a random number for position', IntToStr(ixS))); end; // Storing entered numbers of the static array in reverse order into the dynamic ixD := High(DynamicArray); for ixS := Low(StaticArray) to High(StaticArray) do begin DynamicArray[ixD] := StaticArray[ixS]; Dec(ixD); end; // Concatenating the static and dynamic array into a single string variable StaticArrayText := ''; for ixS := Low(StaticArray) to High(StaticArray) do StaticArrayText := StaticArrayText + IntToStr(StaticArray[ixS]); DynamicArrayText := ''; for ixD := Low(DynamicArray) to High(DynamicArray) do DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[ixD]); end; // Displaying both arrays (#13#10 = Carriage Return/Line Feed) ShowMessage(StaticArrayText + #13#10 + DynamicArrayText); end;
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.
#Maxima
Maxima
z1: 5 + 2 * %i; 2*%i+5   z2: 3 - 7 * %i; 3-7*%i   carg(z1); atan(2/5)   cabs(z1); sqrt(29)   rectform(z1 * z2); 29-29*%i   polarform(z1); sqrt(29)*%e^(%i*atan(2/5))   conjugate(z1); 5-2*%i   z1 + z2; 8-5*%i   z1 - z2; 9*%i+2   z1 * z2; (3-7*%i)*(2*%i+5)   z1 * z2, rectform; 29-29*%i   z1 / z2; (2*%i+5)/(3-7*%i)   z1 / z2, rectform; (41*%i)/58+1/58   realpart(z1); 5   imagpart(z1); 2
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.
#.D0.9C.D0.9A-61.2F52
МК-61/52
ПA С/П ПB С/П ПC С/П ПD С/П ИПC x^2 ИПD x^2 + П3 ИПA ИПC * ИПB ИПD * + ИП3 / П1 ИПB ИПC * ИПA ИПD * - ИП3 / П2 ИП1 С/П ИПA ИПC * ИПB ИПD * - П1 ИПB ИПC * ИПA ИПD * + П2 ИП1 С/П ИПB ИПD + П2 ИПA ИПC + ИП1 С/П ИПB ИПD - П2 ИПA ИПC - П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
#Ol
Ol
  (define x 3/7) (define y 9/11) (define z -2/5)   ; demonstrate builtin functions:   (print "(abs " z ") = " (abs z)) (print "- " z " = " (- z)) (print x " + " y " = " (+ x y)) (print x " - " y " = " (- x y)) (print x " * " y " = " (* x y)) (print x " / " y " = " (/ x y)) (print x " < " y " = " (< x y)) (print x " > " y " = " (> x y))   ; introduce new functions:   (define (+:= x) (+ x 1)) (define (-:= x) (- x 1))   (print "+:= " z " = " (+:= z)) (print "-:= " z " = " (-:= z))   ; finally, find all perfect numbers less than 2^15:   (lfor-each (lambda (candidate) (let ((sum (lfold (lambda (sum factor) (if (= 0 (modulo candidate factor)) (+ sum (/ 1 factor) (/ factor candidate)) sum)) (/ 1 candidate) (liota 2 1 (+ (isqrt candidate) 1))))) (if (= 1 (denominator sum)) (print candidate (if (eq? sum 1) ", perfect" ""))))) (liota 2 1 (expt 2 15)))  
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
#Python
Python
from math import sqrt   def agm(a0, g0, tolerance=1e-10): """ Calculating the arithmetic-geometric mean of two numbers a0, g0.   tolerance the tolerance for the converged value of the arithmetic-geometric mean (default value = 1e-10) """ an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0) while abs(an - gn) > tolerance: an, gn = (an + gn) / 2.0, sqrt(an * gn) return an   print agm(1, 1 / sqrt(2))
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ temp put [ 2over 2over temp share approx= iff 2drop done 2over 2over v* temp share vsqrt drop dip [ dip [ v+ 2 n->v v/ ] ] again ] base share temp take ** round ] is agm ( n/d n/d n --> n/d )   1 n->v 2 n->v 125 vsqrt drop 1/v 125 agm 2dup 125 point$ echo$ cr cr swap say "Num: " echo cr say "Den: " echo
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Common_Lisp
Common Lisp
> (expt 0 0) 1
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Crystal
Crystal
puts "Int32: #{0_i32**0_i32}" puts "Negative Int32: #{-0_i32**-0_i32}" puts "Float32: #{0_f32**0_f32}" puts "Negative Float32: #{-0_f32**-0_f32}"
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.
#OCaml
OCaml
type expression = | Const of float | Sum of expression * expression (* e1 + e2 *) | Diff of expression * expression (* e1 - e2 *) | Prod of expression * expression (* e1 * e2 *) | Quot of expression * expression (* e1 / e2 *)   let rec eval = function | Const c -> c | Sum (f, g) -> eval f +. eval g | Diff(f, g) -> eval f -. eval g | Prod(f, g) -> eval f *. eval g | Quot(f, g) -> eval f /. eval g   open Genlex   let lexer = make_lexer ["("; ")"; "+"; "-"; "*"; "/"]   let rec parse_expr = parser [< e1 = parse_mult; e = parse_more_adds e1 >] -> e and parse_more_adds e1 = parser [< 'Kwd "+"; e2 = parse_mult; e = parse_more_adds (Sum(e1, e2)) >] -> e | [< 'Kwd "-"; e2 = parse_mult; e = parse_more_adds (Diff(e1, e2)) >] -> e | [< >] -> e1 and parse_mult = parser [< e1 = parse_simple; e = parse_more_mults e1 >] -> e and parse_more_mults e1 = parser [< 'Kwd "*"; e2 = parse_simple; e = parse_more_mults (Prod(e1, e2)) >] -> e | [< 'Kwd "/"; e2 = parse_simple; e = parse_more_mults (Quot(e1, e2)) >] -> e | [< >] -> e1 and parse_simple = parser | [< 'Int i >] -> Const(float i) | [< 'Float f >] -> Const f | [< 'Kwd "("; e = parse_expr; 'Kwd ")" >] -> e     let parse_expression = parser [< e = parse_expr; _ = Stream.empty >] -> e   let read_expression s = parse_expression(lexer(Stream.of_string s))
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal. E.G. 6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6. 10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value. 12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14. Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0 Task Write a routine (function, procedure, whatever) to find Zumkeller numbers. Use the routine to find and display here, on this page, the first 220 Zumkeller numbers. Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers. Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5. See Also OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions OEIS:A174865 - Odd Zumkeller numbers Related Tasks Abundant odd numbers Abundant, deficient and perfect number classifications Proper divisors , Factors of an integer
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program zumkellex641.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */   /* REMARK 2 : this program is not optimized. Not search First 40 odd Zumkeller numbers not divisible by 5 */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ NBDIVISORS, 100     /*******************************************/ /* Structures */ /********************************************/ /* structurea area divisors */ .struct 0 div_ident: // ident .struct div_ident + 8 div_flag: // value 0, 1 or 2 .struct div_flag + 8 div_fin: /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStartPgm: .asciz "Program start \n" szMessEndPgm: .asciz "Program normal end.\n" szMessErrorArea: .asciz "\033[31mError : area divisors too small.\n" szMessError: .asciz "\033[31mError  !!!\n"   szCarriageReturn: .asciz "\n"   /* datas message display */ szMessEntete: .asciz "The first 220 Zumkeller numbers are:\n" sNumber: .space 4*20,' ' .space 12,' ' // for end of conversion szMessListDivi: .asciz "Divisors list : \n" szMessListDiviHeap: .asciz "Heap 1 Divisors list : \n" szMessResult: .ascii " " sValue: .space 12,' ' .asciz ""   szMessEntete1: .asciz "The first 40 odd Zumkeller numbers are:\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 tbDivisors: .skip div_fin * NBDIVISORS // area divisors sZoneConv: .skip 30 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // program start ldr x0,qAdrszMessStartPgm // display start message bl affichageMess   ldr x0,qAdrszMessEntete // display message bl affichageMess mov x2,#1 // counter number mov x3,#0 // counter zumkeller number mov x4,#0 // counter for line display 1: mov x0,x2 // number mov x1,#0 // display flag bl testZumkeller cmp x0,#1 // zumkeller ? bne 3f // no mov x0,x2 ldr x1,qAdrsZoneConv // and convert ascii string bl conversion10 ldr x0,qAdrsZoneConv // copy result in display line ldr x1,qAdrsNumber lsl x5,x4,#2 add x1,x1,x5 11: ldrb w5,[x0],1 cbz w5,12f strb w5,[x1],1 b 11b 12: add x4,x4,#1 cmp x4,#20 blt 2f //add x1,x1,#3 // carriage return at end of display line mov x0,#'\n' strb w0,[x1] mov x0,#0 strb w0,[x1,#1] // end of display line ldr x0,qAdrsNumber // display result message bl affichageMess mov x4,#0 2: add x3,x3,#1 // increment counter 3: add x2,x2,#1 // increment number cmp x3,#220 // end ? blt 1b   /* raz display line */ ldr x0,qAdrsNumber mov x1,' ' mov x2,0 31: strb w1,[x0,x2] add x2,x2,1 cmp x2,4*20 blt 31b   /* odd zumkeller numbers */ ldr x0,qAdrszMessEntete1 bl affichageMess mov x2,#1 mov x3,#0 mov x4,#0 4: mov x0,x2 // number mov x1,#0 // display flag bl testZumkeller cmp x0,#1 bne 6f mov x0,x2 ldr x1,qAdrsZoneConv // and convert ascii string bl conversion10 ldr x0,qAdrsZoneConv // copy result in display line ldr x1,qAdrsNumber lsl x5,x4,#3 add x1,x1,x5 41: ldrb w5,[x0],1 cbz w5,42f strb w5,[x1],1 b 41b 42: add x4,x4,#1 cmp x4,#8 blt 5f mov x0,#'\n' strb w0,[x1] strb wzr,[x1,#1] ldr x0,qAdrsNumber // display result message bl affichageMess mov x4,#0 5: add x3,x3,#1 6: add x2,x2,#2 cmp x3,#40 blt 4b     ldr x0,qAdrszMessEndPgm // display end message bl affichageMess b 100f 99: // display error message ldr x0,qAdrszMessError bl affichageMess 100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc 0 // perform system call qAdrszMessStartPgm: .quad szMessStartPgm qAdrszMessEndPgm: .quad szMessEndPgm qAdrszMessError: .quad szMessError qAdrszCarriageReturn: .quad szCarriageReturn qAdrszMessResult: .quad szMessResult qAdrsValue: .quad sValue qAdrszMessEntete: .quad szMessEntete qAdrszMessEntete1: .quad szMessEntete1 qAdrsNumber: .quad sNumber qAdrsZoneConv: .quad sZoneConv /******************************************************************/ /* test if number is Zumkeller number */ /******************************************************************/ /* x0 contains the number */ /* x1 contains display flag (<>0: display, 0: no display ) */ /* x0 return 1 if Zumkeller number else return 0 */ testZumkeller: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers mov x7,x1 // save flag ldr x1,qAdrtbDivisors bl divisors // create area of divisors cmp x0,#0 // 0 divisors or error ? ble 98f mov x5,x0 // number of dividers mov x6,x1 // number of odd dividers cmp x7,#1 // display divisors ? bne 1f ldr x0,qAdrszMessListDivi // yes bl affichageMess mov x0,x5 mov x1,#0 ldr x2,qAdrtbDivisors bl printHeap 1: tst x6,#1 // number of odd divisors is odd ? bne 99f mov x0,x5 mov x1,#0 ldr x2,qAdrtbDivisors bl sumDivisors // compute divisors sum tst x0,#1 // sum is odd ? bne 99f // yes -> end lsr x6,x0,#1 // compute sum /2 mov x0,x6 // x0 contains sum / 2 mov x1,#1 // first heap mov x3,x5 // number divisors mov x4,#0 // N° element to start bl searchHeap cmp x0,#-2 beq 100f // end cmp x0,#-1 beq 100f // end   cmp x7,#1 // print flag ? bne 2f ldr x0,qAdrszMessListDiviHeap bl affichageMess mov x0,x5 // yes print divisors of first heap ldr x2,qAdrtbDivisors mov x1,#1 bl printHeap 2: mov x0,#1 // ok b 100f 98: mov x0,-1 b 100f 99: mov x0,#0 b 100f 100: ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrtbDivisors: .quad tbDivisors qAdrszMessListDiviHeap: .quad szMessListDiviHeap /******************************************************************/ /* search sum divisors = sum / 2 */ /******************************************************************/ /* x0 contains sum to search */ /* x1 contains flag (1 or 2) */ /* x2 contains address of divisors area */ /* x3 contains elements number */ /* x4 contains N° element to start */ /* x0 return -2 end search */ /* x0 return -1 no heap */ /* x0 return 0 Ok */ /* recursive routine */ searchHeap: stp x3,lr,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x8,[sp,-16]! // save registers 1: cmp x4,x3 // indice = elements number beq 99f lsl x6,x4,#4 // compute element address add x6,x6,x2 ldr x7,[x6,#div_flag] // flag equal ? cmp x7,#0 bne 6f ldr x5,[x6,#div_ident] cmp x5,x0 // element value = remaining amount beq 7f // yes bgt 6f // too large // too less mov x8,x0 // save sum sub x0,x0,x5 // new sum to find add x4,x4,#1 // next divisors bl searchHeap // other search cmp x0,#0 // find -> ok beq 5f mov x0,x8 // sum begin sub x4,x4,#1 // prev divisors bl razFlags // zero in all flags > current element 4: add x4,x4,#1 // last divisors b 1b 5: str x1,[x6,#div_flag] // flag -> area element flag b 100f 6: add x4,x4,#1 // last divisors b 1b 7: str x1,[x6,#div_flag] // flag -> area element flag mov x0,#0 // search ok b 100f 8: mov x0,#-1 // end search b 100f 99: mov x0,#-2 b 100f 100: ldp x6,x8,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x3,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* raz flags */ /******************************************************************/ /* x0 contains sum to search */ /* x1 contains flag (1 or 2) */ /* x2 contains address of divisors area */ /* x3 contains elements number */ /* x4 contains N° element to start */ /* x5 contains current sum */ /* REMARK  : NO SAVE REGISTERS x14 x15 x16 AND LR */ razFlags: mov x14,x4 1: cmp x14,x3 // indice > nb elements ? bge 100f // yes -> end lsl x15,x14,#4 add x15,x15,x2 // compute address element ldr x16,[x15,#div_flag] // load flag cmp x1,x16 // equal ? bne 2f str xzr,[x15,#div_flag] // yes -> store 0 2: add x14,x14,#1 // increment indice b 1b // and loop 100: ret // return to address lr x30 /******************************************************************/ /* compute sum of divisors */ /******************************************************************/ /* x0 contains elements number */ /* x1 contains flag (0 1 or 2) /* x2 contains address of divisors area /* x0 return divisors sum */ /* REMARK  : NO SAVE REGISTERS x13 x14 x15 x16 AND LR */ sumDivisors: mov x13,#0 // indice mov x16,#0 // sum 1: lsl x14,x13,#4 // N° element * 16 add x14,x14,x2 ldr x15,[x14,#div_flag] // compare flag cmp x15,x1 bne 2f ldr x15,[x14,#div_ident] // load value add x16,x16,x15 // and add 2: add x13,x13,#1 cmp x13,x0 blt 1b mov x0,x16 // return sum 100: ret // return to address lr x30 /******************************************************************/ /* print heap */ /******************************************************************/ /* x0 contains elements number */ /* x1 contains flag (0 1 or 2) */ /* x2 contains address of divisors area */ printHeap: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers stp x5,x6,[sp,-16]! // save registers stp x1,x7,[sp,-16]! // save registers mov x6,x0 mov x5,x1 mov x3,#0 // indice 1: lsl x1,x3,#4 // N° element * 16 add x1,x1,x2 ldr x4,[x1,#div_flag] cmp x4,x5 bne 2f ldr x0,[x1,#div_ident] ldr x1,qAdrsValue // and convert ascii string bl conversion10 ldr x0,qAdrszMessResult // display result message bl affichageMess 2: add x3,x3,#1 cmp x3,x6 blt 1b ldr x0,qAdrszCarriageReturn bl affichageMess 100: ldp x1,x8,[sp],16 // restaur 2 registers ldp x5,x6,[sp],16 // restaur 2 registers ldp x3,x4,[sp],16 // restaur 2 registers ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* divisors function */ /******************************************************************/ /* x0 contains the number */ /* x1 contains address of divisors area /* x0 return divisors number */ /* x1 return counter odd divisors */ /* REMARK  : NO SAVE REGISTERS x10 x11 x12 x13 x14 x15 x16 x17 x18 */ divisors: str lr,[sp,-16]! // save register LR cmp x0,#1 // = 1 ? ble 98f mov x17,x0 mov x18,x1 mov x11,#1 // counter odd divisors mov x0,#1 // first divisor = 1 str x0,[x18,#div_ident] mov x0,#0 str x0,[x18,#div_flag] tst x17,#1 // number is odd ? cinc x11,x11,ne // count odd divisors mov x0,x17 // last divisor = N add x10,x18,#16 // store at next element str x0,[x10,#div_ident] mov x0,#0 str x0,[x10,#div_flag]   mov x16,#2 // first divisor mov x15,#2 // Counter divisors 2: // begin loop udiv x12,x17,x16 msub x13,x12,x16,x17 cmp x13,#0 // remainder = 0 ? bne 3f cmp x12,x16 blt 4f // quot<divisor end lsl x10,x15,#4 // N° element * 16 add x10,x10,x18 // and add at area begin address str x12,[x10,#div_ident] str xzr,[x10,#div_flag] add x15,x15,#1 // increment counter cmp x15,#NBDIVISORS // area maxi ? bge 99f tst x12,#1 cinc x11,x11,ne // count odd divisors cmp x12,x16 // quotient = divisor ? ble 4f lsl x10,x15,#4 // N° element * 16 add x10,x10,x18 // and add at area begin address str x16,[x10,#div_ident] str xzr,[x10,#div_flag] add x15,x15,#1 // increment counter cmp x15,#NBDIVISORS // area maxi ? bge 99f tst x16,#1 cinc x11,x11,ne // count odd divisors 3: cmp x12,x16 ble 4f add x16,x16,#1 // increment divisor b 2b // and loop   4: mov x0,x15 // return divisors number mov x1,x11 // return count odd divisors b 100f 98: mov x0,0 b 100f 99: // error ldr x0,qAdrszMessErrorArea bl affichageMess mov x0,-1 100: ldr lr,[sp],16 // restaur 1 registers ret // return to address lr x30 qAdrszMessListDivi: .quad szMessListDivi qAdrszMessErrorArea: .quad szMessErrorArea /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal. E.G. 6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6. 10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value. 12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14. Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0 Task Write a routine (function, procedure, whatever) to find Zumkeller numbers. Use the routine to find and display here, on this page, the first 220 Zumkeller numbers. Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers. Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5. See Also OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions OEIS:A174865 - Odd Zumkeller numbers Related Tasks Abundant odd numbers Abundant, deficient and perfect number classifications Proper divisors , Factors of an integer
#AppleScript
AppleScript
-- Sum n's proper divisors. on aliquotSum(n) if (n < 2) then return 0 set sum to 1 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set sum to sum + limit set limit to limit - 1 end if repeat with i from 2 to limit if (n mod i is 0) then set sum to sum + i + n div i end repeat   return sum end aliquotSum   -- Return n's proper divisors. on properDivisors(n) set output to {}   if (n > 1) then set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set end of output to limit set limit to limit - 1 end if repeat with i from limit to 2 by -1 if (n mod i is 0) then set beginning of output to i set end of output to n div i end if end repeat set beginning of output to 1 end if   return output end properDivisors   -- Does a subset of the given list of numbers add up to the target value? on subsetOf:numberList sumsTo:target script o property lst : numberList property someNegatives : false   on ssp(target, i) repeat while (i > 1) set n to item i of my lst set i to i - 1 if ((n = target) or (((n < target) or (someNegatives)) and (ssp(target - n, i)))) then return true end repeat return (target = beginning of my lst) end ssp end script -- The search can be more efficient if it's known the list contains no negatives. repeat with n in o's lst if (n < 0) then set o's someNegatives to true exit repeat end if end repeat   return o's ssp(target, count o's lst) end subsetOf:sumsTo:   -- Is n a Zumkeller number? on isZumkeller(n) -- Yes if its aliquot sum is greater than or equal to it, the difference between them is even, and -- either n is odd or a subset of its proper divisors sums to half the sum of the divisors and it. -- Using aliquotSum() to get the divisor sum and then calling properDivisors() too if a list's actually -- needed is generally faster than using properDivisors() in the first place and summing the result. set sum to aliquotSum(n) return ((sum ≥ n) and ((sum - n) mod 2 = 0) and ¬ ((n mod 2 = 1) or (my subsetOf:(properDivisors(n)) sumsTo:((sum + n) div 2)))) end isZumkeller   -- Task code: -- Find and return q Zumkeller numbers, starting the search at n and continuing at the -- given interval, applying the Zumkeller test only to numbers passing the given filter. on zumkellerNumbers(q, n, interval, filter) script o property zumkellers : {} end script   set counter to 0 repeat until (counter = q) if ((filter's OK(n)) and (isZumkeller(n))) then set end of o's zumkellers to n set counter to counter + 1 end if set n to n + interval end repeat   return o's zumkellers end zumkellerNumbers   on joinText(textList, delimiter) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delimiter set txt to textList as text set AppleScript's text item delimiters to astid   return txt end joinText   on formatForDisplay(resultList, heading, resultsPerLine, separator) script o property input : resultList property output : {heading} end script   set len to (count o's input) repeat with i from 1 to len by resultsPerLine set j to i + resultsPerLine - 1 if (j > len) then set j to len set end of o's output to joinText(items i thru j of o's input, separator) end repeat   return joinText(o's output, linefeed) end formatForDisplay   on doTask(cheating) set output to {} script noFilter on OK(n) return true end OK end script set header to "1st 220 Zumkeller numbers:" set end of output to formatForDisplay(zumkellerNumbers(220, 1, 1, noFilter), header, 20, " ") set header to "1st 40 odd Zumkeller numbers:" set end of output to formatForDisplay(zumkellerNumbers(40, 1, 2, noFilter), header, 10, " ")   -- Stretch goal: set header to "1st 40 odd Zumkeller numbers not ending with 5:" script no5Multiples on OK(n) return (n mod 5 > 0) end OK end script if (cheating) then -- Knowing that the HCF of the first 203 odd Zumkellers not ending with 5 -- is 63, just check 63 and each 126th number thereafter. -- For the 204th - 907th such numbers, the HCF reduces to 21, so adjust accordingly. -- (See Horsth's comments on the Talk page.) set zumkellers to zumkellerNumbers(40, 63, 126, no5Multiples) else -- Otherwise check alternate numbers from 1. set zumkellers to zumkellerNumbers(40, 1, 2, no5Multiples) end if set end of output to formatForDisplay(zumkellers, header, 10, " ")   return joinText(output, linefeed & linefeed) end doTask   local cheating set cheating to false doTask(cheating)
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#11l
11l
V y = String(BigInt(5) ^ 4 ^ 3 ^ 2) print(‘5^4^3^2 = #....#. and has #. digits’.format(y[0.<20], y[(len)-20..], y.len))
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#D
D
import std.stdio, std.algorithm, std.string, std.functional, std.typecons, std.typetuple, bitmap;   struct BlackWhite { ubyte c; alias c this; static immutable black = typeof(this)(0), white = typeof(this)(1); }   alias Neighbours = BlackWhite[9]; alias Img = Image!BlackWhite;   /// Zhang-Suen thinning algorithm. Img zhangSuen(Img image1, Img image2) pure nothrow @safe @nogc in { assert(image1.image.all!(x => x == Img.black || x == Img.white)); assert(image1.nx == image2.nx && image1.ny == image2.ny); } out(result) { assert(result.nx == image1.nx && result.ny == image1.ny); assert(result.image.all!(x => x == Img.black || x == Img.white)); } body { /// True if inf <= x <= sup. static inInterval(T)(in T x, in T inf, in T sup) pure nothrow @safe @nogc { return x >= inf && x <= sup; }   /// Return 8-neighbours+1 of point (x,y) of given image, in order. static void neighbours(in Img I, in size_t x, in size_t y, out Neighbours n) pure nothrow @safe @nogc { n = [I[x,y-1], I[x+1,y-1], I[x+1,y], I[x+1,y+1], // P2,P3,P4,P5 I[x,y+1], I[x-1,y+1], I[x-1,y], I[x-1,y-1], // P6,P7,P8,P9 I[x,y-1]]; }   if (image1.nx < 3 || image1.ny < 3) { image2.image[] = image1.image[]; return image2; }   immutable static zeroOne = [0, 1]; //** Neighbours n; bool hasChanged; do { hasChanged = false;   foreach (immutable ab; TypeTuple!(tuple(2, 4), tuple(0, 6))) { foreach (immutable y; 1 .. image1.ny - 1) { foreach (immutable x; 1 .. image1.nx - 1) { neighbours(image1, x, y, n); if (image1[x, y] && // Cond. 0 (!n[ab[0]] || !n[4] || !n[6]) && // Cond. 4 (!n[0] || !n[2] || !n[ab[1]]) && // Cond. 3 //n[].count([0, 1]) == 1 && n[].count(zeroOne) == 1 && // Cond. 2 // n[0 .. 8].sum in iota(2, 7)) { inInterval(n[0 .. 8].sum, 2, 6)) { // Cond. 1 hasChanged = true; image2[x, y] = Img.black; } else image2[x, y] = image1[x, y]; } } image1.swap(image2); } } while (hasChanged);   return image1; }   void main() { immutable before_txt = " ##..### ##..### ##..### ##..### ##..##. ##..##. ##..##. ##..##. ##..##. ##..##. ##..##. ##..##. ######. .......";   immutable small_rc = " ................................ .#########.......########....... .###...####.....####..####...... .###....###.....###....###...... .###...####.....###............. .#########......###............. .###.####.......###....###...... .###..####..###.####..####.###.. .###...####.###..########..###.. ................................";   immutable rc = " ........................................................... .#################...................#############......... .##################...............################......... .###################............##################......... .########.....#######..........###################......... ...######.....#######.........#######.......######......... ...######.....#######........#######....................... ...#################.........#######....................... ...################..........#######....................... ...#################.........#######....................... ...######.....#######........#######....................... ...######.....#######........#######....................... ...######.....#######.........#######.......######......... .########.....#######..........###################......... .########.....#######.######....##################.######.. .########.....#######.######......################.######.. .########.....#######.######.........#############.######.. ...........................................................";   foreach (immutable txt; [before_txt, small_rc, rc]) { auto img = Img.fromText(txt); "From:".writeln; img.textualShow(/*bl=*/ '.', /*wh=*/ '#'); "\nTo thinned:".writeln; img.zhangSuen(img.dup).textualShow(/*bl=*/ '.', /*wh=*/ '#'); writeln; } }
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.
#VBA
VBA
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlXYScatter .HasLegend = False .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y End With End Sub Public Sub main() Dim x(1000) As Single, y(1000) As Single a = 1 b = 9 For i = 0 To 1000 theta = i * WorksheetFunction.Pi() / 60 r = a + b * theta x(i) = r * Cos(theta) y(i) = r * Sin(theta) Next i plot_coordinate_pairs x, y End Sub
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.
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window   class Game { static init() { Window.title = "Archimedean Spiral" __width = 400 __height = 400 Canvas.resize(__width, __height) Window.resize(__width, __height) var col = Color.red spiral(col) }   static spiral(col) { var theta = 0 while (theta < 52 * Num.pi) { var x = ((theta/Num.pi).cos * theta + __width/2).truncate var y = ((theta/Num.pi).sin * theta + __height/2).truncate Canvas.pset(x, y, col) theta = theta + 0.025 } }   static update() {}   static draw(dt) {} }
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace Zeckendorf { class Program { private static uint Fibonacci(uint n) { if (n < 2) { return n; } else { return Fibonacci(n - 1) + Fibonacci(n - 2); } }   private static string Zeckendorf(uint num) { IList<uint> fibonacciNumbers = new List<uint>(); uint fibPosition = 2;   uint currentFibonaciNum = Fibonacci(fibPosition);   do { fibonacciNumbers.Add(currentFibonaciNum); currentFibonaciNum = Fibonacci(++fibPosition); } while (currentFibonaciNum <= num);   uint temp = num; StringBuilder output = new StringBuilder();   foreach (uint item in fibonacciNumbers.Reverse()) { if (item <= temp) { output.Append("1"); temp -= item; } else { output.Append("0"); } }   return output.ToString(); }   static void Main(string[] args) { for (uint i = 1; i <= 20; i++) { string zeckendorfRepresentation = Zeckendorf(i); Console.WriteLine(string.Format("{0} : {1}", i, zeckendorfRepresentation)); }   Console.ReadKey(); } } }  
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.
#BBC_BASIC
BBC BASIC
DIM doors%(100) FOR pass% = 1 TO 100 FOR door% = pass% TO 100 STEP pass% doors%(door%) = NOT doors%(door%) NEXT door% NEXT pass% FOR door% = 1 TO 100 IF doors%(door%) PRINT "Door " ; door% " is open" NEXT door%
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)
#Diego
Diego
set_ns(rosettacode); set_base(0);   // Create a new dynamic array with length zero, variant and/or mixed datatypes add_array(myEmptyArray);   // Create a new dynamic array with length zero, of integers with no mixed datatypes add_array({int}, myIntegerArray);   // Create a new fixed-length array with length 5 add_array(myFiveArray)_len(5)_base(0); // The value base '_base(0)' is usually defaulted to zero, depends upon thing.   // Create an array with 2 members (length is 2) add_ary(myStringArray)_value(Item1,Item2); // '_array' can be shortened to '_ary'   // Assign a value to member [2] with_ary(myChangeArray)_at(2)_v(5); // '_value' can be shortened to '_v'   // Add a member to an array with the push function (defaulted at end), length increased by one [myExpandedArray]_push()_v(9); // 'with_ary(...)' can be shortened to '[...]' [myExpandedArray]_append()_v(9);   // Add a member to an array with the push function (at a location), length increased by one [myExpandedArray]_pushat(3)_v(8);   // Remove a member to an array with the pop function (defaulted at end), length reduced by one [myExpandedArray]_pop();   // Remove a member to an array with the pop function (at a location), length reduced by one [myExpandedArray]_popat(3);   // Swap a member to an array with the swap function [myExpandedArray]_swapfrom(2)_swapto(6); [myExpandedArray]_swap(2, 6);   // Rectiline a member in an array [MyCaterpillarArray]_rectilat(4)_rectilup(2); [MyCaterpillarArray]_rectilup(4, 2); [MyCaterpillarArray]_rectilat(5)_rectildown(3); [MyCaterpillarArray]_rectildown(5, 3);   // Null a member to an array with the pluck function (defaulted at end) [myExpandedArray]_pluck();   // Null a member to an array with the pluck function (at a location) [myExpandedArray]_pluckat(3);   // Get size of array [mySizableArray]_size(); // '_len()' can also be used [myMultidimensialArray]_size()   // Retrieve an element of an array [myArray]_at(3); [myArray]_first(); // Retrieve first element in an array [myArray]_last(); // Retrieve last element in an array   // More transformations of arrays (like append, union, intersection) are available   // For multi-dimensional array use the 'matrix' object   set_matrixorder(row-major); // set major order as row- or column-major order depends on the thing set_handrule(right); // set hand-rule, most things will use right hand-rule   // Create a new dynamic two-dimensional array with length zero, variant and/or mixed datatypes add_matrix(myMatrix)_dim(2);   // Create a new dynamic three-dimensional array with length zero, of integers with no mixed datatypes add_matrix({int}, my3DEmptyMatrix)_dim(3);   // Convert an array to a matrix by adding a new dimension with length zero, variant and/or mixed datatypes with_array(MyConvertedArray)_dim(); // Should now use '_matrix' object rather than '_array' with_array(MyConvertedArray)_dim(3); // Add three dimensions to array, should now use '_matrix' object rather than '_array'   // Create a new fixed-length traditional (2D) matrix with 5 rows and 4 columns add_matrix(myMatrix)_rows(5)_columns(4); add_matirx(myMatrix)_subs(5, 4); // check or set major order first   // Create a new fixed-length mutil-dimensional matrix with 5 rows, 4 columns, 6 subscripts, and 8 subscripts add_matrix(myMatrix)_rows(5)_columns(4)_subs(6)_subs(8); add_mat(myMatrix)_subs(5, 4, 6, 8); // check or set major order first, '_matrix' can be shortened to 'mat'   // Create a 4 x 4 identiy matrix: add_mat(myIdentityMatrix)_subs(4, 4)_identity; // ...or...   add_mat(myMorphedMatrix)_subs(4, 4) with_mat(myMorphedMatrix)_trans(morph)_identity(); // More transformations available   // Assign a value to member [2,4] with_mat(myMatrix)_row(2)_col(4)_value(5); // ...or... with_mat(myMatrix)_at(2, 4)_v(5); // check or set major order first   // Add a member(s) to a matrix using push functions is available // Remove a member(s) from a matrix with the pop functions is available // Swap a member(s) in a matrix with the swap functions is available   // Rectiline a single member in a three-dimensional matrix [MyWobbleMatrix]_rectilat()_row(3)_col(3)_sub(3)_rectilto()_row(-1)_col(1)_sub(0); // ...or... [MyWobbleMatrix]_rectilat(3, 3, 3)_rectilto(-1, 1, 0); // check or set major order first, ...or... [MyWobbleMatrix]_rectilat(3, 3, 3)_rectilleft(1)_rectilup(1); / check or set hand-rule, ...or...   // Also 'crab', 'elevate', 'slide' and 'pump' movements are available // Also 'row', 'pitch', and 'yaw' movements are available // Also, quaternions calculations are available // Null a member in a matrix using pluck functions is available   // Get size of a matrix mat(mySizableMatrix)_size(); // will return an array of the size() [myMultidimensialArray]_len(); // '_len()' can also be used   // Retrieve an element of a matrix [myMatrix]_at(3, 2); [myArray]_first()_atsub(2); // Retrieve first element of a row/column/subscript of a matrix [myArray]_last()_atsub(2); // Retrieve last element of a row/column/subscript of a matrix [myArray]_origin(); // Retrieve first element in a matrix [myArray]_end(); // Retrieve last element in a matrix   reset_ns[];
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.
#Modula-2
Modula-2
MODULE complex;   IMPORT InOut;   TYPE Complex = RECORD R, Im : REAL END;   VAR z : ARRAY [0..3] OF Complex;   PROCEDURE ShowComplex (str : ARRAY OF CHAR; p : Complex);   BEGIN InOut.WriteString (str); InOut.WriteString (" = "); InOut.WriteReal (p.R, 6, 2); IF p.Im >= 0.0 THEN InOut.WriteString (" + ") ELSE InOut.WriteString (" - ") END; InOut.WriteReal (ABS (p.Im), 6, 2); InOut.WriteString (" i "); InOut.WriteLn; InOut.WriteBf END ShowComplex;   PROCEDURE AddComplex (x1, x2 : Complex; VAR x3 : Complex);   BEGIN x3.R := x1.R + x2.R; x3.Im := x1.Im + x2.Im END AddComplex;   PROCEDURE SubComplex (x1, x2 : Complex; VAR x3 : Complex);   BEGIN x3.R := x1.R - x2.R; x3.Im := x1.Im - x2.Im END SubComplex;   PROCEDURE MulComplex (x1, x2 : Complex; VAR x3 : Complex);   BEGIN x3.R := x1.R * x2.R - x1.Im * x2.Im; x3.Im := x1.R * x2.Im + x1.Im * x2.R END MulComplex;   PROCEDURE InvComplex (x1 : Complex; VAR x2 : Complex);   BEGIN x2.R := x1.R / (x1.R * x1.R + x1.Im * x1.Im); x2.Im := -1.0 * x1.Im / (x1.R * x1.R + x1.Im * x1.Im) END InvComplex;   PROCEDURE NegComplex (x1 : Complex; VAR x2 : Complex);   BEGIN x2.R := - x1.R; x2.Im := - x1.Im END NegComplex;   BEGIN InOut.WriteString ("Enter two complex numbers : "); InOut.WriteBf; InOut.ReadReal (z[0].R); InOut.ReadReal (z[0].Im); InOut.ReadReal (z[1].R); InOut.ReadReal (z[1].Im); ShowComplex ("z1", z[0]); ShowComplex ("z2", z[1]); InOut.WriteLn; AddComplex (z[0], z[1], z[2]); ShowComplex ("z1 + z2", z[2]); SubComplex (z[0], z[1], z[2]); ShowComplex ("z1 - z2", z[2]); MulComplex (z[0], z[1], z[2]); ShowComplex ("z1 * z2", z[2]); InvComplex (z[0], z[2]); ShowComplex ("1 / z1", z[2]); NegComplex (z[0], z[2]); ShowComplex (" - z1", z[2]); InOut.WriteLn END complex.
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
#ooRexx
ooRexx
  loop candidate = 6 to 2**19 sum = .fraction~new(1, candidate) max2 = rxcalcsqrt(candidate)~trunc   loop factor = 2 to max2 if candidate // factor == 0 then do sum += .fraction~new(1, factor) sum += .fraction~new(1, candidate / factor) end end if sum == 1 then say candidate "is a perfect number" end   ::class fraction inherit orderable ::method init expose numerator denominator use strict arg numerator, denominator = 1   if denominator == 0 then raise syntax 98.900 array("Fraction denominator cannot be zero")   -- if the denominator is negative, make the numerator carry the sign if denominator < 0 then do numerator = -numerator denominator = - denominator end     -- find the greatest common denominator and reduce to -- the simplest form gcd = self~gcd(numerator~abs, denominator~abs)   numerator /= gcd denominator /= gcd   -- fraction instances are immutable, so these are -- read only attributes ::attribute numerator GET ::attribute denominator GET   -- calculate the greatest common denominator of a numerator/denominator pair ::method gcd private use arg x, y   loop while y \= 0 -- check if they divide evenly temp = x // y x = y y = temp end return x   -- calculate the least common multiple of a numerator/denominator pair ::method lcm private use arg x, y return x / self~gcd(x, y) * y   ::method abs expose numerator denominator -- the denominator is always forced to be positive return self~class~new(numerator~abs, denominator)   ::method reciprocal expose numerator denominator return self~class~new(denominator, numerator)   -- convert a fraction to regular Rexx number ::method toNumber expose numerator denominator   if numerator == 0 then return 0 return numerator/denominator   ::method negative expose numerator denominator return self~class~new(-numerator, denominator)   ::method add expose numerator denominator use strict arg other -- convert to a fraction if a regular number if \other~isa(.fraction) then other = self~class~new(other, 1)   multiple = self~lcm(denominator, other~denominator) newa = numerator * multiple / denominator newb = other~numerator * multiple / other~denominator return self~class~new(newa + newb, multiple)   ::method subtract use strict arg other return self + (-other)   ::method times expose numerator denominator use strict arg other -- convert to a fraction if a regular number if \other~isa(.fraction) then other = self~class~new(other, 1) return self~class~new(numerator * other~numerator, denominator * other~denominator)   ::method divide use strict arg other -- convert to a fraction if a regular number if \other~isa(.fraction) then other = self~class~new(other, 1) -- and multiply by the reciprocal return self * other~reciprocal   -- compareTo method used by the orderable interface to implement -- the operator methods ::method compareTo expose numerator denominator -- convert to a fraction if a regular number if \other~isa(.fraction) then other = self~class~new(other, 1)   return (numerator * other~denominator - denominator * other~numerator)~sign   -- we still override "==" and "\==" because we want to bypass the -- checks for not being an instance of the class ::method "==" expose numerator denominator use strict arg other   -- convert to a fraction if a regular number if \other~isa(.fraction) then other = self~class~new(other, 1) -- Note: these are numeric comparisons, so we're using the "=" -- method so those are handled correctly return numerator = other~numerator & denominator = other~denominator   ::method "\==" use strict arg other return \self~"\=="(other)   -- some operator overrides -- these only work if the left-hand-side of the -- subexpression is a quaternion ::method "*" forward message("TIMES")   ::method "/" forward message("DIVIDE")   ::method "-" -- need to check if this is a prefix minus or a subtract if arg() == 0 then forward message("NEGATIVE") else forward message("SUBTRACT")   ::method "+" -- need to check if this is a prefix plus or an addition if arg() == 0 then return self -- we can return this copy since it is imutable else forward message("ADD")   ::method string expose numerator denominator if denominator == 1 then return numerator return numerator"/"denominator   -- override hashcode for collection class hash uses ::method hashCode expose numerator denominator return numerator~hashcode~bitxor(numerator~hashcode)   ::requires rxmath library  
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
#R
R
arithmeticMean <- function(a, b) { (a + b)/2 } geometricMean <- function(a, b) { sqrt(a * b) }   arithmeticGeometricMean <- function(a, b) { rel_error <- abs(a - b) / pmax(a, b) if (all(rel_error < .Machine$double.eps, na.rm=TRUE)) { agm <- a return(data.frame(agm, rel_error)); } Recall(arithmeticMean(a, b), geometricMean(a, b)) }   agm <- arithmeticGeometricMean(1, 1/sqrt(2)) print(format(agm, digits=16))
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
#Racket
Racket
  #lang racket (define (agm a g [ε 1e-15]) (if (<= (- a g) ε) a (agm (/ (+ a g) 2) (sqrt (* a g)) ε)))   (agm 1 (/ 1 (sqrt 2)))  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#D
D
void main() { import std.stdio, std.math, std.bigint, std.complex;   writeln("Int: ", 0 ^^ 0); writeln("Ulong: ", 0UL ^^ 0UL); writeln("Float: ", 0.0f ^^ 0.0f); writeln("Double: ", 0.0 ^^ 0.0); writeln("Real: ", 0.0L ^^ 0.0L); writeln("pow: ", pow(0, 0)); writeln("BigInt: ", 0.BigInt ^^ 0); writeln("Complex: ", complex(0.0, 0.0) ^^ 0); }
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Dc
Dc
0 0^p  
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.
#ooRexx
ooRexx
  expressions = .array~of("2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25") loop input over expressions expression = createExpression(input) if expression \= .nil then say 'Expression "'input'" parses to "'expression~string'" and evaluates to "'expression~evaluate'"' end     -- create an executable expression from the input, printing out any -- errors if they are raised. ::routine createExpression use arg inputString -- signal on syntax return .ExpressionParser~parseExpression(inputString)   syntax: condition = condition('o') say condition~errorText say condition~message return .nil     -- a base class for tree nodes in the tree -- all nodes return some sort of value. This can be constant, -- or the result of additional evaluations ::class evaluatornode -- all evaluation is done here ::method evaluate abstract   -- node for numeric values in the tree ::class constant ::method init expose value use arg value   ::method evaluate expose value return value   ::method string expose value return value   -- node for a parenthetical group on the tree ::class parens ::method init expose subexpression use arg subexpression   ::method evaluate expose subexpression return subexpression~evaluate   ::method string expose subexpression return "("subexpression~string")"   -- base class for binary operators ::class binaryoperator ::method init expose left right -- the left and right sides are set after the left and right sides have -- been resolved. left = .nil right = .nil   -- base operation ::method evaluate expose left right return self~operation(left~evaluate, right~evaluate)   -- the actual operation of the node ::method operation abstract ::method symbol abstract ::method precedence abstract   -- display an operator as a string value ::method string expose left right return '('left~string self~symbol right~string')'   ::attribute left ::attribute right   ::class addoperator subclass binaryoperator ::method operation use arg left, right return left + right   ::method symbol return "+"   ::method precedence return 1   ::class subtractoperator subclass binaryoperator ::method operation use arg left, right return left - right   ::method symbol return "-"   ::method precedence return 1   ::class multiplyoperator subclass binaryoperator ::method operation use arg left, right return left * right   ::method symbol return "*"   ::method precedence return 2   ::class divideoperator subclass binaryoperator ::method operation use arg left, right return left / right   ::method symbol return "/"   ::method precedence return 2   -- a class to parse the expression and build an evaluation tree ::class expressionParser -- create a resolved operand from an operator instance and the top -- two entries on the operand stack. ::method createNewOperand class use strict arg operator, operands -- the operands are a stack, so they are in inverse order current operator~right = operands~pull operator~left = operands~pull -- this goes on the top of the stack now operands~push(operator)   ::method parseExpression class use strict arg inputString -- stacks for managing the operands and pending operators operands = .queue~new operators = .queue~new -- this flags what sort of item we expect to find at the current -- location afterOperand = .false   loop currentIndex = 1 to inputString~length char = inputString~subChar(currentIndex) -- skip over whitespace if char == ' ' then iterate currentIndex -- If the last thing we parsed was an operand, then -- we expect to see either a closing paren or an -- operator to appear here if afterOperand then do if char == ')' then do loop while \operators~isempty operator = operators~pull -- if we find the opening paren, replace the -- top operand with a paren group wrapper -- and stop popping items if operator == '(' then do operands~push(.parens~new(operands~pull)) leave end -- collapse the operator stack a bit self~createNewOperand(operator, operands) end -- done with this character iterate currentIndex end afterOperand = .false operator = .nil if char == "+" then operator = .addoperator~new else if char == "-" then operator = .subtractoperator~new else if char == "*" then operator = .multiplyoperator~new else if char == "/" then operator = .divideoperator~new if operator \= .nil then do loop while \operators~isEmpty top = operators~peek -- start of a paren group stops the popping if top == '(' then leave -- or the top operator has a lower precedence if top~precedence < operator~precedence then leave -- process this pending one self~createNewOperand(operators~pull, operands) end -- this new operator is now top of the stack operators~push(operator) -- and back to the top iterate currentIndex end raise syntax 98.900 array("Invalid expression character" char) end -- if we've hit an open paren, add this to the operator stack -- as a phony operator if char == '(' then do operators~push('(') iterate currentIndex end -- not an operator, so we have an operand of some type afterOperand = .true startindex = currentIndex -- allow a leading minus sign on this if inputString~subchar(currentIndex) == '-' then currentIndex += 1 -- now scan for the end of numbers loop while currentIndex <= inputString~length -- exit for any non-numeric value if \inputString~matchChar(currentIndex, "0123456789.") then leave currentIndex += 1 end -- extract the string value operand = inputString~substr(startIndex, currentIndex - startIndex) if \operand~datatype('Number') then raise syntax 98.900 array("Invalid numeric operand '"operand"'") -- back this up to the last valid character currentIndex -= 1 -- add this to the operand stack as a tree element that returns a constant operands~push(.constant~new(operand)) end   loop while \operators~isEmpty operator = operators~pull if operator == '(' then raise syntax 98.900 array("Missing closing ')' in expression") self~createNewOperand(operator, operands) end -- our entire expression should be the top of the expression tree expression = operands~pull if \operands~isEmpty then raise syntax 98.900 array("Invalid expression") return expression  
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case. Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100; Subtraction 10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg: abcde 10100 - 1000 _____ 100 borrow 1 from a leaves 100 + 100 add the carry _____ 1001 A larger example: abcdef 100100 - 1000 ______ 1*0100 borrow 1 from b + 100 add the carry ______ 1*1001 Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a: 1001 + 1000 add the carry ____ 10100 Multiplication Here you teach your computer its zeckendorf tables. eg. 101 * 1001: a = 1 * 101 = 101 b = 10 * 101 = a + a = 10000 c = 100 * 101 = b + a = 10101 d = 1000 * 101 = c + b = 101010 1001 = d + a therefore 101 * 1001 = 101010 + 101 ______ 1000100 Division Lets try 1000101 divided by 101, so we can use the same table used for multiplication. 1000101 - 101010 subtract d (1000 * 101) _______ 1000 - 101 b and c are too large to subtract, so subtract a ____ 1 so 1000101 divided by 101 is d + a (1001) remainder 1 Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
#11l
11l
T Zeckendorf Int dLen dVal = 0   F (x = ‘0’) V q = 1 V i = x.len - 1 .dLen = i I/ 2 L i >= 0 .dVal = .dVal + (x[i].code - ‘0’.code) * q q = q * 2 i = i - 1   F a(n) V i = n L I .dLen < i .dLen = i V j = (.dVal >> (i * 2)) [&] 3 I j == 0 | j == 1 R I j == 2 I (.dVal >> ((i + 1) * 2) [&] 1) != 1 R .dVal = .dVal + (1 << (i * 2 + 1)) R I j == 3 V temp = 3 << (i * 2) temp = temp (+) -1 .dVal = .dVal [&] temp .b((i + 1) * 2) i = i + 1   F b(pos) I pos == 0 .inc() R I (.dVal >> pos) [&] 1 == 0 .dVal = .dVal + (1 << pos) .a(Int(pos / 2)) I pos > 1 .a(Int(pos / 2) - 1) E V temp = 1 << pos temp = temp (+) -1 .dVal = .dVal [&] temp .b(pos + 1) .b(pos - (I pos > 1 {2} E 1))   F c(pos) I (.dVal >> pos) [&] 1 == 1 V temp = 1 << pos temp = temp (+) -1 .dVal = .dVal [&] temp R .c(pos + 1) I pos > 0 .b(pos - 1) E .inc()   F inc() -> N .dVal = .dVal + 1 .a(0)   F +(rhs) V copy = (.) V rhs_dVal = rhs.dVal V limit = (rhs.dLen + 1) * 2 L(gn) 0 .< limit I ((rhs_dVal >> gn) [&] 1) == 1 copy.b(gn) R copy   F -(rhs) V copy = (.) V rhs_dVal = rhs.dVal V limit = (rhs.dLen + 1) * 2 L(gn) 0 .< limit I (rhs_dVal >> gn) [&] 1 == 1 copy.c(gn) L (((copy.dVal >> ((copy.dLen * 2) [&] 31)) [&] 3) == 0) | (copy.dLen == 0) copy.dLen = copy.dLen - 1 R copy   F *(rhs) V na = copy(rhs) V nb = copy(rhs) V nr = Zeckendorf() V dVal = .dVal L(i) 0 .< (.dLen + 1) * 2 I ((dVal >> i) [&] 1) > 0 nr = nr + nb V nt = copy(nb) nb = nb + na na = copy(nt) R nr   F String() V dig = [‘00’, ‘01’, ‘10’] V dig1 = [‘’, ‘1’, ‘10’]   I .dVal == 0 R ‘0’ V idx = (.dVal >> ((.dLen * 2) [&] 31)) [&] 3 String sb = dig1[idx] V i = .dLen - 1 L i >= 0 idx = (.dVal >> (i * 2)) [&] 3 sb ‘’= dig[idx] i = i - 1 R sb   print(‘Addition:’) V g = Zeckendorf(‘10’) g = g + Zeckendorf(‘10’) print(g) g = g + Zeckendorf(‘10’) print(g) g = g + Zeckendorf(‘1001’) print(g) g = g + Zeckendorf(‘1000’) print(g) g = g + Zeckendorf(‘10101’) print(g) print()   print(‘Subtraction:’) g = Zeckendorf(‘1000’) g = g - Zeckendorf(‘101’) print(g) g = Zeckendorf(‘10101010’) g = g - Zeckendorf(‘1010101’) print(g) print()   print(‘Multiplication:’) g = Zeckendorf(‘1001’) g = g * Zeckendorf(‘101’) print(g) g = Zeckendorf(‘101010’) g = g + Zeckendorf(‘101’) print(g)
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal. E.G. 6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6. 10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value. 12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14. Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0 Task Write a routine (function, procedure, whatever) to find Zumkeller numbers. Use the routine to find and display here, on this page, the first 220 Zumkeller numbers. Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers. Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5. See Also OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions OEIS:A174865 - Odd Zumkeller numbers Related Tasks Abundant odd numbers Abundant, deficient and perfect number classifications Proper divisors , Factors of an integer
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program zumkeller4.s */ /* new version 10/2020 */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   .equ NBDIVISORS, 1000   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStartPgm: .asciz "Program start \n" szMessEndPgm: .asciz "Program normal end.\n" szMessErrorArea: .asciz "\033[31mError : area divisors too small.\n" szMessError: .asciz "\033[31mError  !!!\n" szMessErrGen: .asciz "Error end program.\n" szMessNbPrem: .asciz "This number is prime !!!.\n" szMessResultFact: .asciz "@ "   szCarriageReturn: .asciz "\n"   /* datas message display */ szMessEntete: .asciz "The first 220 Zumkeller numbers are:\n" sNumber: .space 4*20,' ' .space 12,' ' @ for end of conversion szMessListDivi: .asciz "Divisors list : \n" szMessListDiviHeap: .asciz "Heap 1 Divisors list : \n" szMessResult: .ascii " " sValue: .space 12,' ' .asciz ""   szMessEntete1: .asciz "The first 40 odd Zumkeller numbers are:\n" szMessEntete2: .asciz "First 40 odd Zumkeller numbers not divisible by 5:\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 sZoneConv: .skip 24 tbZoneDecom: .skip 8 * NBDIVISORS // facteur 4 octets, nombre 4 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: @ program start ldr r0,iAdrszMessStartPgm @ display start message bl affichageMess   ldr r0,iAdrszMessEntete @ display result message bl affichageMess mov r2,#1 mov r3,#0 mov r4,#0 1: mov r0,r2 @ number bl testZumkeller cmp r0,#1 bne 3f mov r0,r2 ldr r1,iAdrsNumber @ and convert ascii string lsl r5,r4,#2 add r1,r5 bl conversion10 add r4,r4,#1 cmp r4,#20 blt 2f add r1,r1,#3 mov r0,#'\n' strb r0,[r1] mov r0,#0 strb r0,[r1,#1] ldr r0,iAdrsNumber @ display result message bl affichageMess mov r4,#0 2: add r3,r3,#1 3: add r2,r2,#1 cmp r3,#220 blt 1b   /* odd zumkeller numbers */ ldr r0,iAdrszMessEntete1 bl affichageMess mov r2,#1 mov r3,#0 mov r4,#0 4: mov r0,r2 @ number bl testZumkeller cmp r0,#1 bne 6f mov r0,r2 ldr r1,iAdrsNumber @ and convert ascii string lsl r5,r4,#3 add r1,r5 bl conversion10 add r4,r4,#1 cmp r4,#8 blt 5f add r1,r1,#8 mov r0,#'\n' strb r0,[r1] mov r0,#0 strb r0,[r1,#1] ldr r0,iAdrsNumber @ display result message bl affichageMess mov r4,#0 5: add r3,r3,#1 6: add r2,r2,#2 cmp r3,#40 blt 4b /* odd zumkeller numbers not multiple5 */ 61: ldr r0,iAdrszMessEntete2 bl affichageMess mov r3,#0 mov r4,#0 7: lsr r8,r2,#3 @ divide counter by 5 add r8,r8,r2,lsr #4 add r8,r8,r8,lsr #4 add r8,r8,r8,lsr #8 add r8,r8,r8,lsr #16 add r9,r8,r8,lsl #2 @ multiply result by 5 sub r9,r2,r9 mov r6,#13 mul r9,r6,r9 lsr r9,#6 add r9,r8 @ it is a quotient add r9,r9,r9,lsl #2 @ multiply by 5 sub r9,r2,r9 @ compute remainder cmp r9,#0 @ remainder = zero ? beq 9f mov r0,r2 @ number bl testZumkeller cmp r0,#1 bne 9f mov r0,r2 ldr r1,iAdrsNumber @ and convert ascii string lsl r5,r4,#3 add r1,r5 bl conversion10 add r4,r4,#1 cmp r4,#8 blt 8f add r1,r1,#8 mov r0,#'\n' strb r0,[r1] mov r0,#0 strb r0,[r1,#1] ldr r0,iAdrsNumber @ display result message bl affichageMess mov r4,#0 8: add r3,r3,#1 9: add r2,r2,#2 cmp r3,#40 blt 7b   ldr r0,iAdrszMessEndPgm @ display end message bl affichageMess b 100f 99: @ display error message ldr r0,iAdrszMessError bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc 0 @ perform system call iAdrszMessStartPgm: .int szMessStartPgm iAdrszMessEndPgm: .int szMessEndPgm iAdrszMessError: .int szMessError iAdrszCarriageReturn: .int szCarriageReturn iAdrszMessResult: .int szMessResult iAdrsValue: .int sValue iAdrtbZoneDecom: .int tbZoneDecom iAdrszMessEntete: .int szMessEntete iAdrszMessEntete1: .int szMessEntete1 iAdrszMessEntete2: .int szMessEntete2 iAdrsNumber: .int sNumber   /******************************************************************/ /* test if number is Zumkeller number */ /******************************************************************/ /* r0 contains the number */ /* r0 return 1 if Zumkeller number else return 0 */ testZumkeller: push {r1-r6,lr} @ save registers mov r6,r0 @ save number ldr r1,iAdrtbZoneDecom bl decompFact @ create area of divisors cmp r0,#1 @ no divisors movle r0,#0 ble 100f tst r2,#1 @ odd sum ? movne r0,#0 bne 100f @ yes -> end tst r1,#1 @ number of odd divisors is odd ? movne r0,#0 bne 100f @ yes -> end lsl r5,r6,#1 @ abondant number cmp r5,r2 movgt r0,#0 bgt 100f @ no -> end mov r3,r0 mov r4,r2 @ save sum ldr r0,iAdrtbZoneDecom mov r1,#0 mov r2,r3 bl shellSort @ sort table   mov r1,r3 @ factors number ldr r0,iAdrtbZoneDecom lsr r2,r4,#1 @ sum / 2 bl computePartIter @   100: pop {r1-r6,lr} @ restaur registers bx lr @ return   /******************************************************************/ /* search factors to sum = entry value */ /******************************************************************/ /* r0 contains address of divisors area */ /* r1 contains elements number */ /* r2 contains divisors sum / 2 */ /* r0 return 1 if ok 0 else */ computePartIter: push {r1-r7,fp,lr} @ save registers lsl r7,r1,#3 @ compute size of temp table sub sp,r7 @ and reserve on stack mov fp,sp @ frame pointer = stack address = begin table mov r5,#0 @ stack indice sub r3,r1,#1 1: ldr r4,[r0,r3,lsl #2] @ load factor cmp r4,r2 @ compare value bgt 2f beq 90f @ equal -> end ok cmp r3,#0 @ first item ? beq 3f sub r3,#1 @ push indice item in temp table add r6,fp,r5,lsl #3 str r3,[r6] str r2,[r6,#4] @ push sum in temp table add r5,#1 sub r2,r4 @ substract divisors from sum b 1b 2: sub r3,#1 @ other divisors cmp r3,#0 @ first item ? bge 1b 3: @ first item cmp r5,#0 @ stack empty ? moveq r0,#0 @ no sum factors equal to value beq 100f @ end sub r5,#1 @ else pop stack add r6,fp,r5,lsl #3 @ and restaur ldr r3,[r6] @ indice ldr r2,[r6,#4] @ and value b 1b @ and loop   90: mov r0,#1 @ it is ok 100: add sp,r7 @ stack alignement pop {r1-r7,fp,lr} @ restaur registers bx lr @ return   /******************************************************************/ /* factor decomposition */ /******************************************************************/ /* r0 contains number */ /* r1 contains address of divisors area */ /* r0 return divisors items in table */ /* r1 return the number of odd divisors */ /* r2 return the sum of divisors */ decompFact: push {r3-r8,lr} @ save registers mov r5,r1 mov r8,r0 @ save number bl isPrime @ prime ? cmp r0,#1 beq 98f @ yes is prime mov r1,#1 str r1,[r5] @ first factor mov r12,#1 @ divisors sum mov r11,#1 @ number odd divisors mov r4,#1 @ indice divisors table mov r1,#2 @ first divisor mov r6,#0 @ previous divisor mov r7,#0 @ number of same divisors 2: mov r0,r8 @ dividende bl division @ r1 divisor r2 quotient r3 remainder cmp r3,#0 bne 5f @ if remainder <> zero -> no divisor mov r8,r2 @ else quotient -> new dividende cmp r1,r6 @ same divisor ? beq 4f @ yes mov r7,r4 @ number factors in table mov r9,#0 @ indice 21: ldr r10,[r5,r9,lsl #2 ] @ load one factor mul r10,r1,r10 @ multiply str r10,[r5,r7,lsl #2] @ and store in the table tst r10,#1 @ divisor odd ? addne r11,#1 add r12,r10 add r7,r7,#1 @ and increment counter add r9,r9,#1 cmp r9,r4 blt 21b mov r4,r7 mov r6,r1 @ new divisor b 7f 4: @ same divisor sub r9,r4,#1 mov r7,r4 41: ldr r10,[r5,r9,lsl #2 ] cmp r10,r1 subne r9,#1 bne 41b sub r9,r4,r9 42: ldr r10,[r5,r9,lsl #2 ] mul r10,r1,r10 str r10,[r5,r7,lsl #2] @ and store in the table tst r10,#1 @ divsor odd ? addne r11,#1 add r12,r10 add r7,r7,#1 @ and increment counter add r9,r9,#1 cmp r9,r4 blt 42b mov r4,r7 b 7f @ and loop   /* not divisor -> increment next divisor */ 5: cmp r1,#2 @ if divisor = 2 -> add 1 addeq r1,#1 addne r1,#2 @ else add 2 b 2b   /* divisor -> test if new dividende is prime */ 7: mov r3,r1 @ save divisor cmp r8,#1 @ dividende = 1 ? -> end beq 10f mov r0,r8 @ new dividende is prime ? mov r1,#0 bl isPrime @ the new dividende is prime ? cmp r0,#1 bne 10f @ the new dividende is not prime   cmp r8,r6 @ else dividende is same divisor ? beq 9f @ yes mov r7,r4 @ number factors in table mov r9,#0 @ indice 71: ldr r10,[r5,r9,lsl #2 ] @ load one factor mul r10,r8,r10 @ multiply str r10,[r5,r7,lsl #2] @ and store in the table tst r10,#1 @ divsor odd ? addne r11,#1 add r12,r10 add r7,r7,#1 @ and increment counter add r9,r9,#1 cmp r9,r4 blt 71b mov r4,r7 mov r7,#0 b 11f 9: sub r9,r4,#1 mov r7,r4 91: ldr r10,[r5,r9,lsl #2 ] cmp r10,r8 subne r9,#1 bne 91b sub r9,r4,r9 92: ldr r10,[r5,r9,lsl #2 ] mul r10,r8,r10 str r10,[r5,r7,lsl #2] @ and store in the table tst r10,#1 @ divisor odd ? addne r11,#1 add r12,r10 add r7,r7,#1 @ and increment counter add r9,r9,#1 cmp r9,r4 blt 92b mov r4,r7 b 11f   10: mov r1,r3 @ current divisor = new divisor cmp r1,r8 @ current divisor > new dividende ? ble 2b @ no -> loop   /* end decomposition */ 11: mov r0,r4 @ return number of table items mov r2,r12 @ return sum mov r1,r11 @ return number of odd divisor mov r3,#0 str r3,[r5,r4,lsl #2] @ store zéro in last table item b 100f     98: //ldr r0,iAdrszMessNbPrem //bl affichageMess mov r0,#1 @ return code b 100f 99: ldr r0,iAdrszMessError bl affichageMess mov r0,#-1 @ error code b 100f 100: pop {r3-r8,lr} @ restaur registers bx lr iAdrszMessNbPrem: .int szMessNbPrem /***************************************************/ /* check if a number is prime */ /***************************************************/ /* r0 contains the number */ /* r0 return 1 if prime 0 else */ @2147483647 @4294967297 @131071 isPrime: push {r1-r6,lr} @ save registers cmp r0,#0 beq 90f cmp r0,#17 bhi 1f cmp r0,#3 bls 80f @ for 1,2,3 return prime cmp r0,#5 beq 80f @ for 5 return prime cmp r0,#7 beq 80f @ for 7 return prime cmp r0,#11 beq 80f @ for 11 return prime cmp r0,#13 beq 80f @ for 13 return prime cmp r0,#17 beq 80f @ for 17 return prime 1: tst r0,#1 @ even ? beq 90f @ yes -> not prime mov r2,r0 @ save number sub r1,r0,#1 @ exposant n - 1 mov r0,#3 @ base bl moduloPuR32 @ compute base power n - 1 modulo n cmp r0,#1 bne 90f @ if <> 1 -> not prime   mov r0,#5 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#7 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#11 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#13 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#17 bl moduloPuR32 cmp r0,#1 bne 90f 80: mov r0,#1 @ is prime b 100f 90: mov r0,#0 @ no prime 100: @ fin standard de la fonction pop {r1-r6,lr} @ restaur des registres bx lr @ retour de la fonction en utilisant lr /********************************************************/ /* Calcul modulo de b puissance e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /* */ /********************************************************/ /* r0 nombre */ /* r1 exposant */ /* r2 modulo */ /* r0 return result */ moduloPuR32: push {r1-r7,lr} @ save registers cmp r0,#0 @ verif <> zero beq 100f cmp r2,#0 @ verif <> zero beq 100f @ TODO: vérifier les cas d erreur 1: mov r4,r2 @ save modulo mov r5,r1 @ save exposant mov r6,r0 @ save base mov r3,#1 @ start result   mov r1,#0 @ division de r0,r1 par r2 bl division32R mov r6,r2 @ base <- remainder 2: tst r5,#1 @ exposant even or odd beq 3f umull r0,r1,r6,r3 mov r2,r4 bl division32R mov r3,r2 @ result <- remainder 3: umull r0,r1,r6,r6 mov r2,r4 bl division32R mov r6,r2 @ base <- remainder   lsr r5,#1 @ left shift 1 bit cmp r5,#0 @ end ? bne 2b mov r0,r3 100: @ fin standard de la fonction pop {r1-r7,lr} @ restaur des registres bx lr @ retour de la fonction en utilisant lr   /***************************************************/ /* division number 64 bits in 2 registers by number 32 bits */ /***************************************************/ /* r0 contains lower part dividende */ /* r1 contains upper part dividende */ /* r2 contains divisor */ /* r0 return lower part quotient */ /* r1 return upper part quotient */ /* r2 return remainder */ division32R: push {r3-r9,lr} @ save registers mov r6,#0 @ init upper upper part remainder  !! mov r7,r1 @ init upper part remainder with upper part dividende mov r8,r0 @ init lower part remainder with lower part dividende mov r9,#0 @ upper part quotient mov r4,#0 @ lower part quotient mov r5,#32 @ bits number 1: @ begin loop lsl r6,#1 @ shift upper upper part remainder lsls r7,#1 @ shift upper part remainder orrcs r6,#1 lsls r8,#1 @ shift lower part remainder orrcs r7,#1 lsls r4,#1 @ shift lower part quotient lsl r9,#1 @ shift upper part quotient orrcs r9,#1 @ divisor sustract upper part remainder subs r7,r2 sbcs r6,#0 @ and substract carry bmi 2f @ négative ?   @ positive or equal orr r4,#1 @ 1 -> right bit quotient b 3f 2: @ negative orr r4,#0 @ 0 -> right bit quotient adds r7,r2 @ and restaur remainder adc r6,#0 3: subs r5,#1 @ decrement bit size bgt 1b @ end ? mov r0,r4 @ lower part quotient mov r1,r9 @ upper part quotient mov r2,r7 @ remainder 100: @ function end pop {r3-r9,lr} @ restaur registers bx lr /***************************************************/ /* shell Sort */ /***************************************************/   /* r0 contains the address of table */ /* r1 contains the first element but not use !! */ /* this routine use first element at index zero !!! */ /* r2 contains the number of element */ shellSort: push {r0-r7,lr} @save registers sub r2,#1 @ index last item mov r1,r2 @ init gap = last item 1: @ start loop 1 lsrs r1,#1 @ gap = gap / 2 beq 100f @ if gap = 0 -> end mov r3,r1 @ init loop indice 1 2: @ start loop 2 ldr r4,[r0,r3,lsl #2] @ load first value mov r5,r3 @ init loop indice 2 3: @ start loop 3 cmp r5,r1 @ indice < gap blt 4f @ yes -> end loop 2 sub r6,r5,r1 @ index = indice - gap ldr r7,[r0,r6,lsl #2] @ load second value cmp r4,r7 @ compare values strlt r7,[r0,r5,lsl #2] @ store if < sublt r5,r1 @ indice = indice - gap blt 3b @ and loop 4: @ end loop 3 str r4,[r0,r5,lsl #2] @ store value 1 at indice 2 add r3,#1 @ increment indice 1 cmp r3,r2 @ end ? ble 2b @ no -> loop 2 b 1b @ yes loop for new gap   100: @ end function pop {r0-r7,lr} @ restaur registers bx lr @ return /******************************************************************/ /* display divisors function */ /******************************************************************/ /* r0 contains address of divisors area */ /* r1 contains the number of area items */ displayDivisors: push {r2-r8,lr} @ save registers cmp r1,#0 beq 100f mov r2,r1 mov r3,#0 @ indice mov r4,r0 1: add r5,r4,r3,lsl #2 ldr r0,[r5] @ load factor   ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessResultFact ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message add r3,#1 @ other ithem cmp r3,r2 @ items maxi ? blt 1b ldr r0,iAdrszCarriageReturn bl affichageMess b 100f   100: pop {r2-r8,lr} @ restaur registers bx lr @ return iAdrszMessResultFact: .int szMessResultFact iAdrsZoneConv: .int sZoneConv /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#8th
8th
  200000 n# 5 4 3 2 bfloat ^ ^ ^ "%.0f" s:strfmt dup s:len . " digits" . cr dup 20 s:lsub . "..." . 20 s:rsub . cr  
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#ACL2
ACL2
(in-package "ACL2")   (include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)   (set-print-length 0 state)   (defun arbitrary-precision () (declare (xargs :mode :program)) (let* ((x (expt 5 (expt 4 (expt 3 2)))) (s (mv-let (col str) (fmt1-to-string "~xx" (list (cons #\x x)) 0) (declare (ignore col)) str))) (cw "~s0 ... ~x1 (~x2 digits)~%" (subseq s 0 20) (mod x (expt 10 20)) (1- (length s)))))
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#Elena
Elena
import system'collections; import system'routines; import extensions; import extensions'routines;   const string[] image = new string[]{ " ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "};   int[][] nbrs = new int[][] { new int[]{0, -1}, new int[]{1, -1}, new int[]{1, 0}, new int[]{1, 1}, new int[]{0, 1}, new int[]{-1, 1}, new int[]{-1, 0}, new int[]{-1, -1}, new int[]{0, -1} };   int[][][] nbrGroups = new int[][][] { new int[][]{new int[]{0, 2, 4}, new int[]{2, 4, 6}}, new int[][]{new int[]{0, 2, 6}, new int[]{0, 4, 6}} };   extension zhangsuenOp : Matrix<CharValue> { proceed(r, c, toWhite, firstStep) { if (self[r][c] != $35) { ^ false };   int nn := self.numNeighbors(r,c);   if ((nn < 2) || (nn > 6)) { ^ false };   if(self.numTransitions(r,c) != 1) { ^ false };   ifnot (self.atLeastOneIsWhite(r,c,firstStep.iif(0,1))) { ^ false };   toWhite.append(new { x = c; y = r; });   ^ true }   numNeighbors(r,c) { int count := 0;   for (int i := 0, i < nbrs.Length, i += 1) { if (self[r + nbrs[i][1]][c + nbrs[i][0]] == $35) { count += 1 } };   ^ count; }   numTransitions(r,c) { int count := 0;   for (int i := 0, i < nbrs.Length, i += 1) { if (self[r + nbrs[i][1]][c + nbrs[i][0]] == $32) { if (self[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == $35) { count := count + 1 } } };   ^ count }   atLeastOneIsWhite(r, c, step) { int count := 0; var group := nbrGroups[step]; for(int i := 0, i < 3, i += 1) { for(int j := 0, j < group[i].Length, j += 1) { var nbr := nbrs[group[i][j]];   if (self[r + nbr[1]][c + nbr[0]] == $32) { count := count + 1; ^ true };   ^ false } };   ^ count > 1 }   thinImage() { bool firstStep := false; bool hasChanged := true; var toWhite := new List();   while (hasChanged || firstStep) { hasChanged := false; firstStep := firstStep.Inverted;   for(int r := 1, r < self.Rows, r += 1) { for(int c := 1, c < self.Columns, c += 1) { if(self.proceed(r,c,toWhite,firstStep)) { hasChanged := true } } };   toWhite.forEach:(p){ self[p.y][p.x] := $32 }; toWhite.clear() } }   print() { var it := self.enumerator();   it.forEach:(ch){ console.print(ch," ") }; while (it.next()) { console.writeLine();   it.forEach:(ch){ console.print(ch," ") } } } }   public program() { Matrix<CharValue> grid := class Matrix<CharValue>.load(new { int Rows = image.Length;   int Columns = image[0].Length;   at(int i, int j) = image[i][j]; });   grid.thinImage();   grid.print();   console.readChar() }
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#Elixir
Elixir
defmodule ZhangSuen do @neighbours [{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}] # 8 neighbours   def thinning(str, black \\ ?#) do s0 = for {line, i} <- (String.split(str, "\n") |> Enum.with_index), {c, j} <- (to_char_list(line) |> Enum.with_index), into: Map.new, do: {{i,j}, (if c==black, do: 1, else: 0)} {xrange, yrange} = range(s0) print(s0, xrange, yrange) s1 = thinning_loop(s0, xrange, yrange) print(s1, xrange, yrange) end   defp thinning_loop(s0, xrange, yrange) do s1 = step(s0, xrange, yrange, 1) # Step 1 s2 = step(s1, xrange, yrange, 0) # Step 2 if Map.equal?(s0, s2), do: s2, else: thinning_loop(s2, xrange, yrange) end   defp step(s, xrange, yrange, g) do for x <- xrange, y <- yrange, into: Map.new, do: {{x,y}, s[{x,y}] - zs(s,x,y,g)} end   defp zs(s, x, y, g) do if get(s,x,y) == 0 or # P1 (get(s,x-1,y) + get(s,x,y+1) + get(s,x+g,y-1+g)) == 3 or # P2, P4, P6/P8 (get(s,x-1+g,y+g) + get(s,x+1,y) + get(s,x,y-1)) == 3 do # P4/P2, P6, P8 0 else next = for {i,j} <- @neighbours, do: get(s, x+i, y+j) bp1 = Enum.sum(next) # B(P1) if bp1 in 2..6 do ap1 = (next++[hd(next)]) |> Enum.chunk(2,1) |> Enum.count(fn [a,b] -> a<b end) # A(P1) if ap1 == 1, do: 1, else: 0 else 0 end end end   defp get(map, x, y), do: Map.get(map, {x,y}, 0)   defp range(map), do: range(Map.keys(map), 0, 0) defp range([], xmax, ymax), do: {0 .. xmax, 0 .. ymax} defp range([{x,y} | t], xmax, ymax), do: range(t, max(x,xmax), max(y,ymax))   @display  %{0 => " ", 1 => "#"} defp print(map, xrange, yrange) do Enum.each(xrange, fn x -> IO.puts (for y <- yrange, do: @display[map[{x,y}]]) end) end end   str = """ ........................................................... .#################...................#############......... .##################...............################......... .###################............##################......... .########.....#######..........###################......... ...######.....#######.........#######.......######......... ...######.....#######........#######....................... ...#################.........#######....................... ...###############...........#######....................... ...#################.........#######....................... ...######....########........#######....................... ...######.....#######........#######....................... ...######.....#######.........#######.......######......... .########.....#######..........###################......... .########.....#######..#####....##################.######.. .########.....#######..#####......################.######.. .########.....#######..#####.........#############.######.. ........................................................... """ ZhangSuen.thinning(str)   str = """ 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 """ ZhangSuen.thinning(str, ?1)
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#XPL0
XPL0
real A, B, R, T, X, Y; [SetVid($12); \set 640x480 graphics A:= 0.0; B:= 3.0; T:= 0.0; Move(320, 240); \start at center of screen repeat R:= A + B*T; X:= R*Cos(T); Y:= R*Sin(T); Line(fix(X)+320, 240-fix(Y), 4\red\); T:= T + 0.03; \increase angle (Theta) until T >= 314.159; \50 revs ]
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.
#Yabasic
Yabasic
5 OPEN WINDOW 320, 200 : WINDOW ORIGIN "CC" 10 LET A=1.5 20 LET B=0.7 30 FOR T=0 TO 30*PI STEP 0.05 40 LET R=A+B*T 50 LINE TO R*COS(T),R*SIN(T) 60 NEXT T
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.
#zkl
zkl
fcn archimedeanSpiral(a,b,circles){ w,h:=640,640; centerX,centerY:=w/2,h/2; bitmap:=PPM(w+1,h+1,0xFF|FF|FF); // White background   foreach deg in ([0.0 .. 360*circles]){ rad:=deg.toRad(); r:=rad*b + a; x,y:=r.toRectangular(rad); bitmap[centerX + x, centerY + y] = 0x00|FF|00; // Green dot } bitmap.writeJPGFile("archimedeanSpiral.jpg"); }(0,5,7);
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#C.2B.2B
C++
  // For a class N which implements Zeckendorf numbers: // I define an increment operation ++() // I define a comparison operation <=(other N) // Nigel Galloway October 22nd., 2012 #include <iostream> class N { private: int dVal = 0, dLen; public: N(char const* x = "0"){ int i = 0, q = 1; for (; x[i] > 0; i++); for (dLen = --i/2; i >= 0; i--) { dVal+=(x[i]-48)*q; q*=2; }} const N& operator++() { for (int i = 0;;i++) { if (dLen < i) dLen = i; switch ((dVal >> (i*2)) & 3) { case 0: dVal += (1 << (i*2)); return *this; case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this; case 2: dVal &= ~(3 << (i*2)); }}} const bool operator<=(const N& other) const {return dVal <= other.dVal;} friend std::ostream& operator<<(std::ostream&, const N&); }; N operator "" N(char const* x) {return N(x);} std::ostream &operator<<(std::ostream &os, const N &G) { const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"}; if (G.dVal == 0) return os << "0"; os << dig1[(G.dVal >> (G.dLen*2)) & 3]; for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3]; return os; }  
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.
#bc
bc
/* 0 means door is closed, 1 means door is open */ for (i = 0; i < 100; i++) { for (j = i; j < 100; j += (i + 1)) { d[j] = 1 - d[j] /* Toggle door */ } }   "Open doors: " for (i = 0; i < 100; i++) { if (d[i] == 1) (i + 1) }
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)
#Dragon
Dragon
array = newarray(3) //optionally, replace "newarray(5)" with a brackets list of values like "[1, 2, 3]" array[0] = 42 showln array[2]
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.
#Nanoquery
Nanoquery
import math   class Complex declare real declare imag   def Complex() real = 0.0 imag = 0.0 end   def Complex(r, i) real = double(r) imag = double(i) end   def operator-(b) return new(Complex, this.real - b.real, this.imag - b.imag) end   def operator+(b) return new(Complex, this.real + b.real, this.imag + b.imag) end   def operator*(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) end   def inv() // 1/(a+bi) * (a-bi)/(a-bi) = 1/(a+bi) but it's more workable denom = this.real * this.real + this.imag * this.imag return new(Complex, real/denom, -imag/denom) end   def neg() return new(Complex, -this.real, -this.imag) end   def conj() return new(Complex, this.real, -this.imag) end   def toString() return this.real + " + " + this.imag + " * i" end end   a = new(Complex, math.pi, -5) b = new(Complex, -1, 2.5) println a.neg() println a + b println a.inv() println a * b println a.conj()
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.
#Nemerle
Nemerle
using System; using System.Console; using System.Numerics; using System.Numerics.Complex;   module RCComplex { PrettyPrint(this c : Complex) : string { mutable sign = '+'; when (c.Imaginary < 0) sign = '-'; $"$(c.Real) $sign $(Math.Abs(c.Imaginary))i" }   Main() : void { def complex1 = Complex(1.0, 1.0); def complex2 = Complex(3.14159, 1.2);   WriteLine(Add(complex1, complex2).PrettyPrint()); WriteLine(Multiply(complex1, complex2).PrettyPrint()); WriteLine(Negate(complex2).PrettyPrint()); WriteLine(Reciprocal(complex2).PrettyPrint()); WriteLine(Conjugate(complex2).PrettyPrint()); } }
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
#PARI.2FGP
PARI/GP
for(n=2,1<<19, s=0; fordiv(n,d,s+=1/d); if(s==2,print(n)) )
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
#Raku
Raku
sub agm( $a is copy, $g is copy ) { ($a, $g) = ($a + $g)/2, sqrt $a * $g until $a ≅ $g; return $a; }   say agm 1, 1/sqrt 2;
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Raven
Raven
define agm use $a, $g, $errlim # $errlim $g $a "%d %g %d\n" print $a 1.0 + as $t repeat $a 1.0 * $g - abs -15 exp10 $a * > while $a $g + 2 / as $t $a $g * sqrt as $g $t as $a $g $a $t "t: %g a: %g g: %g\n" print $a     16 1 2 sqrt / 1 agm "agm: %.15g\n" print
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Delphi
Delphi
print pow 0 0
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#EasyLang
EasyLang
print pow 0 0
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Oz
Oz
declare   fun {Expr X0 ?X} choice [L _ R] = {Do [Term &+ Expr] X0 ?X} in add(L R) [] [L _ R] = {Do [Term &- Expr] X0 ?X} in sub(L R) [] {Term X0 X} end end   fun {Term X0 ?X} choice [L _ R] = {Do [Factor &* Term] X0 ?X} in mul(L R) [] [L _ R] = {Do [Factor &/ Term] X0 ?X} in 'div'(L R) [] {Factor X0 X} end end   fun {Factor X0 ?X} choice {Parens Expr X0 X} [] {Number X0 X} end end   fun {Number X0 X} Ds = {Many1 Digit X0 X} in num(Ds) end   fun {Digit X0 ?X} D|!X = X0 in D = choice &0 [] &1 [] &2 [] &3 [] &4 [] &5 [] &6 [] &7 [] &8 [] &9 end end   fun {Many1 Rule X0 ?X} choice [{Rule X0 X}] [] X1 in {Rule X0 X1}|{Many1 Rule X1 X} end end   fun {Parens Rule X0 ?X} [_ R _] = {Do [&( Rule &)] X0 X} in R end   fun {Do Rules X0 ?X} Res#Xn = {FoldL Rules fun {$ Res#Xi Rule} if {Char.is Rule} then !Rule|X2 = Xi in (Rule|Res) # X2 elseif {Procedure.is Rule} then X2 in ({Rule Xi X2}|Res) # X2 end end nil#X0} in X = Xn {Reverse Res} end   %% Returns a singleton list if an AST was found or nil otherwise. fun {Parse S} {SearchOne fun {$} {Expr S nil} end} end   fun {Eval X} case X of num(Ds) then {String.toInt Ds} [] add(L R) then {Eval L} + {Eval R} [] sub(L R) then {Eval L} - {Eval R} [] mul(L R) then {Eval L} * {Eval R} [] 'div'(L R) then {Eval L} div {Eval R} end end   [AST] = {Parse "((11+15)*15)*2-(3)*4*1"}   in   {Inspector.configure widgetShowStrings true} {Inspect AST} {Inspect {Eval AST}}
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case. Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100; Subtraction 10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg: abcde 10100 - 1000 _____ 100 borrow 1 from a leaves 100 + 100 add the carry _____ 1001 A larger example: abcdef 100100 - 1000 ______ 1*0100 borrow 1 from b + 100 add the carry ______ 1*1001 Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a: 1001 + 1000 add the carry ____ 10100 Multiplication Here you teach your computer its zeckendorf tables. eg. 101 * 1001: a = 1 * 101 = 101 b = 10 * 101 = a + a = 10000 c = 100 * 101 = b + a = 10101 d = 1000 * 101 = c + b = 101010 1001 = d + a therefore 101 * 1001 = 101010 + 101 ______ 1000100 Division Lets try 1000101 divided by 101, so we can use the same table used for multiplication. 1000101 - 101010 subtract d (1000 * 101) _______ 1000 - 101 b and c are too large to subtract, so subtract a ____ 1 so 1000101 divided by 101 is d + a (1001) remainder 1 Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
#C
C
#include <stdbool.h> #include <stdio.h> #include <string.h>   int inv(int a) { return a ^ -1; }   struct Zeckendorf { int dVal, dLen; };   void a(struct Zeckendorf *self, int n) { void b(struct Zeckendorf *, int); // forward declare   int i = n; while (true) { if (self->dLen < i) self->dLen = i; int j = (self->dVal >> (i * 2)) & 3; switch (j) { case 0: case 1: return; case 2: if (((self->dVal >> ((i + 1) * 2)) & 1) != 1) return; self->dVal += 1 << (i * 2 + 1); return; case 3: self->dVal = self->dVal & inv(3 << (i * 2)); b(self, (i + 1) * 2); break; default: break; } i++; } }   void b(struct Zeckendorf *self, int pos) { void increment(struct Zeckendorf *); // forward declare   if (pos == 0) { increment(self); return; } if (((self->dVal >> pos) & 1) == 0) { self->dVal += 1 << pos; a(self, pos / 2); if (pos > 1) a(self, pos / 2 - 1); } else { self->dVal = self->dVal & inv(1 << pos); b(self, pos + 1); b(self, pos - (pos > 1 ? 2 : 1)); } }   void c(struct Zeckendorf *self, int pos) { if (((self->dVal >> pos) & 1) == 1) { self->dVal = self->dVal & inv(1 << pos); return; } c(self, pos + 1); if (pos > 0) { b(self, pos - 1); } else { increment(self); } }   struct Zeckendorf makeZeckendorf(char *x) { struct Zeckendorf z = { 0, 0 }; int i = strlen(x) - 1; int q = 1;   z.dLen = i / 2; while (i >= 0) { z.dVal += (x[i] - '0') * q; q *= 2; i--; }   return z; }   void increment(struct Zeckendorf *self) { self->dVal++; a(self, 0); }   void addAssign(struct Zeckendorf *self, struct Zeckendorf rhs) { int gn; for (gn = 0; gn < (rhs.dLen + 1) * 2; gn++) { if (((rhs.dVal >> gn) & 1) == 1) { b(self, gn); } } }   void subAssign(struct Zeckendorf *self, struct Zeckendorf rhs) { int gn; for (gn = 0; gn < (rhs.dLen + 1) * 2; gn++) { if (((rhs.dVal >> gn) & 1) == 1) { c(self, gn); } } while ((((self->dVal >> self->dLen * 2) & 3) == 0) || (self->dLen == 0)) { self->dLen--; } }   void mulAssign(struct Zeckendorf *self, struct Zeckendorf rhs) { struct Zeckendorf na = rhs; struct Zeckendorf nb = rhs; struct Zeckendorf nr = makeZeckendorf("0"); struct Zeckendorf nt; int i;   for (i = 0; i < (self->dLen + 1) * 2; i++) { if (((self->dVal >> i) & 1) > 0) addAssign(&nr, nb); nt = nb; addAssign(&nb, na); na = nt; }   *self = nr; }   void printZeckendorf(struct Zeckendorf z) { static const char *const dig[3] = { "00", "01", "10" }; static const char *const dig1[3] = { "", "1", "10" };   if (z.dVal == 0) { printf("0"); return; } else { int idx = (z.dVal >> (z.dLen * 2)) & 3; int i;   printf(dig1[idx]); for (i = z.dLen - 1; i >= 0; i--) { idx = (z.dVal >> (i * 2)) & 3; printf(dig[idx]); } } }   int main() { struct Zeckendorf g;   printf("Addition:\n"); g = makeZeckendorf("10"); addAssign(&g, makeZeckendorf("10")); printZeckendorf(g); printf("\n"); addAssign(&g, makeZeckendorf("10")); printZeckendorf(g); printf("\n"); addAssign(&g, makeZeckendorf("1001")); printZeckendorf(g); printf("\n"); addAssign(&g, makeZeckendorf("1000")); printZeckendorf(g); printf("\n"); addAssign(&g, makeZeckendorf("10101")); printZeckendorf(g); printf("\n\n");   printf("Subtraction:\n"); g = makeZeckendorf("1000"); subAssign(&g, makeZeckendorf("101")); printZeckendorf(g); printf("\n"); g = makeZeckendorf("10101010"); subAssign(&g, makeZeckendorf("1010101")); printZeckendorf(g); printf("\n\n");   printf("Multiplication:\n"); g = makeZeckendorf("1001"); mulAssign(&g, makeZeckendorf("101")); printZeckendorf(g); printf("\n"); g = makeZeckendorf("101010"); addAssign(&g, makeZeckendorf("101")); printZeckendorf(g); printf("\n");   return 0; }
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal. E.G. 6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6. 10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value. 12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14. Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0 Task Write a routine (function, procedure, whatever) to find Zumkeller numbers. Use the routine to find and display here, on this page, the first 220 Zumkeller numbers. Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers. Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5. See Also OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions OEIS:A174865 - Odd Zumkeller numbers Related Tasks Abundant odd numbers Abundant, deficient and perfect number classifications Proper divisors , Factors of an integer
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace ZumkellerNumbers { class Program { static List<int> GetDivisors(int n) { List<int> divs = new List<int> { 1, n }; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.Add(i); if (i != j) { divs.Add(j); } } } return divs; }   static bool IsPartSum(List<int> divs, int sum) { if (sum == 0) { return true; } var le = divs.Count; if (le == 0) { return false; } var last = divs[le - 1]; List<int> newDivs = new List<int>(); for (int i = 0; i < le - 1; i++) { newDivs.Add(divs[i]); } if (last > sum) { return IsPartSum(newDivs, sum); } return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last); }   static bool IsZumkeller(int n) { var divs = GetDivisors(n); var sum = divs.Sum(); // if sum is odd can't be split into two partitions with equal sums if (sum % 2 == 1) { return false; } // if n is odd use 'abundant odd number' optimization if (n % 2 == 1) { var abundance = sum - 2 * n; return abundance > 0 && abundance % 2 == 0; } // if n and sum are both even check if there's a partition which totals sum / 2 return IsPartSum(divs, sum / 2); }   static void Main() { Console.WriteLine("The first 220 Zumkeller numbers are:"); int i = 2; for (int count = 0; count < 220; i++) { if (IsZumkeller(i)) { Console.Write("{0,3} ", i); count++; if (count % 20 == 0) { Console.WriteLine(); } } }   Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (IsZumkeller(i)) { Console.Write("{0,5} ", i); count++; if (count % 10 == 0) { Console.WriteLine(); } } }   Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (i % 10 != 5 && IsZumkeller(i)) { Console.Write("{0,7} ", i); count++; if (count % 8 == 0) { Console.WriteLine(); } } } } } }
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with GNATCOLL.GMP; use GNATCOLL.GMP; with GNATCOLL.GMP.Integers; use GNATCOLL.GMP.Integers; procedure ArbitraryInt is type stracc is access String; BigInt : Big_Integer; len : Natural; str : stracc; begin Set (BigInt, 5); Raise_To_N (BigInt, Unsigned_Long (4**(3**2))); str := new String'(Image (BigInt)); len := str'Length; Put_Line ("Size is:"& Natural'Image (len)); Put_Line (str (1 .. 20) & "....." & str (len - 19 .. len)); end ArbitraryInt;
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#ALGOL_68
ALGOL 68
  BEGIN COMMENT The task specifies   "Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value."   Now one should always speak strictly, especially to animals and small children and, strictly speaking, Algol 68 Genie requires that a non-default numeric precision for a LONG LONG INT be specified by "precision=<integral denotation>" either in a source code PRAGMAT or as a command line argument. However, that specification need not be made manually. This snippet of code outputs an appropriate PRAGMAT   printf (($gg(0)xgl$, "PR precision=", ENTIER (1.0 + log (5) * 4^(3^(2))), "PR"));   and the technique shown in the "Call a foreign-language function" task used to write, compile and run an Algol 68 program in which the precision is programmatically determined.   The default stack size on this machine is also inadequate but twice the default is sufficient. The PRAGMAT below can be machine generated with   printf (($gg(0)xgl$, "PR stack=", 2 * system stack size, "PR"));   COMMENT PR precision=183231 PR PR stack=16777216 PR INT digits = ENTIER (1.0 + log (5) * 4^(3^(2))), exponent = 4^(3^2); LONG LONG INT big = LONG LONG 5^exponent; printf (($gxg(0)l$, " First 20 digits:", big % LONG LONG 10 ^ (digits - 20))); printf (($gxg(0)l$, " Last 20 digits:", big MOD LONG LONG 10 ^ 20)); printf (($gxg(0)l$, "Number of digits:", digits)) END  
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#Fortran
Fortran
FOR ALL (i = 2:n - 1) A(i) = (A(i - 1) + A(i) + A(i + 1))/3
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### Algorithm Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:   P9     P2     P3     P8     P1     P4     P7     P6     P5   Obviously the boundary pixels of the image cannot have the full eight neighbours. Define A ( P 1 ) {\displaystyle A(P1)} = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). Define B ( P 1 ) {\displaystyle B(P1)} = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) Step 1 All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P6 is white (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. Step 2 All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. (0) The pixel is black and has eight neighbours (1) 2 <= B ( P 1 ) <= 6 {\displaystyle 2<=B(P1)<=6} (2) A(P1) = 1 (3) At least one of P2 and P4 and P8 is white (4) At least one of P2 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. Iteration If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. Task Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 Reference Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#FreeBASIC
FreeBASIC
' version 08-10-2016 ' compile with: fbc -s console   Data "00000000000000000000000000000000" Data "01111111110000000111111110000000" Data "01110001111000001111001111000000" Data "01110000111000001110000111000000" Data "01110001111000001110000000000000" Data "01111111110000001110000000000000" Data "01110111100000001110000111000000" Data "01110011110011101111001111011100" Data "01110001111011100111111110011100" Data "00000000000000000000000000000000" Data "END"   ' ------=< MAIN >=------   Dim As UInteger x, y, m, n Dim As String input_str   Do ' find out how big it is Read input_str If input_str = "END" Then Exit Do If x < Len(input_str) Then x = Len(input_str) y = y + 1 Loop   m = x -1 : n = y -1 ReDim As UByte old(m, n), new_(m, n)   y = 0 Restore ' restore data pointer Do ' put data in array Read input_str If input_str="END" Then Exit Do For x = 0 To Len(input_str) -1 old(x,y) = input_str[x] - Asc("0") ' print image If old(x, y) = 0 Then Print "."; Else Print "#"; Next Print y = y + 1 Loop   'corners and sides do not change For x = 0 To m new_(x, 0) = old(x, 0) new_(x, n) = old(x, n) Next   For y = 0 To n new_(0, y) = old(0, y) new_(m, y) = old(m, y) Next   Dim As UInteger tmp, change, stage = 1 Do change = 0 For y = 1 To n -1 For x = 1 To m -1 ' -1- If old(x,y) = 0 Then ' first condition, p1 must be black new_(x,y) = 0 Continue For End If ' -2- tmp = old(x, y -1) + old(x +1, y -1) tmp = tmp + old(x +1, y) + old(x +1, y +1) + old(x, y +1) tmp = tmp + old(x -1, y +1) + old(x -1, y) + old(x -1, y -1) If tmp < 2 OrElse tmp > 6 Then ' 2 <= B(p1) <= 6 new_(x, y) = 1 Continue For End If ' -3- tmp = 0 If old(x , y ) = 0 And old(x , y -1) = 1 Then tmp += 1 ' p1 > p2 If old(x , y -1) = 0 And old(x +1, y -1) = 1 Then tmp += 1 ' p2 > p3 If old(x +1, y -1) = 0 And old(x +1, y ) = 1 Then tmp += 1 ' p3 > p4 If old(x +1, y ) = 0 And old(x +1, y +1) = 1 Then tmp += 1 ' p4 > p5 If old(x +1, y +1) = 0 And old(x , y +1) = 1 Then tmp += 1 ' p5 > p6 If old(x , y +1) = 0 And old(x -1, y +1) = 1 Then tmp += 1 ' p6 > p7 If old(x -1, y +1) = 0 And old(x -1, y ) = 1 Then tmp += 1 ' p7 > p8 If old(x -1, y ) = 0 And old(x -1, y -1) = 1 Then tmp += 1 ' p8 > p9 If old(x -1, y -1) = 0 And old(x , y -1) = 1 Then tmp += 1 ' p9 > p2 ' tmp = 1 ==> A(P1) = 1 If tmp <> 1 Then new_(x, y) = 1 Continue For End If If (stage And 1) = 1 Then ' step 1 -4- -5- If (old(x, y -1) + old(x +1, y) + old(x, y +1)) = 3 OrElse _ (old(x +1, y) + old(x, y +1) + old(x -1, y)) = 3 Then new_(x, y) = 1 Continue For End If Else ' step 2 -4- -5- If (old(x, y -1) + old(x +1, y) + old(x -1, y)) = 3 OrElse _ (old(x, y -1) + old(x, y +1) + old(x -1, y)) = 3 Then new_(x, y) = 1 Continue For End If End If ' all condition are met, make p1 white (0) new_(x, y) = 0 change = 1 ' flag change Next Next   ' copy new_() into old() For y = 0 To n For x = 0 To m old(x, y) = new_(x, y) Next Next   stage += 1 Loop Until change = 0 ' stop when there are no changes made   Print ' print result Print "End result" For y = 0 To n For x = 0 To m If old(x, y) = 0 Then Print "."; Else Print "#"; Next Print Next     ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Clojure
Clojure
(def fibs (lazy-cat [1 1] (map + fibs (rest fibs))))   (defn z [n] (if (zero? n) "0" (let [ps (->> fibs (take-while #(<= % n)) rest reverse) fz (fn [[s n] p] (if (>= n p) [(conj s 1) (- n p)] [(conj s 0) n]))] (->> ps (reduce fz [[] n]) first (apply str)))))   (doseq [n (range 0 21)] (println n (z n)))
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.
#BCPL
BCPL
get "libhdr"   let start() be $( let doors = vec 100   // close all doors for n = 1 to 100 do doors!n := 0   // make 100 passes for pass = 1 to 100 do $( let n = pass while n <= 100 do $( doors!n := ~doors!n n := n + pass $) $)   // report which doors are open for n = 1 to 100 do if doors!n then writef("Door %N is open.*N", n) $)
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)
#DWScript
DWScript
  // dynamic array, extensible, this a reference type var d : array of Integer; d.Add(1); // has various methods to add, delete, etc. d.Add(2, 3);   // read and write elements by index item := d[5]; d[6] := item+1;   // static, fixed-size array, arbitrary lower-bound, this is a value type var s : array [2..4] of Integer;   // inline array constructor, works for both static and dynamic arrays s := [1, 2, 3];