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/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
#COBOL
COBOL
identification division. program-id. arbitrary-precision-integers. remarks. Uses opaque libgmp internals that are built into libcob.   data division. working-storage section. 01 gmp-number. 05 mp-alloc usage binary-long. 05 mp-size usage binary-long. 05 mp-limb usage pointer. 01 gmp-build. 05 mp-alloc usage binary-long. 05 mp-size usage binary-long. 05 mp-limb usage pointer.   01 the-int usage binary-c-long unsigned. 01 the-exponent usage binary-c-long unsigned. 01 valid-exponent usage binary-long value 1. 88 cant-use value 0 when set to false 1.   01 number-string usage pointer. 01 number-length usage binary-long.   01 window-width constant as 20. 01 limit-width usage binary-long. 01 number-buffer pic x(window-width) based.   procedure division. arbitrary-main.   *> calculate 10 ** 19 perform initialize-integers. display "10 ** 19  : " with no advancing move 10 to the-int move 19 to the-exponent perform raise-pow-accrete-exponent perform show-all-or-portion perform clean-up   *> calculate 12345 ** 9 perform initialize-integers. display "12345 ** 9  : " with no advancing move 12345 to the-int move 9 to the-exponent perform raise-pow-accrete-exponent perform show-all-or-portion perform clean-up   *> calculate 5 ** 4 ** 3 ** 2 perform initialize-integers. display "5 ** 4 ** 3 ** 2: " with no advancing move 3 to the-int move 2 to the-exponent perform raise-pow-accrete-exponent move 4 to the-int perform raise-pow-accrete-exponent move 5 to the-int perform raise-pow-accrete-exponent perform show-all-or-portion perform clean-up goback. *> **************************************************************   initialize-integers. call "__gmpz_init" using gmp-number returning omitted call "__gmpz_init" using gmp-build returning omitted .   raise-pow-accrete-exponent. *> check before using previously overflowed exponent intermediate if cant-use then display "Error: intermediate overflow occured at " the-exponent upon syserr goback end-if call "__gmpz_set_ui" using gmp-number by value 0 returning omitted call "__gmpz_set_ui" using gmp-build by value the-int returning omitted call "__gmpz_pow_ui" using gmp-number gmp-build by value the-exponent returning omitted call "__gmpz_set_ui" using gmp-build by value 0 returning omitted call "__gmpz_get_ui" using gmp-number returning the-exponent call "__gmpz_fits_ulong_p" using gmp-number returning valid-exponent .   *> get string representation, base 10 show-all-or-portion. call "__gmpz_sizeinbase" using gmp-number by value 10 returning number-length display "GMP length: " number-length ", " with no advancing   call "__gmpz_get_str" using null by value 10 by reference gmp-number returning number-string call "strlen" using by value number-string returning number-length display "strlen: " number-length   *> slide based string across first and last of buffer move window-width to limit-width set address of number-buffer to number-string if number-length <= window-width then move number-length to limit-width display number-buffer(1:limit-width) else display number-buffer with no advancing subtract window-width from number-length move function max(0, number-length) to number-length if number-length <= window-width then move number-length to limit-width else display "..." with no advancing end-if set address of number-buffer up by function max(window-width, number-length) display number-buffer(1:limit-width) end-if .   clean-up. call "free" using by value number-string returning omitted call "__gmpz_clear" using gmp-number returning omitted call "__gmpz_clear" using gmp-build returning omitted set address of number-buffer to null set cant-use to false .   end program arbitrary-precision-integers.  
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
#JavaScript
JavaScript
function Point(x, y) { this.x = x; this.y = y; } var ZhangSuen = (function () { function ZhangSuen() { } ZhangSuen.image = [" ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "];   ZhangSuen.nbrs = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]];   ZhangSuen.nbrGroups = [[[0, 2, 4], [2, 4, 6]], [[0, 2, 6], [0, 4, 6]]];   ZhangSuen.toWhite = new Array(); ; ZhangSuen.main = function (args) { ZhangSuen.grid = new Array(ZhangSuen.image.length); for (var r = 0; r < ZhangSuen.image.length; r++) ZhangSuen.grid[r] = (ZhangSuen.image[r]).split(''); ZhangSuen.thinImage(); }; ZhangSuen.thinImage = function () { var firstStep = false; var hasChanged; do { hasChanged = false; firstStep = !firstStep; for (var r = 1; r < ZhangSuen.grid.length - 1; r++) { for (var c = 1; c < ZhangSuen.grid[0].length - 1; c++) { if (ZhangSuen.grid[r][c] !== '#') continue; var nn = ZhangSuen.numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (ZhangSuen.numTransitions(r, c) !== 1) continue; if (!ZhangSuen.atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; ZhangSuen.toWhite.push(new Point(c, r)); hasChanged = true; } } for (let i = 0; i < ZhangSuen.toWhite.length; i++) { var p = ZhangSuen.toWhite[i]; ZhangSuen.grid[p.y][p.x] = ' '; } ZhangSuen.toWhite = new Array(); } while ((firstStep || hasChanged)); ZhangSuen.printResult(); }; ZhangSuen.numNeighbors = function (r, c) { var count = 0; for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++) if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === '#') count++; return count; }; ZhangSuen.numTransitions = function (r, c) { var count = 0; for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++) if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === ' ') { if (ZhangSuen.grid[r + ZhangSuen.nbrs[i + 1][1]][c + ZhangSuen.nbrs[i + 1][0]] === '#') count++; } return count; }; ZhangSuen.atLeastOneIsWhite = function (r, c, step) { var count = 0; var group = ZhangSuen.nbrGroups[step]; for (var i = 0; i < 2; i++) for (var j = 0; j < group[i].length; j++) { var nbr = ZhangSuen.nbrs[group[i][j]]; if (ZhangSuen.grid[r + nbr[1]][c + nbr[0]] === ' ') { count++; break; } } return count > 1; }; ZhangSuen.printResult = function () { for (var i = 0; i < ZhangSuen.grid.length; i++) { var row = ZhangSuen.grid[i]; console.log(row.join('')); } }; return ZhangSuen; }()); ZhangSuen.main(null);
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
#EchoLisp
EchoLisp
  ;; special fib's starting with 1 2 3 5 ... (define (fibonacci n) (+ (fibonacci (1- n)) (fibonacci (- n 2)))) (remember 'fibonacci #(1 2))   (define-constant Φ (// (1+ (sqrt 5)) 2)) (define-constant logΦ (log Φ)) ;; find i : fib(i) >= n (define (iFib n) (floor (// (log (+ (* n Φ) 0.5)) logΦ)))   ;; left trim zeroes (string-delimiter "") (define (zeck->string digits) (if (!= 0 (first digits)) (string-join digits "") (zeck->string (rest digits))))   (define (Zeck n) (cond (( < n 0) "no negative zeck") ((inexact? n) "no floating zeck") ((zero? n) "0") (else (zeck->string (for/list ((s (reverse (take fibonacci (iFib n))))) (if ( > s n) 0 (begin (-= n s) 1 )))))))  
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.
#Burlesque
Burlesque
  blsq ) 10ro2?^ {1 4 9 16 25 36 49 64 81 100}  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Eiffel
Eiffel
  class APPLICATION   inherit ARGUMENTS   create make   feature {NONE} -- Initialization make -- Run application. do -- initialize the array, index starts at 1 (not zero) and prefill everything with the letter z create my_static_array.make_filled ("z", 1, 50)   my_static_array.put ("a", 1) my_static_array.put ("b", 2) my_static_array [3] := "c"   -- access to array fields print (my_static_array.at(1) + "%N") print (my_static_array.at(2) + "%N") print (my_static_array [3] + "%N")   -- in Eiffel static arrays can be resized in three ways my_static_array.force ("c", 51) -- forces 'c' in position 51 and resizes the array to that size (now 51 places) my_static_array.automatic_grow -- adds 50% more indices (having now 76 places) my_static_array.grow (100) -- resizes the array to 100 places end   my_static_array: ARRAY [STRING] 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.
#Pascal
Pascal
program complexDemo(output);   const { I experienced some hiccups with -1.0 using GPC (GNU Pascal Compiler) } negativeOne = -1.0;   type line = string(80);   { as per task requirements wrap arithmetic operations into separate functions } function sum(protected x, y: complex): complex; begin sum := x + y end;   function product(protected x, y: complex): complex; begin product := x * y end;   function negative(protected x: complex): complex; begin negative := -x end;   function inverse(protected x: complex): complex; begin inverse := x ** negativeOne end;   { only this function is not covered by Extended Pascal, ISO 10206 } function conjugation(protected x: complex): complex; begin conjugation := cmplx(re(x), im(x) * negativeOne) end;   { --- test suite ------------------------------------------------------------- } function asString(protected x: complex): line; const totalWidth = 5; fractionDigits = 2; var result: line; begin writeStr(result, '(', re(x):totalWidth:fractionDigits, ', ', im(x):totalWidth:fractionDigits, ')'); asString := result end;   { === MAIN =================================================================== } var x: complex; { for demonstration purposes: how to initialize complex variables } y: complex value cmplx(1.0, 4.0); z: complex value polar(exp(1.0), 3.14159265358979); begin x := cmplx(-3, 2);   writeLn(asString(x), ' + ', asString(y), ' = ', asString(sum(x, y))); writeLn(asString(x), ' * ', asString(z), ' = ', asString(product(x, z)));   writeLn;   writeLn(' −', asString(z), ' = ', asString(negative(z))); writeLn(' inverse(', asString(z), ') = ', asString(inverse(z))); writeLn(' conjugation(', asString(y), ') = ', asString(conjugation(y))); end.
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ -2 n->v rot factors witheach [ n->v 1/v v+ ] v0= ] is perfect ( n -> b )   19 bit times [ i^ perfect if [ i^ echo cr ] ]
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
#Smalltalk
Smalltalk
agm:y "return the arithmetic-geometric mean agm(x, y) of the receiver (x) and the argument, y. See https://en.wikipedia.org/wiki/Arithmetic-geometric_mean"   |ai an gi gn epsilon delta|   ai := (self + y) / 2. gi := (self * y) sqrt. epsilon := self ulp.   [ an := (ai + gi) / 2. gn := (ai * gi) sqrt. delta := (an - ai) abs. ai := an. gi := gn. ] doUntil:[ delta < epsilon ]. ^ ai
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
#Frink
Frink
println[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
#FutureBasic
FutureBasic
window 1   print 0^0   HandleEvents
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
#Gambas
Gambas
Public Sub Main()   Print 0 ^ 0   End
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Zig_Zag is   type Matrix is array (Positive range <>, Positive range <>) of Natural; function Zig_Zag (Size : Positive) return Matrix is Data : Matrix (1..Size, 1..Size); I, J : Integer := 1; begin Data (1, 1) := 0; for Element in 1..Size**2 - 1 loop if (I + J) mod 2 = 0 then -- Even stripes if J < Size then J := J + 1; else I := I + 2; end if; if I > 1 then I := I - 1; end if; else -- Odd stripes if I < Size then I := I + 1; else J := J + 2; end if; if J > 1 then J := J - 1; end if; end if; Data (I, J) := Element; end loop; return Data; end Zig_Zag;   procedure Put (Data : Matrix) is begin for I in Data'Range (1) loop for J in Data'Range (2) loop Put (Integer'Image (Data (I, J))); end loop; New_Line; end loop; end Put;   begin Put (Zig_Zag (5)); end Test_Zig_Zag;
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. Example a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). Task Find and show as output the first  30  Yellowstone numbers. Extra Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. Related tasks   Greatest common divisor.   Plot coordinate pairs. See also   The OEIS entry:   A098550 The Yellowstone permutation.   Applegate et al, 2015: The Yellowstone Permutation [1].
#Arturo
Arturo
yellowstone: function [n][ result: new [1 2 3] present: new [1 2 3] start: new 4 while [n > size result][ candidate: new start while ø [ if all? @[ not? contains? present candidate 1 = gcd @[candidate last result] 1 <> gcd @[candidate get result (size result)-2] ][ 'result ++ candidate 'present ++ candidate while [contains? present start] -> inc 'start break ] inc 'candidate ] ] return result ]   print yellowstone 30
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. Example a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). Task Find and show as output the first  30  Yellowstone numbers. Extra Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. Related tasks   Greatest common divisor.   Plot coordinate pairs. See also   The OEIS entry:   A098550 The Yellowstone permutation.   Applegate et al, 2015: The Yellowstone Permutation [1].
#AutoHotkey
AutoHotkey
A := [], in_seq := [] loop 30 { n := A_Index if n <=3 A[n] := n, in_seq[n] := true else while true { s := A_Index if !in_seq[s] && relatively_prime(s, A[n-1]) && !relatively_prime(s, A[n-2]) { A[n] := s in_seq[s] := true break } } } for i, v in A result .= v "," MsgBox % result := "[" Trim(result, ",") "]" return ;-------------------------------------- relatively_prime(a, b){ return (GCD(a, b) = 1) } ;-------------------------------------- GCD(a, b) { while b b := Mod(a | 0x0, a := b) return a }
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The expression will be a string or list of symbols like "(1+3)*7". The four symbols + - * / must be supported as binary operators with conventional precedence rules. Precedence-control parentheses must also be supported. Note For those who don't remember, mathematical precedence is as follows: Parentheses Multiplication/Division (left to right) Addition/Subtraction (left to right) C.f 24 game Player. Parsing/RPN calculator algorithm. Parsing/RPN to infix conversion.
#Racket
Racket
#lang racket   (require parser-tools/yacc parser-tools/lex (prefix-in ~ parser-tools/lex-sre))   (define-tokens value-tokens (NUM)) (define-empty-tokens op-tokens (OPEN CLOSE + - * / EOF NEG))   (define lex (lexer [(eof) 'EOF] [whitespace (lex input-port)] [(~or "+" "-" "*" "/") (string->symbol lexeme)] ["(" 'OPEN] [")" 'CLOSE] [(~: (~+ numeric) (~? (~: #\. (~* numeric)))) (token-NUM (string->number lexeme))]))   (define parse (parser [start E] [end EOF] [tokens value-tokens op-tokens] [error void] [precs (left - +) (left * /) (left NEG)] [grammar (E [(NUM) $1] [(E + E) (+ $1 $3)] [(E - E) (- $1 $3)] [(E * E) (* $1 $3)] [(E / E) (/ $1 $3)] [(- E) (prec NEG) (- $2)] [(OPEN E CLOSE) $2])]))   (define (calc str) (define i (open-input-string str)) (displayln (parse (λ () (lex i)))))   (calc "(1 + 2 * 3) - (1+2)*-3")
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.
#Raku
Raku
sub ev (Str $s --> Numeric) {   grammar expr { token TOP { ^ <sum> $ } token sum { <product> (('+' || '-') <product>)* } token product { <factor> (('*' || '/') <factor>)* } token factor { <unary_minus>? [ <parens> || <literal> ] } token unary_minus { '-' } token parens { '(' <sum> ')' } token literal { \d+ ['.' \d+]? || '.' \d+ } }   my sub minus ($b) { $b ?? -1 !! +1 }   my sub sum ($x) { [+] flat product($x<product>), map { minus($^y[0] eq '-') * product $^y<product> }, |($x[0] or []) }   my sub product ($x) { [*] flat factor($x<factor>), map { factor($^y<factor>) ** minus($^y[0] eq '/') }, |($x[0] or []) }   my sub factor ($x) { minus($x<unary_minus>) * ($x<parens> ?? sum $x<parens><sum> !! $x<literal>) }   expr.parse([~] split /\s+/, $s); $/ or fail 'No parse.'; sum $/<sum>;   }   # Testing:   say ev '5'; # 5 say ev '1 + 2 - 3 * 4 / 5'; # 0.6 say ev '1 + 5*3.4 - .5 -4 / -2 * (3+4) -6'; # 25.5 say ev '((11+15)*15)* 2 + (3) * -4 *1'; # 768
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.
#Julia
Julia
import Base.*, Base.+, Base.-, Base./, Base.show, Base.!=, Base.==, Base.<=, Base.<, Base.>, Base.>=, Base.divrem   const z0 = "0" const z1 = "1" const flipordered = (z1 < z0)   mutable struct Z s::String end Z() = Z(z0) Z(z::Z) = Z(z.s)   pairlen(x::Z, y::Z) = max(length(x.s), length(y.s)) tolen(x::Z, n::Int) = (s = x.s; while length(s) < n s = z0 * s end; s)   <(x::Z, y::Z) = (l = pairlen(x, y); flipordered ? tolen(x, l) > tolen(y, l) : tolen(x, l) < tolen(y, l)) >(x::Z, y::Z) = (l = pairlen(x, y); flipordered ? tolen(x, l) < tolen(y, l) : tolen(x, l) > tolen(y, l)) ==(x::Z, y::Z) = (l = pairlen(x, y); tolen(x, l) == tolen(y, l)) <=(x::Z, y::Z) = (l = pairlen(x, y); flipordered ? tolen(x, l) >= tolen(y, l) : tolen(x, l) <= tolen(y, l)) >=(x::Z, y::Z) = (l = pairlen(x, y); flipordered ? tolen(x, l) <= tolen(y, l) : tolen(x, l) >= tolen(y, l)) !=(x::Z, y::Z) = (l = pairlen(x, y); tolen(x, l) != tolen(y, l))   function tocanonical(z::Z) while occursin(z0 * z1 * z1, z.s) z.s = replace(z.s, z0 * z1 * z1 => z1 * z0 * z0) end len = length(z.s) if len > 1 && z.s[1:2] == z1 * z1 z.s = z1 * z0 * z0 * ((len > 2) ? z.s[3:end] : "") end while (len = length(z.s)) > 1 && string(z.s[1]) == z0 if len == 2 if z.s == z0 * z0 z.s = z0 elseif z.s == z0 * z1 z.s = z1 end else z.s = z.s[2:end] end end z end   function inc(z) if z.s[end] == z0[1] z.s = z.s[1:end-1] * z1[1] elseif z.s[end] == z1[1] if length(z.s) > 1 if z.s[end-1:end] == z0 * z1 z.s = z.s[1:end-2] * z1 * z0 end else z.s = z1 * z0 end end tocanonical(z) end   function dec(z) if z.s[end] == z1[1] z.s = z.s[1:end-1] * z0 else if (m = match(Regex(z1 * z0 * '+' * '$'), z.s)) != nothing len = length(m.match) if iseven(len) z.s = z.s[1:end-len] * (z0 * z1) ^ div(len, 2) else z.s = z.s[1:end-len] * (z0 * z1) ^ div(len, 2) * z0 end end end tocanonical(z) z end   function +(x::Z, y::Z) a = Z(x.s) b = Z(y.s) while b.s != z0 inc(a) dec(b) end a end   function -(x::Z, y::Z) a = Z(x.s) b = Z(y.s) while b.s != z0 dec(a) dec(b) end a end   function *(x::Z, y::Z) if (x.s == z0) || (y.s == z0) return Z(z0) elseif x.s == z1 return Z(y.s) elseif y.s == z1 return Z(x.s) end a = Z(x.s) b = Z(z1) while b != y c = Z(z0) while c != x inc(a) inc(c) end inc(b) end a end   function divrem(x::Z, y::Z) if y.s == z0 throw("Zeckendorf division by 0") elseif (y.s == z1) || (x.s == z0) return Z(x.s) end a = Z(x.s) b = Z(y.s) c = Z(z0) while a > b a = a - b inc(c) end tocanonical(c), tocanonical(a) end   function /(x::Z, y::Z) a, _ = divrem(x, y) a end   show(io::IO, z::Z) = show(io, parse(BigInt, tocanonical(z).s))   function zeckendorftest() a = Z("10") b = Z("1001") c = Z("1000") d = Z("10101")   println("Addition:") x = a println(x += a) println(x += a) println(x += b) println(x += c) println(x += d)   println("\nSubtraction:") x = Z("1000") println(x - Z("101")) x = Z("10101010") println(x - Z("1010101"))   println("\nMultiplication:") x = Z("1001") y = Z("101") println(x * y) println(Z("101010") * y)   println("\nDivision:") x = Z("1000101") y = Z("101") println(x / y) println(divrem(x, y)) end   zeckendorftest()  
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.
#Kotlin
Kotlin
// version 1.1.51   class Zeckendorf(x: String = "0") : Comparable<Zeckendorf> {   var dVal = 0 var dLen = 0   private fun a(n: Int) { var i = n while (true) { if (dLen < i) dLen = i val j = (dVal shr (i * 2)) and 3 when (j) { 0, 1 -> return   2 -> { if (((dVal shr ((i + 1) * 2)) and 1) != 1) return dVal += 1 shl (i * 2 + 1) return }   3 -> { dVal = dVal and (3 shl (i * 2)).inv() b((i + 1) * 2) } } i++ } }   private fun b(pos: Int) { if (pos == 0) { var thiz = this ++thiz return } if (((dVal shr pos) and 1) == 0) { dVal += 1 shl pos a(pos / 2) if (pos > 1) a(pos / 2 - 1) } else { dVal = dVal and (1 shl pos).inv() b(pos + 1) b(pos - (if (pos > 1) 2 else 1)) } }   private fun c(pos: Int) { if (((dVal shr pos) and 1) == 1) { dVal = dVal and (1 shl pos).inv() return } c(pos + 1) if (pos > 0) b(pos - 1) else { var thiz = this; ++thiz } }   init { var q = 1 var i = x.length - 1 dLen = i / 2 while (i >= 0) { dVal += (x[i] - '0').toInt() * q q *= 2 i-- } }   operator fun inc(): Zeckendorf { dVal += 1 a(0) return this }   operator fun plusAssign(other: Zeckendorf) { for (gn in 0 until (other.dLen + 1) * 2) { if (((other.dVal shr gn) and 1) == 1) b(gn) } }   operator fun minusAssign(other: Zeckendorf) { for (gn in 0 until (other.dLen + 1) * 2) { if (((other.dVal shr gn) and 1) == 1) c(gn) } while ((((dVal shr dLen * 2) and 3) == 0) || (dLen == 0)) dLen-- }   operator fun timesAssign(other: Zeckendorf) { var na = other.copy() var nb = other.copy() var nt: Zeckendorf var nr = "0".Z for (i in 0..(dLen + 1) * 2) { if (((dVal shr i) and 1) > 0) nr += nb nt = nb.copy() nb += na na = nt.copy() } dVal = nr.dVal dLen = nr.dLen }   override operator fun compareTo(other: Zeckendorf) = dVal.compareTo(other.dVal)   override fun toString(): String { if (dVal == 0) return "0" val sb = StringBuilder(dig1[(dVal shr (dLen * 2)) and 3]) for (i in dLen - 1 downTo 0) { sb.append(dig[(dVal shr (i * 2)) and 3]) } return sb.toString() }   fun copy(): Zeckendorf { val z = "0".Z z.dVal = dVal z.dLen = dLen return z }   companion object { val dig = listOf("00", "01", "10") val dig1 = listOf("", "1", "10") } }   val String.Z get() = Zeckendorf(this)   fun main(args: Array<String>) { println("Addition:") var g = "10".Z g += "10".Z println(g) g += "10".Z println(g) g += "1001".Z println(g) g += "1000".Z println(g) g += "10101".Z println(g) println("\nSubtraction:") g = "1000".Z g -= "101".Z println(g) g = "10101010".Z g -= "1010101".Z println(g) println("\nMultiplication:") g = "1001".Z g *= "101".Z println(g) g = "101010".Z g += "101".Z println(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
#jq
jq
# The factors, sorted def factors: . as $num | reduce range(1; 1 + sqrt|floor) as $i ([]; if ($num % $i) == 0 then ($num / $i) as $r | if $i == $r then . + [$i] else . + [$i, $r] end else . end | sort) ;   # If the input is a sorted array of distinct non-negative integers, # then the output will be a stream of [$x,$y] arrays, # where $x and $y are non-empty arrays that partition the # input, and where ($x|add) == $sum. # If [$x,$y] is emitted, then [$y,$x] will not also be emitted. # The items in $x appear in the same order as in the input, and similarly # for $y. # def distinct_partitions($sum): # input: [$array, $n, $lim] where $n>0 # output: a stream of arrays, $a, each with $n distinct items from $array, # preserving the order in $array, and such that # add == $lim def p: . as [$in, $n, $lim] | if $n==1 # this condition is very common so it saves time to check early on then ($in | bsearch($lim)) as $ix | if $ix < 0 then empty else [$lim] end else ($in|length) as $length | if $length <= $n then empty elif $length==$n then $in | select(add == $lim) elif ($in[-$n:]|add) < $lim then empty else ($in[:$n]|add) as $rsum | if $rsum > $lim then empty elif $rsum == $lim then "amazing" | debug | $in[:$n] else range(0; 1 + $length - $n) as $i | [$in[$i]] + ([$in[$i+1:], $n-1, $lim - $in[$i]]|p) end end end;   range(1; (1+length)/2) as $i | ([., $i, $sum]|p) as $pi | [ $pi, (. - $pi)] | select( if (.[0]|length) == (.[1]|length) then (.[0] < .[1]) else true end) #1  ;   def zumkellerPartitions: factors | add as $sum | if $sum % 2 == 1 then empty else distinct_partitions($sum / 2) end;   def is_zumkeller: first(factors | add as $sum | if $sum % 2 == 1 then empty else distinct_partitions($sum / 2) | select( (.[0]|add) == (.[1]|add)) // ("internal error: \(.)" | debug | empty) #2 end | true) // false;
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
#Julia
Julia
using Primes   function factorize(n) f = [one(n)] for (p, x) in factor(n) f = reduce(vcat, [f*p^i for i in 1:x], init=f) end f end   function cansum(goal, list) if goal == 0 || list[1] == goal return true elseif length(list) > 1 if list[1] > goal return cansum(goal, list[2:end]) else return cansum(goal - list[1], list[2:end]) || cansum(goal, list[2:end]) end end return false end   function iszumkeller(n) f = reverse(factorize(n)) fsum = sum(f) return iseven(fsum) && cansum(div(fsum, 2) - f[1], f[2:end]) end   function printconditionalnum(condition, maxcount, numperline = 20) count, spacing = 1, div(80, numperline) for i in 1:typemax(Int) if condition(i) count += 1 print(rpad(i, spacing), (count - 1) % numperline == 0 ? "\n" : "") if count > maxcount return end end end end   println("First 220 Zumkeller numbers:") printconditionalnum(iszumkeller, 220) println("\n\nFirst 40 odd Zumkeller numbers:") printconditionalnum((n) -> isodd(n) && iszumkeller(n), 40, 8) println("\n\nFirst 40 odd Zumkeller numbers not ending with 5:") printconditionalnum((n) -> isodd(n) && (string(n)[end] != '5') && iszumkeller(n), 40, 8)  
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
#Common_Lisp
Common Lisp
(let ((s (format () "~s" (expt 5 (expt 4 (expt 3 2)))))) (format t "~a...~a, length ~a" (subseq s 0 20) (subseq s (- (length s) 20)) (length s)))
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
#D
D
void main() { import std.stdio, std.bigint, std.conv;   auto s = text(5.BigInt ^^ 4 ^^ 3 ^^ 2); writefln("5^4^3^2 = %s..%s (%d digits)", s[0..20], s[$-20..$], s.length); }
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
#Julia
Julia
  const pixelstring = "00000000000000000000000000000000" * "01111111110000000111111110000000" * "01110001111000001111001111000000" * "01110000111000001110000111000000" * "01110001111000001110000000000000" * "01111111110000001110000000000000" * "01110111100000001110000111000000" * "01110011110011101111001111011100" * "01110001111011100111111110011100" * "00000000000000000000000000000000" const pixels = reshape([UInt8(c- 48) for c in pixelstring], (32,10))'     function surroundtesting(px, i, j, step) if px[i,j] == 0 return false end isize, jsize = size(px) if i < 1 || j < 1 || i == isize || j == jsize # criteria 0.both return false end s = Array{Int,1}(9) s[1] = s[9] = px[i-1,j]; s[2] = px[i-1,j+1]; s[3] = px[i,j+1]; s[4] = px[i+1,j+1] s[5] = px[i+1,j]; s[6] = px[i+1,j-1]; s[7] = px[i,j-1]; s[8] = px[i-1,j-1] b = sum(s[1:8]) if b < 2 || b > 6 # criteria 1.both return false end if sum([(s[i] == 0 && s[i+1] == 1) for i in 1:length(s)-1]) != 1 # criteria 2.both return false end if step == 1 rightwhite = s[1] == 0 || s[3] == 0 || s[5] == 0 # 1.3 downwhite = s[3] == 0 || s[5] == 0 || s[7] == 0 # 1.4 return rightwhite && downwhite end upwhite = s[1] == 0 || s[3] == 0 || s[7] == 0 # 2.3 leftwhite = s[1] == 0 || s[5] == 0 || s[7] == 0 # 2.4 return upwhite && leftwhite end     function zsthinning(mat) retmat = copy(mat) testmat = zeros(Int, size(mat)) isize, jsize = size(testmat) needredo = true loops = 0 while(needredo) loops += 1 println("loop number $loops") needredo = false for n in 1:2 for i in 1:isize, j in 1:jsize testmat[i,j] = surroundtesting(retmat, i, j, n) ? 1 : 0 end for i in 1:isize, j in 1:jsize if testmat[i,j] == 1 retmat[i,j] = 0 needredo = true end end end end retmat end     function asciiprint(mat) for i in 1:size(mat)[1] println(join(map(i -> i == 1 ? '#' : ' ', mat[i,:]))) end end     asciiprint(zsthinning(pixels))
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
#Elena
Elena
import system'routines; import system'collections; import system'text; import extensions; extension op { fibonacci() { if (self < 2) { ^ self } else { ^ (self - 1).fibonacci() + (self - 2).fibonacci() }; }   zeckendorf() { var fibonacciNumbers := new List<int>();   int num := self; int fibPosition := 2; int currentFibonaciNum := fibPosition.fibonacci();   while (currentFibonaciNum <= num) { fibonacciNumbers.append:currentFibonaciNum;   fibPosition := fibPosition + 1; currentFibonaciNum := fibPosition.fibonacci() };   auto output := new TextBuilder(); int temp := num;   fibonacciNumbers.sequenceReverse().forEach:(item) { if (item <= temp) { output.write("1"); temp := temp - item } else { output.write("0") } };   ^ output.Value } }   public program() { for(int i := 1, i <= 20, i += 1) { console.printFormatted("{0} : {1}",i,i.zeckendorf()).writeLine() };   console.readChar() }
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.
#BQN
BQN
swch ← ≠´{100⥊1«𝕩⥊0}¨1+↕100 ¯1↓∾{𝕩∾@+10}¨•Fmt¨⟨swch,/swch⟩
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)
#Elena
Elena
var staticArray := new int[]{1, 2, 3};
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Perl
Perl
use Math::Complex; my $a = 1 + 1*i; my $b = 3.14159 + 1.25*i;   print "$_\n" foreach $a + $b, # addition $a * $b, # multiplication -$a, # negation 1 / $a, # multiplicative inverse ~$a; # complex conjugate
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
#Racket
Racket
  -> (* 1/7 14) 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
#SQL
SQL
WITH rec (rn, a, g, diff) AS ( SELECT 1, 1, 1/SQRT(2), 1 - 1/SQRT(2) FROM dual UNION ALL SELECT rn + 1, (a + g)/2, SQRT(a * g), (a + g)/2 - SQRT(a * g) FROM rec WHERE diff > 1e-38 ) SELECT * FROM rec WHERE diff <= 1e-38 ;
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
#Standard_ML
Standard ML
  fun agm(a, g) = let fun agm'(a, g, eps) = if Real.abs(a-g) < eps then a else agm'((a+g)/2.0, Math.sqrt(a*g), eps) in agm'(a, g, 1e~15) end;  
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
#Go
Go
package main   import ( "fmt" "math" "math/big" "math/cmplx" )   func main() { fmt.Println("float64: ", math.Pow(0, 0)) var b big.Int fmt.Println("big integer:", b.Exp(&b, &b, nil)) fmt.Println("complex: ", cmplx.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
#Groovy
Groovy
println 0**0
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Agena
Agena
# zig-zag matrix   makeZigZag := proc( n :: number ) :: table is   local move := proc( x :: number, y :: number, upRight :: boolean ) is if y = n then upRight := not upRight; x := x + 1 elif x = 1 then upRight := not upRight; y := y + 1 else x := x - 1; y := y + 1 fi; return x, y, upRight end ;   # create empty table local result := []; for i to n do result[ i ] := []; for j to n do result[ i, j ] := 0 od od;   # fill the table local x, y, upRight := 1, 1, true; for i to n * n do result[ x, y ] := i - 1; if upRight then x, y, upRight := move( x, y, upRight ) else y, x, upRight := move( y, x, upRight ) fi od;   return result end;   scope local m := makeZigZag( 5 ); for i to size m do for j to size m do printf( " %3d", m[ i, j ] ) od; print() od epocs
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. Example a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). Task Find and show as output the first  30  Yellowstone numbers. Extra Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. Related tasks   Greatest common divisor.   Plot coordinate pairs. See also   The OEIS entry:   A098550 The Yellowstone permutation.   Applegate et al, 2015: The Yellowstone Permutation [1].
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h>   typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode;   Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; }   void free_lnode(Lnode *node) { if (node == NULL) { return; }   node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; }   typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List;   List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; }   void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; }   void list_insert(List *list, int v) { Lnode *node;   if (list == NULL) { return; }   node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } }   void list_print(List *list) { Lnode *it;   if (list == NULL) { return; }   for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } }   int list_get(List *list, int idx) { Lnode *it = NULL;   if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } }   if (it == NULL) { return INT_MIN; } return it->v; }   ///////////////////////////////////////   typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode;   Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; }   void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; }   typedef struct map_t { Mnode *front; } Map;   Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; }   void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; }   void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } }   bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; }   ///////////////////////////////////////   int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; }   List *yellow(size_t n) { List *a; Map *b; int i;   a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3);   b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true);   i = 4;   while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; }   free_map(b); return a; }   int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 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.
#REXX
REXX
/*REXX program evaluates an infix─type arithmetic expression and displays the result.*/ nchars = '0123456789.eEdDqQ' /*possible parts of a number, sans ± */ e='***error***'; $=" "; doubleOps= '&|*/'; z= /*handy─dandy variables.*/ parse arg x 1 ox1; if x='' then call serr "no input was specified." x=space(x); L=length(x); x=translate(x, '()()', "[]{}") j=0 do forever; j=j+1; if j>L then leave; _=substr(x, j, 1); _2=getX() newT=pos(_,' ()[]{}^÷')\==0; if newT then do; z=z _ $; iterate; end possDouble=pos(_,doubleOps)\==0 /*is _ a possible double operator?*/ if possDouble then do /* " this " " " " */ if _2==_ then do /*yupper, it's one of a double operator*/ _=_ || _ /*create and use a double char operator*/ x=overlay($, x, Nj) /*blank out 2nd symbol.*/ end z=z _ $; iterate end if _=='+' | _=="-" then do; p_=word(z, max(1,words(z))) /*last Z token. */ if p_=='(' then z=z 0 /*handle a unary ± */ z=z _ $; iterate end lets=0; sigs=0; #=_   do j=j+1 to L; _=substr(x,j,1) /*build a valid number.*/ if lets==1 & sigs==0 then if _=='+' | _=="-" then do; sigs=1 #=# || _ iterate end if pos(_,nchars)==0 then leave lets=lets+datatype(_,'M') /*keep track of the number of exponents*/ #=# || translate(_,'EEEEE', "eDdQq") /*keep building the number. */ end /*j*/ j=j-1 if \datatype(#,'N') then call serr "invalid number: " # z=z # $ end /*forever*/   _=word(z,1); if _=='+' | _=="-" then z=0 z /*handle the unary cases. */ x='(' space(z) ")"; tokens=words(x) /*force stacking for the expression. */ do i=1 for tokens; @.i=word(x,i); end /*i*/ /*assign input tokens. */ L=max(20,length(x)) /*use 20 for the minimum display width.*/ op= ')(-+/*^'; Rop=substr(op,3); p.=; s.=; n=length(op); epr=; stack=   do i=1 for n; _=substr(op,i,1); s._=(i+1)%2; p._=s._ + (i==n); end /*i*/ /* [↑] assign the operator priorities.*/ do #=1 for tokens;  ?=@.# /*process each token from the @. list.*/ if ?=='**' then ?="^" /*convert to REXX-type exponentiation. */ select /*@.# is: ( operator ) operand*/ when ?=='(' then stack="(" stack when isOp(?) then do /*is the token an operator ? */  !=word(stack,1) /*get token from stack.*/ do while !\==')' & s.!>=p.?; epr=epr ! /*addition.*/ stack=subword(stack, 2) /*del token from stack*/  != word(stack, 1) /*get token from stack*/ end /*while*/ stack=? stack /*add token to stack*/ end when ?==')' then do;  !=word(stack, 1) /*get token from stack*/ do while !\=='('; epr=epr ! /*append to expression*/ stack=subword(stack, 2) /*del token from stack*/  != word(stack, 1) /*get token from stack*/ end /*while*/ stack=subword(stack, 2) /*del token from stack*/ end otherwise epr=epr ? /*add operand to epr.*/ end /*select*/ end /*#*/   epr=space(epr stack); tokens=words(epr); x=epr; z=; stack= do i=1 for tokens; @.i=word(epr,i); end /*i*/ /*assign input tokens.*/ Dop='/ // % ÷'; Bop="& | &&" /*division operands; binary operands.*/ Aop='- + * ^ **' Dop Bop; Lop=Aop "||" /*arithmetic operands; legal operands.*/   do #=1 for tokens;  ?=@.#;  ??=? /*process each token from @. list. */ w=words(stack); b=word(stack, max(1, w ) ) /*stack count; the last entry. */ a=word(stack, max(1, w-1) ) /*stack's "first" operand. */ division =wordpos(?, Dop)\==0 /*flag: doing a division operation. */ arith =wordpos(?, Aop)\==0 /*flag: doing arithmetic operation. */ bitOp =wordpos(?, Bop)\==0 /*flag: doing binary mathematics. */ if datatype(?, 'N') then do; stack=stack ?; iterate; end if wordpos(?,Lop)==0 then do; z=e "illegal operator:" ?; leave; end if w<2 then do; z=e "illegal epr expression."; leave; end if ?=='^' then ??="**" /*REXXify ^ ──► ** (make it legal).*/ if ?=='÷' then ??="/" /*REXXify ÷ ──► / (make it legal).*/ if division & b=0 then do; z=e "division by zero" b; leave; end if bitOp & \isBit(a) then do; z=e "token isn't logical: " a; leave; end if bitOp & \isBit(b) then do; z=e "token isn't logical: " b; leave; end select /*perform an arithmetic operation. */ when ??=='+' then y = a + b when ??=='-' then y = a - b when ??=='*' then y = a * b when ??=='/' | ??=="÷" then y = a / b when ??=='//' then y = a // b when ??=='%' then y = a % b when ??=='^' | ??=="**" then y = a ** b when ??=='||' then y = a || b otherwise z=e 'invalid operator:' ?; leave end /*select*/ if datatype(y, 'W') then y=y/1 /*normalize the number with ÷ by 1. */ _=subword(stack, 1, w-2); stack=_ y /*rebuild the stack with the answer. */ end /*#*/   if word(z, 1)==e then stack= /*handle the special case of errors. */ z=space(z stack) /*append any residual entries. */ say 'answer──►' z /*display the answer (result). */ parse source upper . how . /*invoked via C.L. or REXX program ? */ if how=='COMMAND' | \datatype(z, 'W') then exit /*stick a fork in it, we're all done. */ return z /*return Z ──► invoker (the RESULT). */ /*──────────────────────────────────────────────────────────────────────────────────────*/ isBit: return arg(1)==0 | arg(1) == 1 /*returns 1 if 1st argument is binary*/ isOp: return pos(arg(1), rOp) \== 0 /*is argument 1 a "real" operator? */ serr: say; say e arg(1); say; exit 13 /*issue an error message with some text*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ getX: do Nj=j+1 to length(x); _n=substr(x, Nj, 1); if _n==$ then iterate return substr(x, Nj, 1) /* [↑] ignore any blanks in expression*/ end /*Nj*/ return $ /*reached end-of-tokens, return $. */
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.
#Nim
Nim
type Zeckendorf = object dVal: Natural dLen: Natural   const Dig = ["00", "01", "10"] Dig1 = ["", "1", "10"]   # Forward references. func b(z: var Zeckendorf; pos: Natural) func inc(z: var Zeckendorf)     func a(z: var Zeckendorf; n: Natural) = var i = n while true:   if z.dLen < i: z.dLen = i let j = z.dVal shr (i * 2) and 3   case j of 0, 1: return of 2: if (z.dVal shr ((i + 1) * 2) and 1) != 1: return z.dVal += 1 shl (i * 2 + 1) return of 3: z.dVal = z.dVal and not (3 shl (i * 2)) z.b((i + 1) * 2) else: assert(false)   inc i     func b(z: var Zeckendorf; pos: Natural) = if pos == 0: inc z return   if (z.dVal shr pos and 1) == 0: z.dVal += 1 shl pos z.a(pos div 2) if pos > 1: z.a(pos div 2 - 1) else: z.dVal = z.dVal and not(1 shl pos) z.b(pos + 1) z.b(pos - (if pos > 1: 2 else: 1))     func c(z: var Zeckendorf; pos: Natural) = if (z.dVal shr pos and 1) == 1: z.dVal = z.dVal and not(1 shl pos) return   z.c(pos + 1) if pos > 0: z.b(pos - 1) else: inc z     func initZeckendorf(s = "0"): Zeckendorf = var q = 1 var i = s.high result.dLen = i div 2 while i >= 0: result.dVal += (ord(s[i]) - ord('0')) * q q *= 2 dec i     func inc(z: var Zeckendorf) = inc z.dVal z.a(0)     func `+=`(z1: var Zeckendorf; z2: Zeckendorf) = for gn in 0 .. (2 * z2.dLen + 1): if (z2.dVal shr gn and 1) == 1: z1.b(gn)     func `-=`(z1: var Zeckendorf; z2: Zeckendorf) = for gn in 0 .. (2 * z2.dLen + 1): if (z2.dVal shr gn and 1) == 1: z1.c(gn)   while z1.dLen > 0 and (z1.dVal shr (z1.dLen * 2) and 3) == 0: dec z1.dLen     func `*=`(z1: var Zeckendorf; z2: Zeckendorf) = var na, nb = z2 var nr: Zeckendorf for i in 0 .. (z1.dLen + 1) * 2: if (z1.dVal shr i and 1) > 0: nr += nb let nt = nb nb += na na = nt z1 = nr   func`$`(z: var Zeckendorf): string = if z.dVal == 0: return "0" result.add Dig1[z.dVal shr (z.dLen * 2) and 3] for i in countdown(z.dLen - 1, 0): result.add Dig[z.dVal shr (i * 2) and 3]   when isMainModule:   var g: Zeckendorf   echo "Addition:" g = initZeckendorf("10") g += initZeckendorf("10") echo g g += initZeckendorf("10") echo g g += initZeckendorf("1001") echo g g += initZeckendorf("1000") echo g g += initZeckendorf("10101") echo g     echo "\nSubtraction:" g = initZeckendorf("1000") g -= initZeckendorf("101") echo g g = initZeckendorf("10101010") g -= initZeckendorf("1010101") echo g   echo "\nMultiplication:" g = initZeckendorf("1001") g *= initZeckendorf("101") echo g g = initZeckendorf("101010") g += initZeckendorf("101") echo 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
#Kotlin
Kotlin
import java.util.ArrayList import kotlin.math.sqrt   object ZumkellerNumbers { @JvmStatic fun main(args: Array<String>) { var n = 1 println("First 220 Zumkeller numbers:") run { var count = 1 while (count <= 220) { if (isZumkeller(n)) { print("%3d ".format(n)) if (count % 20 == 0) { println() } count++ } n += 1 } }   n = 1 println("\nFirst 40 odd Zumkeller numbers:") run { var count = 1 while (count <= 40) { if (isZumkeller(n)) { print("%6d".format(n)) if (count % 10 == 0) { println() } count++ } n += 2 } }   n = 1 println("\nFirst 40 odd Zumkeller numbers that do not end in a 5:") var count = 1 while (count <= 40) { if (n % 5 != 0 && isZumkeller(n)) { print("%8d".format(n)) if (count % 10 == 0) { println() } count++ } n += 2 } }   private fun isZumkeller(n: Int): Boolean { // numbers congruent to 6 or 12 modulo 18 are Zumkeller numbers if (n % 18 == 6 || n % 18 == 12) { return true } val divisors = getDivisors(n) val divisorSum = divisors.stream().mapToInt { i: Int? -> i!! }.sum() // divisor sum cannot be odd if (divisorSum % 2 == 1) { return false } // numbers where n is odd and the abundance is even are Zumkeller numbers val abundance = divisorSum - 2 * n if (n % 2 == 1 && abundance > 0 && abundance % 2 == 0) { return true } divisors.sort() val j = divisors.size - 1 val sum = divisorSum / 2 // Largest divisor larger than sum - then cannot partition and not Zumkeller number return if (divisors[j] > sum) false else canPartition(j, divisors, sum, IntArray(2)) }   private fun canPartition(j: Int, divisors: List<Int>, sum: Int, buckets: IntArray): Boolean { if (j < 0) { return true } for (i in 0..1) { if (buckets[i] + divisors[j] <= sum) { buckets[i] += divisors[j] if (canPartition(j - 1, divisors, sum, buckets)) { return true } buckets[i] -= divisors[j] } if (buckets[i] == 0) { break } } return false }   private fun getDivisors(number: Int): MutableList<Int> { val divisors: MutableList<Int> = ArrayList() val sqrt = sqrt(number.toDouble()).toLong() for (i in 1..sqrt) { if (number % i == 0L) { divisors.add(i.toInt()) val div = (number / i).toInt() if (div.toLong() != i) { divisors.add(div) } } } return divisors } }
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
#Dart
Dart
import 'dart:math' show pow;   int fallingPowers(int base) => base == 1 ? 1 : pow(base, fallingPowers(base - 1));   void main() { final exponent = fallingPowers(4), s = BigInt.from(5).pow(exponent).toString(); print('First twenty: ${s.substring(0, 20)}'); print('Last twenty: ${s.substring(s.length - 20)}'); print('Number of digits: ${s.length}');  
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
#dc
dc
[5432.dc]sz   5 4 3 2 ^ ^ ^ sy [y = 5 ^ 4 ^ 3 ^ 2]sz ly Z sc [c = length of y]sz [ First 20 digits: ]P ly 10 lc 20 - ^ / p sz [y / (10 ^ (c - 20))]sz [ Last 20 digits: ]P ly 10 20 ^ % p sz [y % (10 ^ 20)]sz [Number of digits: ]P lc p sz
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
#Kotlin
Kotlin
// version 1.1.2   class Point(val x: Int, val y: Int)   val image = arrayOf( " ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " " )   val nbrs = arrayOf( intArrayOf( 0, -1), intArrayOf( 1, -1), intArrayOf( 1, 0), intArrayOf( 1, 1), intArrayOf( 0, 1), intArrayOf(-1, 1), intArrayOf(-1, 0), intArrayOf(-1, -1), intArrayOf( 0, -1) )   val nbrGroups = arrayOf( arrayOf(intArrayOf(0, 2, 4), intArrayOf(2, 4, 6)), arrayOf(intArrayOf(0, 2, 6), intArrayOf(0, 4, 6)) )   val toWhite = mutableListOf<Point>() val grid = Array(image.size) { image[it].toCharArray() }   fun thinImage() { var firstStep = false var hasChanged: Boolean do { hasChanged = false firstStep = !firstStep for (r in 1 until grid.size - 1) { for (c in 1 until grid[0].size - 1) { if (grid[r][c] != '#') continue val nn = numNeighbors(r, c) if (nn !in 2..6) continue if (numTransitions(r, c) != 1) continue val step = if (firstStep) 0 else 1 if (!atLeastOneIsWhite(r, c, step)) continue toWhite.add(Point(c, r)) hasChanged = true } } for (p in toWhite) grid[p.y][p.x] = ' ' toWhite.clear() } while (firstStep || hasChanged) for (row in grid) println(row) }   fun numNeighbors(r: Int, c: Int): Int { var count = 0 for (i in 0 until nbrs.size - 1) { if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++ } return count }   fun numTransitions(r: Int, c: Int): Int { var count = 0 for (i in 0 until nbrs.size - 1) { if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++ } } return count }   fun atLeastOneIsWhite(r: Int, c: Int, step: Int): Boolean { var count = 0; val group = nbrGroups[step] for (i in 0..1) { for (j in 0 until group[i].size) { val nbr = nbrs[group[i][j]] if (grid[r + nbr[1]][c + nbr[0]] == ' ') { count++ break } } } return count > 1 }   fun main(args: Array<String>) { thinImage() }
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
#Elixir
Elixir
defmodule Zeckendorf do def number do Stream.unfold(0, fn n -> zn_loop(n) end) end   defp zn_loop(n) do bin = Integer.to_string(n, 2) if String.match?(bin, ~r/11/), do: zn_loop(n+1), else: {bin, n+1} end end   Zeckendorf.number |> Enum.take(21) |> Enum.with_index |> Enum.each(fn {zn, i} -> IO.puts "#{i}: #{zn}" end)
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.
#C
C
#include <stdio.h>   int main() { char is_open[100] = { 0 }; int pass, door;   /* do the 100 passes */ for (pass = 0; pass < 100; ++pass) for (door = pass; door < 100; door += pass+1) is_open[door] = !is_open[door];   /* output the result */ for (door = 0; door < 100; ++door) printf("door #%d is %s.\n", door+1, (is_open[door]? "open" : "closed"));   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)
#Elixir
Elixir
ret = {:ok, "fun", 3.1415}
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.
#Phix
Phix
-- demo\rosetta\ArithComplex.exw with javascript_semantics include complex.e complex a = complex_new(1,1), -- (or just {1,1}) b = complex_new(3.14159,1.25), c = complex_new(1,0), d = complex_new(0,1) printf(1,"a = %s\n",{complex_sprint(a)}) printf(1,"b = %s\n",{complex_sprint(b)}) printf(1,"c = %s\n",{complex_sprint(c)}) printf(1,"d = %s\n",{complex_sprint(d)}) printf(1,"a+b = %s\n",{complex_sprint(complex_add(a,b))}) printf(1,"a*b = %s\n",{complex_sprint(complex_mul(a,b))}) printf(1,"1/a = %s\n",{complex_sprint(complex_inv(a))}) printf(1,"c/a = %s\n",{complex_sprint(complex_div(c,a))}) printf(1,"c-a = %s\n",{complex_sprint(complex_sub(c,a))}) printf(1,"d-a = %s\n",{complex_sprint(complex_sub(d,a))}) printf(1,"-a = %s\n",{complex_sprint(complex_neg(a))}) printf(1,"conj a = %s\n",{complex_sprint(complex_conjugate(a))})
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Raku
Raku
(2..2**19).hyper.map: -> $candidate { my $sum = 1 / $candidate; for 2 .. ceiling(sqrt($candidate)) -> $factor { if $candidate %% $factor { $sum += 1 / $factor + 1 / ($candidate / $factor); } } if $sum.nude[1] == 1 { say "Sum of reciprocal factors of $candidate = $sum exactly", ($sum == 1 ?? ", perfect!" !! "."); } }
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
#Stata
Stata
mata   real scalar agm(real scalar a, real scalar b) { real scalar c do { c=0.5*(a+b) b=sqrt(a*b) a=c } while (a-b>1e-15*a) return(0.5*(a+b)) }   agm(1,1/sqrt(2)) 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
#Swift
Swift
import Darwin   enum AGRError : Error { case undefined }   func agm(_ a: Double, _ g: Double, _ iota: Double = 1e-8) throws -> Double { var a = a var g = g var a1: Double = 0 var g1: Double = 0   guard a * g >= 0 else { throw AGRError.undefined }   while abs(a - g) > iota { a1 = (a + g) / 2 g1 = sqrt(a * g) a = a1 g = g1 }   return a }   do { try print(agm(1, 1 / sqrt(2))) } catch { print("agr is undefined when a * g < 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
#GW-BASIC
GW-BASIC
PRINT 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
#Haskell
Haskell
import Data.Complex   main = do print $ 0 ^ 0 print $ 0.0 ^ 0 print $ 0 ^^ 0 print $ 0 ** 0 print $ (0 :+ 0) ^ 0 print $ (0 :+ 0) ** (0 :+ 0)
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#ALGOL_68
ALGOL 68
PROC zig zag = (INT n)[,]INT: ( PROC move = (REF INT i, j)VOID: ( IF j < n THEN i := ( i <= 1 | 1 | i-1 ); j +:= 1 ELSE i +:= 1 FI );   [n, n]INT a; INT x:=LWB a, y:=LWB a;   FOR v FROM 0 TO n**2-1 DO a[y, x] := v; IF ODD (x + y) THEN move(x, y) ELSE move(y, x) FI OD; a );   INT dim = 5; #IF formatted transput possible THEN FORMAT d = $z-d$; FORMAT row = $"("n(dim-1)(f(d)",")f(d)")"$; FORMAT block = $"("n(dim-1)(f(row)","lx)f(row)")"l$;   printf((block, zig zag(dim))) ELSE# [,]INT result = zig zag(dim); FOR i TO dim DO print((result[i,], new line)) OD #FI#
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. Example a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). Task Find and show as output the first  30  Yellowstone numbers. Extra Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. Related tasks   Greatest common divisor.   Plot coordinate pairs. See also   The OEIS entry:   A098550 The Yellowstone permutation.   Applegate et al, 2015: The Yellowstone Permutation [1].
#C.2B.2B
C++
#include <iostream> #include <numeric> #include <set>   template <typename integer> class yellowstone_generator { public: integer next() { n2_ = n1_; n1_ = n_; if (n_ < 3) { ++n_; } else { for (n_ = min_; !(sequence_.count(n_) == 0 && std::gcd(n1_, n_) == 1 && std::gcd(n2_, n_) > 1); ++n_) {} } sequence_.insert(n_); for (;;) { auto it = sequence_.find(min_); if (it == sequence_.end()) break; sequence_.erase(it); ++min_; } return n_; } private: std::set<integer> sequence_; integer min_ = 1; integer n_ = 0; integer n1_ = 0; integer n2_ = 0; };   int main() { std::cout << "First 30 Yellowstone numbers:\n"; yellowstone_generator<unsigned int> ygen; std::cout << ygen.next(); for (int i = 1; i < 30; ++i) std::cout << ' ' << ygen.next(); std::cout << '\n'; return 0; }
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program yahoosearch64.s */   /* access RosettaCode.org and data extract */ /* use openssl for access to port 443 */ /* test openssl : package libssl-dev */ /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ TAILLEBUFFER, 500   .equ SSL_OP_NO_SSLv3, 0x02000000 .equ SSL_OP_NO_COMPRESSION, 0x00020000 .equ SSL_MODE_AUTO_RETRY, 0x00000004 .equ SSL_CTRL_MODE, 33   .equ BIO_C_SET_CONNECT, 100 .equ BIO_C_DO_STATE_MACHINE, 101 .equ BIO_C_SET_SSL, 109 .equ BIO_C_GET_SSL, 110   .equ LGBUFFERREQ, 512001   /*********************************/ /* Initialized data */ /*********************************/ .data szMessDebutPgm: .asciz "Début du programme. \n" szRetourLigne: .asciz "\n" szMessFinOK: .asciz "Fin normale du programme. \n" szMessErreur: .asciz "Erreur  !!!" szMessExtractArea: .asciz "Extraction = " szNomSite1: .asciz "search.yahoo.com:443" // host name and port szLibStart: .asciz ">Rosetta Code" // search string szNomrepCertif: .asciz "/pi/certificats" szRequete1: .asciz "GET /search?p=\"Rosettacode.org\"&b=1 HTTP/1.1 \r\nHost: search.yahoo.com\r\nConnection: keep-alive\r\nContent-Type: text/plain\r\n\r\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 sBufferreq: .skip LGBUFFERREQ szExtractArea: .skip TAILLEBUFFER stNewSSL: .skip 200 /*********************************/ /* code section */ /*********************************/ .text .global main main: ldr x0,qAdrszMessDebutPgm bl affichageMess // start message   /* connexion host port 443 and send query */ bl envoiRequete cmp x0,#-1 beq 99f // error ?   bl analyseReponse   ldr x0,qAdrszMessFinOK // end message bl affichageMess mov x0, #0 // return code ok b 100f 99: ldr x0,qAdrszMessErreur // error bl affichageMess mov x0, #1 // return code error b 100f 100: mov x8,EXIT // program end svc 0 // system call qAdrszMessDebutPgm: .quad szMessDebutPgm qAdrszMessFinOK: .quad szMessFinOK qAdrszMessErreur: .quad szMessErreur   /*********************************************************/ /* connexion host port 443 and send query */ /*********************************************************/ envoiRequete: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers //************************************* // openSsl functions use * //************************************* //init ssl bl OPENSSL_init_crypto bl ERR_load_BIO_strings mov x2, #0 mov x1, #0 mov x0, #2 bl OPENSSL_init_crypto mov x2, #0 mov x1, #0 mov x0, #0 bl OPENSSL_init_ssl cmp x0,#0 blt erreur bl TLS_client_method bl SSL_CTX_new cmp x0,#0 ble erreur mov x20,x0 // save contex ldr x1,iFlag bl SSL_CTX_set_options mov x0,x20 // contex mov x1,#0 ldr x2,qAdrszNomrepCertif bl SSL_CTX_load_verify_locations cmp x0,#0 ble erreur mov x0,x20 // contex bl BIO_new_ssl_connect cmp x0,#0 ble erreur mov x21,x0 // save bio mov x1,#BIO_C_GET_SSL mov x2,#0 ldr x3,qAdrstNewSSL bl BIO_ctrl ldr x0,qAdrstNewSSL ldr x0,[x0] mov x1,#SSL_CTRL_MODE mov x2,#SSL_MODE_AUTO_RETRY mov x3,#0 bl SSL_ctrl mov x0,x21 // bio mov x1,#BIO_C_SET_CONNECT mov x2,#0 ldr x3,qAdrszNomSite1 bl BIO_ctrl mov x0,x21 // bio mov x1,#BIO_C_DO_STATE_MACHINE mov x2,#0 mov x3,#0 bl BIO_ctrl // compute query length mov x2,#0 ldr x1,qAdrszRequete1 // query 1: ldrb w0,[x1,x2] cmp x0,#0 add x8,x2,1 csel x2,x8,x2,ne bne 1b // send query mov x0,x21 // bio // x1 = address query // x2 = length query mov x3,#0 bl BIO_write // send query cmp x0,#0 blt erreur ldr x22,qAdrsBufferreq // buffer address 2: // begin loop to read datas mov x0,x21 // bio mov x1,x22 // buffer address ldr x2,qLgBuffer mov x3,#0 bl BIO_read cmp x0,#0 ble 4f // error ou pb server add x22,x22,x0 sub x2,x22,#8 ldr x2,[x2] ldr x3,qCharEnd cmp x2,x3 // text end ? beq 4f mov x1,#0xFFFFFF // delay loop 3: subs x1,x1,1 bgt 3b b 2b // loop read other chunk 4: // read end //ldr x0,qAdrsBufferreq // to display buffer response of the query //bl affichageMess mov x0, x21 // close bio bl BIO_free_all mov x0,#0 b 100f erreur: // error display ldr x1,qAdrszMessErreur bl afficheErreur mov x0,#-1 // error code b 100f 100: 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 qAdrszRequete1: .quad szRequete1 qAdrsBufferreq: .quad sBufferreq iFlag: .quad SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION qAdrstNewSSL: .quad stNewSSL qAdrszNomSite1: .quad szNomSite1 qAdrszNomrepCertif: .quad szNomrepCertif qCharEnd: .quad 0x0A0D0A0D300A0D0A qLgBuffer: .quad LGBUFFERREQ - 1 /*********************************************************/ /* response analyze */ /*********************************************************/ analyseReponse: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers ldr x0,qAdrsBufferreq // buffer address ldr x1,qAdrszLibStart // key text address mov x2,#2 // occurence key text mov x3,#-11 // offset ldr x4,qAdrszExtractArea // address result area bl extChaine cmp x0,#-1 beq 99f ldr x0,qAdrszMessExtractArea bl affichageMess ldr x0,qAdrszExtractArea // résult display bl affichageMess ldr x0,qAdrszRetourLigne bl affichageMess b 100f 99: ldr x0,qAdrszMessErreur // error bl affichageMess mov x0, #-1 // error return code b 100f 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrszLibStart: .quad szLibStart qAdrszExtractArea: .quad szExtractArea qAdrszMessExtractArea: .quad szMessExtractArea qAdrszRetourLigne: .quad szRetourLigne /*********************************************************/ /* Text Extraction behind text key */ /*********************************************************/ /* x0 buffer address */ /* x1 key text to search */ /* x2 number occurences to key text */ /* x3 offset */ /* x4 result address */ extChaine: 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 x5,x0 // save buffer address mov x6,x1 // save key text // compute text length mov x8,#0 1: // loop ldrb w0,[x5,x8] // load a byte cmp x0,#0 // end ? add x9,x8,1 csel x8,x9,x8,ne bne 1b // no -> loop add x8,x8,x5 // compute text end   mov x7,#0 2: // compute length text key ldrb w0,[x6,x7] cmp x0,#0 add x9,x7,1 csel x7,x9,x7,ne bne 2b   3: // loop to search niéme(x2) key text mov x0,x5 mov x1,x6 bl rechercheSousChaine cmp x0,#0 blt 100f subs x2,x2,1 ble 31f add x5,x5,x0 add x5,x5,x7 b 3b 31: add x0,x0,x5 // add address text to index add x3,x3,x0 // add offset sub x3,x3,1 // and add length key text add x3,x3,x7 cmp x3,x8 // > at text end bge 98f mov x0,0 4: // character loop copy ldrb w2,[x3,x0] strb w2,[x4,x0] cbz x2,99f // text end ? return zero cmp x0,48 // extraction length beq 5f add x0,x0,1 b 4b // and loop 5: mov x2,0 // store final zéro strb w2,[x4,x0] add x0,x0,1 add x0,x0,x3 // x0 return the last position of extraction // it is possible o search another text b 100f 98: mov x0,-1 // error b 100f 99: mov x0,0 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 /******************************************************************/ /* search substring in string */ /******************************************************************/ /* x0 contains address string */ /* x1 contains address substring */ /* x0 return start index substring or -1 if not find */ rechercheSousChaine: 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 x2,#0 // index position string mov x3,#0 // index position substring mov x6,#-1 // search index ldrb w4,[x1,x3] // load first byte substring cbz x4,99f // zero final ? error 1: ldrb w5,[x0,x2] // load string byte cbz x5,99f // zero final ? yes -> not found cmp x5,x4 // compare character two strings beq 2f mov x6,-1 // not equal - > raz index mov x3,0 // and raz byte counter ldrb w4,[x1,x3] // and load byte add x2,x2,1 // and increment byte counter b 1b // and loop 2: // characters equal cmp x6,-1 // first character equal ? csel x6,x2,x6,eq // yes -> start index in x6 add x3,x3,1 // increment substring counter ldrb w4,[x1,x3] // and load next byte cbz x4,3f // zero final ? yes -> search end add x2,x2,1 // else increment string index b 1b // and loop 3: mov x0,x6 // return start index substring in the string b 100f 99: mov x0,-1 // not found 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 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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.
#Ruby
Ruby
$op_priority = {"+" => 0, "-" => 0, "*" => 1, "/" => 1}   class TreeNode OP_FUNCTION = { "+" => lambda {|x, y| x + y}, "-" => lambda {|x, y| x - y}, "*" => lambda {|x, y| x * y}, "/" => lambda {|x, y| x / y}} attr_accessor :info, :left, :right   def initialize(info) @info = info end   def leaf? @left.nil? and @right.nil? end   def to_s(order) if leaf? @info else left_s, right_s = @left.to_s(order), @right.to_s(order)   strs = case order when :prefix then [@info, left_s, right_s] when :infix then [left_s, @info, right_s] when :postfix then [left_s, right_s, @info] else [] end   "(" + strs.join(" ") + ")" end end   def eval if !leaf? and operator?(@info) OP_FUNCTION[@info].call(@left.eval, @right.eval) else @info.to_f end end end   def tokenize(exp) exp .gsub('(', ' ( ') .gsub(')', ' ) ') .gsub('+', ' + ') .gsub('-', ' - ') .gsub('*', ' * ') .gsub('/', ' / ') .split(' ') end   def operator?(token) $op_priority.has_key?(token) end   def pop_connect_push(op_stack, node_stack) temp = op_stack.pop temp.right = node_stack.pop temp.left = node_stack.pop node_stack.push(temp) end   def infix_exp_to_tree(exp) tokens = tokenize(exp) op_stack, node_stack = [], []   tokens.each do |token| if operator?(token) # clear stack of higher priority operators until (op_stack.empty? or op_stack.last.info == "(" or $op_priority[op_stack.last.info] < $op_priority[token]) pop_connect_push(op_stack, node_stack) end   op_stack.push(TreeNode.new(token)) elsif token == "(" op_stack.push(TreeNode.new(token)) elsif token == ")" while op_stack.last.info != "(" pop_connect_push(op_stack, node_stack) end   # throw away the '(' op_stack.pop else node_stack.push(TreeNode.new(token)) end end   until op_stack.empty? pop_connect_push(op_stack, node_stack) end   node_stack.last end
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.
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Zeckendorf_arithmetic use warnings;   for ( split /\n/, <<END ) # test cases 1 + 1 10 + 10 10100 + 1010 10100 - 1010 10100 * 1010 100010 * 100101 10100 / 1010 101000 / 1000 100001000001 / 100010 100001000001 / 100101 END { my ($left, $op, $right) = split; my ($x, $y) = map Zeckendorf->new($_), $left, $right; my $answer = $op eq '+' ? $x + $y : $op eq '-' ? $x - $y : $op eq '*' ? $x * $y : $op eq '/' ? $x / $y : die "bad op <$op>"; printf "%12s %s %-9s => %12s in Zeckendorf\n", $x, $op, $y, $answer; printf "%12d %s %-9d => %12d in decimal\n\n", $x->asdecimal, $op, $y->asdecimal, $answer->asdecimal; }   package Zeckendorf; use overload qw("" zstring + zadd - zsub ++ zinc -- zdec * zmul / zdiv ge zge);   sub new { my ($class, $value) = @_; bless \$value, ref $class || $class; }   sub zinc { my ($self, $other, $swap) = @_; local $_ = $$self; s/0$/1/ or s/(?:^|0)1$/10/; 1 while s/(?:^|0)11/100/; $_[0] = $self->new( s/^0+\B//r ); }   sub zdec { my ($self, $other, $swap) = @_; local $_ = $$self; 1 while s/100(?=0*$)/011/; s/1$/0/ or s/10$/01/; $_[0] = $self->new( s/^0+\B//r ); }   sub zstring { ${ shift() } }   sub zadd { my ($self, $other, $swap) = @_; my ($x, $y) = map $self->new($$_), $self, $other; # copy ++$x, $y-- while $$y ne 0; return $x; }   sub zsub { my ($self, $other, $swap) = @_; my ($x, $y) = map $self->new($$_), $self, $other; # copy --$x, $y-- while $$y ne 0; return $x; }   sub zmul { my ($self, $other, $swap) = @_; my ($x, $y) = map $self->new($$_), $self, $other; # copy my $product = Zeckendorf->new(0); $product = $product + $x, --$y while "$y" ne 0; return $product; }   sub zdiv { my ($self, $other, $swap) = @_; my ($x, $y) = map $self->new($$_), $self, $other; # copy my $quotient = Zeckendorf->new(0); ++$quotient, $x = $x - $y while $x ge $y; return $quotient; }   sub zge { my ($self, $other, $swap) = @_; my $l = length( $$self | $$other ); 0 x ($l - length $$self) . $$self ge 0 x ($l - length $$other) . $$other; }   sub asdecimal { my ($self) = @_; my $n = 0; my $aa = my $bb = 1; for ( reverse split //, $$self ) { $n += $bb * $_; ($aa, $bb) = ($bb, $aa + $bb); } return $n; }   sub fromdecimal { my ($self, $value) = @_; my $z = $self->new(0); ++$z for 1 .. $value; return $z; }
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
#Lobster
Lobster
import std   // Derived from Julia and Python versions   def get_divisors(n: int) -> [int]: var i = 2 let d = [1, n] let limit = sqrt(n) while i <= limit: if n % i == 0: let j = n / i push(d,i) if i != j: push(d,j) i += 1 return d   def isPartSum(divs: [int], sum: int) -> bool: if sum == 0: return true let len = length(divs) if len == 0: return false let last = pop(divs) if last > sum: return isPartSum(divs, sum) return isPartSum(copy(divs), sum) or isPartSum(divs, sum-last)   def isZumkeller(n: int) -> bool: let divs = get_divisors(n) let sum = fold(divs, 0): _a+_b if sum % 2 == 1: // if sum is odd can't be split into two partitions with equal sums return false if n % 2 == 1: // if n is odd use 'abundant odd number' optimization let abundance = sum - 2 * n return abundance > 0 and abundance % 2 == 0 return isPartSum(divs, sum/2)   def printZumkellers(q: int, oddonly: bool): var nprinted = 0 var res = "" for(100000) n: if (!oddonly or n % 2 != 0): if isZumkeller(n): let s = string(n) let z = length(s) res = concat_string([res, repeat_string(" ",8-z), s], "") nprinted += 1 if nprinted % 10 == 0 or nprinted >= q: print res res = "" if nprinted >= q: return   print "220 Zumkeller numbers:" printZumkellers(220, false) print "\n\n40 odd Zumkeller numbers:" printZumkellers(40, true)  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[ZumkellerQ] ZumkellerQ[n_] := Module[{d = Divisors[n], t, ds, x}, ds = Total[d]; If[Mod[ds, 2] == 1, False , t = CoefficientList[Product[1 + x^i, {i, d}], x]; t[[1 + ds/2]] > 0 ] ]; i = 1; res = {}; While[Length[res] < 220, r = ZumkellerQ[i]; If[r, AppendTo[res, i]]; i++; ]; res   i = 1; res = {}; While[Length[res] < 40, r = ZumkellerQ[i]; If[r, AppendTo[res, i]]; i += 2; ]; res
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
#Delphi
Delphi
  program Arbitrary_precision_integers;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigIntegers;   var value: BigInteger; result: string;   begin value := BigInteger.pow(3, 2); value := BigInteger.pow(4, value.AsInteger); value := BigInteger.pow(5, value.AsInteger); result := value.tostring; Write('5^4^3^2 = '); Write(result.substring(0, 20), '...'); Write(result.substring(result.length - 20, 20)); Writeln(' (', result.Length,' digits)'); readln; end.
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
#E
E
? def value := 5**(4**(3**2)); null ? def decimal := value.toString(10); null ? decimal(0, 20) # value: "62060698786608744707"   ? decimal(decimal.size() - 20) # value: "92256259918212890625"   ? decimal.size() # value: 183231
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
#Lua
Lua
function zhangSuenThin(img) local dirs={ { 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}, { 0,-1}, }   local black=1 local white=0   function A(x, y) local c=0 local current=img[y+dirs[1][2]][x+dirs[1][1]] for i=2,#dirs do local to_compare=img[y+dirs[i][2]][x+dirs[i][1]] if current==white and to_compare==black then c=c+1 end current=to_compare end return c end   function B(x, y) local c=0 for i=2,#dirs do local value=img[y+dirs[i][2]][x+dirs[i][1]] if value==black then c=c+1 end end return c end   function common_step(x, y) if img[y][x]~=black or x<=1 or x>=#img[y] or y<=1 or y>=#img then return false end   local b_value=B(x, y) if b_value<2 or b_value>6 then return false end   local a_value=A(x, y) if a_value~=1 then return false end return true end   function step_one(x, y) if not common_step(x, y) then return false end local p2=img[y+dirs[1][2]][x+dirs[1][1]] local p4=img[y+dirs[3][2]][x+dirs[3][1]] local p6=img[y+dirs[5][2]][x+dirs[5][1]] local p8=img[y+dirs[7][2]][x+dirs[7][1]]   if p4==white or p6==white or p2==white and p8==white then return true end return false end   function step_two(x, y) if not common_step(x, y) then return false end local p2=img[y+dirs[1][2]][x+dirs[1][1]] local p4=img[y+dirs[3][2]][x+dirs[3][1]] local p6=img[y+dirs[5][2]][x+dirs[5][1]] local p8=img[y+dirs[7][2]][x+dirs[7][1]]   if p2==white or p8==white or p4==white and p6==white then return true end return false end   function convert(to_do) for k,v in pairs(to_do) do img[v[2]][v[1]]=white end end   function do_step_on_all(step) local to_convert={} for y=1,#img do for x=1,#img[y] do if step(x, y) then table.insert(to_convert, {x,y}) end end end convert(to_convert) return #to_convert>0 end   local continue=true while continue do continue=false if do_step_on_all(step_one) then continue=true end   if do_step_on_all(step_two) then continue=true end end   for y=1,#img do for x=1,#img[y] do io.write(img[y][x]==black and '#' or ' ') end io.write('\n') end end   local image = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0}, {0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,0,0}, {0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0}, {0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0}, {0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,0}, {0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, }   zhangSuenThin(image)  
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
#F.23
F#
let fib = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (1,2)   let zeckendorf n = if n = 0 then ["0"] else let folder k state = let (n, z) = (fst state), (snd state) if n >= k then (n - k, "1" :: z) else (n, "0" :: z) let fb = fib |> Seq.takeWhile (fun i -> i<=n) |> Seq.toList snd (List.foldBack folder fb (n, [])) |> List.rev   for i in 0 .. 20 do printfn "%2d: %8s" i (String.concat "" (zeckendorf i))
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.
#C.23
C#
namespace ConsoleApplication1 { using System; class Program { static void Main(string[] args) { bool[] doors = new bool[100];   //Close all doors to start. for (int d = 0; d < 100; d++) doors[d] = false;   //For each pass... for (int p = 0; p < 100; p++)//number of passes { //For each door to toggle... for (int d = 0; d < 100; d++)//door number { if ((d + 1) % (p + 1) == 0) { doors[d] = !doors[d]; } } }   //Output the results. Console.WriteLine("Passes Completed!!! Here are the results: \r\n"); for (int d = 0; d < 100; d++) { if (doors[d]) { Console.WriteLine(String.Format("Door #{0}: Open", d + 1)); } else { Console.WriteLine(String.Format("Door #{0}: Closed", d + 1)); } } Console.ReadKey(true); } } }
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)
#Erlang
Erlang
  %% Create a fixed-size array with entries 0-9 set to 'undefined' A0 = array:new(10). 10 = array:size(A0).   %% Create an extendible array and set entry 17 to 'true', %% causing the array to grow automatically A1 = array:set(17, true, array:new()). 18 = array:size(A1).   %% Read back a stored value true = array:get(17, A1).   %% Accessing an unset entry returns the default value undefined = array:get(3, A1).   %% Accessing an entry beyond the last set entry also returns the %% default value, if the array does not have fixed size undefined = array:get(18, A1).   %% "sparse" functions ignore default-valued entries A2 = array:set(4, false, A1). [{4, false}, {17, true}] = array:sparse_to_orddict(A2).   %% An extendible array can be made fixed-size later A3 = array:fix(A2).   %% A fixed-size array does not grow automatically and does not %% allow accesses beyond the last set entry {'EXIT',{badarg,_}} = (catch array:set(18, true, A3)). {'EXIT',{badarg,_}} = (catch array:get(18, A3)).  
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.
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de addComplex (A B) (cons (+ (car A) (car B)) # Real (+ (cdr A) (cdr B)) ) ) # Imag   (de mulComplex (A B) (cons (- (*/ (car A) (car B) 1.0) (*/ (cdr A) (cdr B) 1.0) ) (+ (*/ (car A) (cdr B) 1.0) (*/ (cdr A) (car B) 1.0) ) ) )   (de invComplex (A) (let Denom (+ (*/ (car A) (car A) 1.0) (*/ (cdr A) (cdr A) 1.0) ) (cons (*/ (car A) 1.0 Denom) (- (*/ (cdr A) 1.0 Denom)) ) ) )   (de negComplex (A) (cons (- (car A)) (- (cdr A))) )   (de fmtComplex (A) (pack (round (car A) (dec *Scl)) (and (gt0 (cdr A)) "+") (round (cdr A) (dec *Scl)) "i" ) )   (let (A (1.0 . 1.0) B (cons pi 1.2)) (prinl "A = " (fmtComplex A)) (prinl "B = " (fmtComplex B)) (prinl "A+B = " (fmtComplex (addComplex A B))) (prinl "A*B = " (fmtComplex (mulComplex A B))) (prinl "1/A = " (fmtComplex (invComplex A))) (prinl "-A = " (fmtComplex (negComplex A))) )
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#PL.2FI
PL/I
/* PL/I complex numbers may be integer or floating-point. */ /* In this example, the variables are floating-pint. */ /* For integer variables, change 'float' to 'fixed binary' */   declare (a, b) complex float; a = 2+5i; b = 7-6i;   put skip list (a+b); put skip list (a - b); put skip list (a*b); put skip list (a/b); put skip list (a**b); put skip list (1/a); put skip list (conjg(a)); /* gives the conjugate of 'a'. */   /* Functions exist for extracting the real and imaginary parts */ /* of a complex number. */   /* As well, trigonometric functions may be used with complex */ /* numbers, such as SIN, COS, TAN, ATAN, and so on. */
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
#REXX
REXX
/*REXX program implements a reasonably complete rational arithmetic (using fractions).*/ L=length(2**19 - 1) /*saves time by checking even numbers. */ do j=2 by 2 to 2**19 - 1; s=0 /*ignore unity (which can't be perfect)*/ mostDivs=eDivs(j); @= /*obtain divisors>1; zero sum; null @. */ do k=1 for words(mostDivs) /*unity isn't return from eDivs here.*/ r='1/'word(mostDivs, k); @=@ r; s=$fun(r, , s) end /*k*/ if s\==1 then iterate /*Is sum not equal to unity? Skip it.*/ say 'perfect number:' right(j, L) " fractions:" @ end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ $div: procedure; parse arg x; x=space(x,0); f= 'fractional division' parse var x n '/' d; d=p(d 1) if d=0 then call err 'division by zero:' x if \datatype(n,'N') then call err 'a non─numeric numerator:' x if \datatype(d,'N') then call err 'a non─numeric denominator:' x return n/d /*──────────────────────────────────────────────────────────────────────────────────────*/ $fun: procedure; parse arg z.1,,z.2 1 zz.2; arg ,op; op=p(op '+') F= 'fractionalFunction'; do j=1 for 2; z.j=translate(z.j, '/', "_"); end /*j*/ if abbrev('ADD' , op) then op= "+" if abbrev('DIVIDE' , op) then op= "/" if abbrev('INTDIVIDE', op, 4) then op= "÷" if abbrev('MODULUS' , op, 3) | abbrev('MODULO', op, 3) then op= "//" if abbrev('MULTIPLY' , op) then op= "*" if abbrev('POWER' , op) then op= "^" if abbrev('SUBTRACT' , op) then op= "-" if z.1=='' then z.1= (op\=="+" & op\=='-') if z.2=='' then z.2= (op\=="+" & op\=='-') z_=z.2 /* [↑] verification of both fractions.*/ do j=1 for 2 if pos('/', z.j)==0 then z.j=z.j"/1"; parse var z.j n.j '/' d.j if \datatype(n.j,'N') then call err 'a non─numeric numerator:' n.j if \datatype(d.j,'N') then call err 'a non─numeric denominator:' d.j if d.j=0 then call err 'a denominator of zero:' d.j n.j=n.j/1; d.j=d.j/1 do while \datatype(n.j,'W'); n.j=(n.j*10)/1; d.j=(d.j*10)/1 end /*while*/ /* [↑] {xxx/1} normalizes a number. */ g=gcd(n.j, d.j); if g=0 then iterate; n.j=n.j/g; d.j=d.j/g end /*j*/   select when op=='+' | op=='-' then do; l=lcm(d.1,d.2); do j=1 for 2; n.j=l*n.j/d.j; d.j=l end /*j*/ if op=='-' then n.2= -n.2; t=n.1 + n.2; u=l end when op=='**' | op=='↑' |, op=='^' then do; if \datatype(z_,'W') then call err 'a non─integer power:' z_ t=1; u=1; do j=1 for abs(z_); t=t*n.1; u=u*d.1 end /*j*/ if z_<0 then parse value t u with u t /*swap U and T */ end when op=='/' then do; if n.2=0 then call err 'a zero divisor:' zz.2 t=n.1*d.2; u=n.2*d.1 end when op=='÷' then do; if n.2=0 then call err 'a zero divisor:' zz.2 t=trunc($div(n.1 '/' d.1)); u=1 end /* [↑] this is integer division. */ when op=='//' then do; if n.2=0 then call err 'a zero divisor:' zz.2 _=trunc($div(n.1 '/' d.1)); t=_ - trunc(_) * d.1; u=1 end /* [↑] modulus division. */ when op=='ABS' then do; t=abs(n.1); u=abs(d.1); end when op=='*' then do; t=n.1 * n.2; u=d.1 * d.2; end when op=='EQ' | op=='=' then return $div(n.1 '/' d.1) = fDiv(n.2 '/' d.2) when op=='NE' | op=='\=' | op=='╪' | , op=='¬=' then return $div(n.1 '/' d.1) \= fDiv(n.2 '/' d.2) when op=='GT' | op=='>' then return $div(n.1 '/' d.1) > fDiv(n.2 '/' d.2) when op=='LT' | op=='<' then return $div(n.1 '/' d.1) < fDiv(n.2 '/' d.2) when op=='GE' | op=='≥' | op=='>=' then return $div(n.1 '/' d.1) >= fDiv(n.2 '/' d.2) when op=='LE' | op=='≤' | op=='<=' then return $div(n.1 '/' d.1) <= fDiv(n.2 '/' d.2) otherwise call err 'an illegal function:' op end /*select*/   if t==0 then return 0; g=gcd(t, u); t=t/g; u=u/g if u==1 then return t return t'/'u /*──────────────────────────────────────────────────────────────────────────────────────*/ eDivs: procedure; parse arg x 1 b,a do j=2 while j*j<x; if x//j\==0 then iterate; a=a j; b=x%j b; end if j*j==x then return a j b; return a b /*───────────────────────────────────────────────────────────────────────────────────────────────────*/ err: say; say '***error*** ' f " detected" arg(1); say; exit 13 gcd: procedure; parse arg x,y; if x=0 then return y; do until _==0; _=x//y; x=y; y=_; end; return x lcm: procedure; parse arg x,y; if y=0 then return 0; x=x*y/gcd(x, y); return x p: return word( arg(1), 1)
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#Tcl
Tcl
proc agm {a b} { set old_b [expr {$b<0?inf:-inf}] while {$a != $b && $b != $old_b} { set old_b $b lassign [list [expr {0.5*($a+$b)}] [expr {sqrt($a*$b)}]] a b } return $a }   puts [agm 1 [expr 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
#TI-83_BASIC
TI-83 BASIC
1→A:1/sqrt(2)→G While abs(A-G)>e-15 (A+G)/2→B sqrt(AG)→G:B→A End A
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
#HolyC
HolyC
F64 a = 0 ` 0; Print("0 ` 0 = %5.3f\n", a);
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
#Icon_and_Unicon
Icon and Unicon
procedure main() write(0^0) end
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#ALGOL_W
ALGOL W
begin % zig-zag matrix %  % z is returned holding a zig-zag matrix of order n, z must be at least n x n % procedure makeZigZag ( integer value n  ; integer array z( *, * ) ) ; begin procedure move ; begin if y = n then begin upRight := not upRight; x := x + 1 end else if x = 1 then begin upRight := not upRight; y := y + 1 end else begin x := x - 1; y := y + 1 end end move ; procedure swapXY ; begin integer swap; swap := x; x  := y; y  := swap; end swapXY ; integer x, y; logical upRight;  % initialise the n x n matrix in z % for i := 1 until n do for j := 1 until n do z( i, j ) := 0;  % fill in the zig-zag matrix % x := y := 1; upRight := true; for i := 1 until n * n do begin z( x, y ) := i - 1; if upRight then move else begin swapXY; move; swapXY end; end; end makeZigZap ;   begin integer array zigZag( 1 :: 10, 1 :: 10 ); for n := 5 do begin makeZigZag( n, zigZag ); for i := 1 until n do begin write( i_w := 4, s_w := 1, zigZag( i, 1 ) ); for j := 2 until n do writeon( i_w := 4, s_w := 1, zigZag( i, j ) ); end end end   end.
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. Example a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). Task Find and show as output the first  30  Yellowstone numbers. Extra Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. Related tasks   Greatest common divisor.   Plot coordinate pairs. See also   The OEIS entry:   A098550 The Yellowstone permutation.   Applegate et al, 2015: The Yellowstone Permutation [1].
#D
D
import std.numeric; import std.range; import std.stdio;   class Yellowstone { private bool[int] sequence_; private int min_ = 1; private int n_ = 0; private int n1_ = 0; private int n2_ = 0;   public this() { popFront(); }   public bool empty() { return false; }   public int front() { return n_; }   public void popFront() { n2_ = n1_; n1_ = n_; if (n_ < 3) { ++n_; } else { for (n_ = min_; !(n_ !in sequence_ && gcd(n1_, n_) == 1 && gcd(n2_, n_) > 1); ++n_) { // empty } } sequence_[n_] = true; while (true) { if (min_ !in sequence_) { break; } sequence_.remove(min_); ++min_; } } }   void main() { new Yellowstone().take(30).writeln(); }
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program yahoosearch.s */ /* access RosettaCode.org and data extract */ /* use openssl for access to port 443 */ /* test openssl : package libssl-dev */   /* 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 */   /*******************************************/ /* Constantes */ /*******************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall .equ BRK, 0x2d @ Linux syscall .equ CHARPOS, '@'   .equ EXIT, 1 .equ TAILLEBUFFER, 500   .equ SSL_OP_NO_SSLv3, 0x02000000 .equ SSL_OP_NO_COMPRESSION, 0x00020000 .equ SSL_MODE_AUTO_RETRY, 0x00000004 .equ SSL_CTRL_MODE, 33   .equ BIO_C_SET_CONNECT, 100 .equ BIO_C_DO_STATE_MACHINE, 101 .equ BIO_C_SET_SSL, 109 .equ BIO_C_GET_SSL, 110   .equ LGBUFFERREQ, 512001 .equ LGBUFFER2, 128001   /*********************************/ /* Initialized data */ /*********************************/ .data szMessDebutPgm: .asciz "Début du programme. \n" szRetourLigne: .asciz "\n" szMessFinOK: .asciz "Fin normale du programme. \n" szMessErreur: .asciz "Erreur  !!!" szMessExtractArea: .asciz "Extraction = " szNomSite1: .asciz "search.yahoo.com:443" @ host name and port szLibStart: .asciz ">Rosetta Code" @ search string szNomrepCertif: .asciz "/pi/certificats" szRequete1: .asciz "GET /search?p=\"Rosettacode.org\"&b=1 HTTP/1.1 \r\nHost: search.yahoo.com\r\nConnection: keep-alive\r\nContent-Type: text/plain\r\n\r\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 sBufferreq: .skip LGBUFFERREQ szExtractArea: .skip TAILLEBUFFER stNewSSL: .skip 200 /*********************************/ /* code section */ /*********************************/ .text .global main main: ldr r0,iAdrszMessDebutPgm bl affichageMess @ start message   /* connexion host port 443 and send query */ bl envoiRequete cmp r0,#-1 beq 99f @ error ?   bl analyseReponse   ldr r0,iAdrszMessFinOK @ end message bl affichageMess mov r0, #0 @ return code ok b 100f 99: ldr r0,iAdrszMessErreur @ error bl affichageMess mov r0, #1 @ return code error b 100f 100: mov r7,#EXIT @ program end svc #0 @ system call iAdrszMessDebutPgm: .int szMessDebutPgm iAdrszMessFinOK: .int szMessFinOK iAdrszMessErreur: .int szMessErreur   /*********************************************************/ /* connexion host port 443 and send query */ /*********************************************************/ envoiRequete: push {r2-r8,lr} @ save registers @************************************* @ openSsl functions use * @************************************* @init ssl bl OPENSSL_init_crypto bl ERR_load_BIO_strings mov r2, #0 mov r1, #0 mov r0, #2 bl OPENSSL_init_crypto mov r2, #0 mov r1, #0 mov r0, #0 bl OPENSSL_init_ssl cmp r0,#0 blt erreur bl TLS_client_method bl SSL_CTX_new cmp r0,#0 ble erreur mov r6,r0 @ save ctx ldr r1,iFlag bl SSL_CTX_set_options mov r0,r6 mov r1,#0 ldr r2,iAdrszNomrepCertif bl SSL_CTX_load_verify_locations cmp r0,#0 ble erreur mov r0,r6 bl BIO_new_ssl_connect cmp r0,#0 ble erreur mov r5,r0 @ save bio mov r1,#BIO_C_GET_SSL mov r2,#0 ldr r3,iAdrstNewSSL bl BIO_ctrl ldr r0,iAdrstNewSSL ldr r0,[r0] mov r1,#SSL_CTRL_MODE mov r2,#SSL_MODE_AUTO_RETRY mov r3,#0 bl SSL_ctrl mov r0,r5 @ bio mov r1,#BIO_C_SET_CONNECT mov r2,#0 ldr r3,iAdrszNomSite1 bl BIO_ctrl mov r0,r5 @ bio mov r1,#BIO_C_DO_STATE_MACHINE mov r2,#0 mov r3,#0 bl BIO_ctrl @ compute query length mov r2,#0 ldr r1,iAdrszRequete1 @ query 1: ldrb r0,[r1,r2] cmp r0,#0 addne r2,#1 bne 1b @ send query mov r0,r5 @ bio @ r1 = address query @ r2 = length query mov r3,#0 bl BIO_write @ send query cmp r0,#0 blt erreur ldr r7,iAdrsBufferreq @ buffer address 2: @ begin loop to read datas mov r0,r5 @ bio mov r1,r7 @ buffer address mov r2,#LGBUFFERREQ - 1 mov r3,#0 bl BIO_read cmp r0,#0 ble 4f @ error ou pb server add r7,r0 sub r2,r7,#6 ldr r2,[r2] ldr r3,iCharEnd cmp r2,r3 @ text end ? beq 4f mov r1,#0xFFFFFF @ delay loop 3: subs r1,#1 bgt 3b b 2b @ loop read other chunk 4: @ read end //ldr r0,iAdrsBufferreq @ to display buffer response of the query //bl affichageMess mov r0, r5 @ close bio bl BIO_free_all mov r0,#0 b 100f erreur: @ error display ldr r1,iAdrszMessErreur bl afficheerreur mov r0,#-1 @ error code b 100f 100: pop {r2-r8,lr} @ restaur registers bx lr iAdrszRequete1: .int szRequete1 iAdrsBufferreq: .int sBufferreq iFlag: .int SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION iAdrstNewSSL: .int stNewSSL iAdrszNomSite1: .int szNomSite1 iAdrszNomrepCertif: .int szNomrepCertif iCharEnd: .int 0x0A0D300A /*********************************************************/ /* response analyze */ /*********************************************************/ analyseReponse: push {r1-r4,lr} @ save registers ldr r0,iAdrsBufferreq @ buffer address ldr r1,iAdrszLibStart @ key text address mov r2,#2 @ occurence key text mov r3,#-11 @ offset ldr r4,iAdrszExtractArea @ address result area bl extChaine cmp r0,#-1 beq 99f ldr r0,iAdrszMessExtractArea bl affichageMess ldr r0,iAdrszExtractArea @ résult display bl affichageMess ldr r0,iAdrszRetourLigne bl affichageMess b 100f 99: ldr r0,iAdrszMessErreur @ error bl affichageMess mov r0, #-1 @ error return code b 100f 100: pop {r1-r4,lr} @ restaur registers bx lr iAdrszLibStart: .int szLibStart iAdrszExtractArea: .int szExtractArea iAdrszMessExtractArea: .int szMessExtractArea iAdrszRetourLigne: .int szRetourLigne /*********************************************************/ /* Text Extraction behind text key */ /*********************************************************/ /* r0 buffer address */ /* r1 key text to search */ /* r2 number occurences to key text */ /* r3 offset */ /* r4 result address */ extChaine: push {r2-r8,lr} @ save registers mov r5,r0 @ save buffer address mov r6,r1 @ save key text @ compute text length mov r7,#0 1: @ loop ldrb r0,[r5,r7] @ load a byte cmp r0,#0 @ end ? addne r7,#1 @ no -> loop bne 1b add r7,r5 @ compute text end   mov r8,#0 2: @ compute length text key ldrb r0,[r6,r8] cmp r0,#0 addne r8,#1 bne 2b   3: @ loop to search nième(r2) key text mov r0,r5 mov r1,r6 bl rechercheSousChaine cmp r0,#0 blt 100f subs r2,#1 addgt r5,r0 addgt r5,r8 bgt 3b add r0,r5 @ add address text to index add r3,r0 @ add offset sub r3,#1 @ and add length key text add r3,r8 cmp r3,r7 @ > at text end movge r0,#-1 @ yes -> error bge 100f mov r0,#0 4: @ character loop copy ldrb r2,[r3,r0] strb r2,[r4,r0] cmp r2,#0 @ text end ? moveq r0,#0 @ return zero beq 100f cmp r0,#48 @ extraction length beq 5f add r0,#1 b 4b @ and loop 5: mov r2,#0 @ store final zéro strb r2,[r4,r0] add r0,#1 add r0,r3 @ r0 return the last position of extraction @ it is possible o search another text 100: pop {r2-r8,lr} @ restaur registers bx lr   /******************************************************************/ /* search substring in string */ /******************************************************************/ /* r0 contains address string */ /* r1 contains address substring */ /* r0 return start index substring or -1 if not find */ rechercheSousChaine: push {r1-r6,lr} @ save registers mov r2,#0 @ index position string mov r3,#0 @ index position substring mov r6,#-1 @ search index ldrb r4,[r1,r3] @ load first byte substring cmp r4,#0 @ zero final ? moveq r0,#-1 @ error beq 100f 1: ldrb r5,[r0,r2] @ load string byte cmp r5,#0 @ zero final ? moveq r0,#-1 @ yes -> not find beq 100f cmp r5,r4 @ compare character two strings beq 2f mov r6,#-1 @ not equal - > raz index mov r3,#0 @ and raz byte counter ldrb r4,[r1,r3] @ and load byte add r2,#1 @ and increment byte counter b 1b @ and loop 2: @ characters equal cmp r6,#-1 @ first character equal ? moveq r6,r2 @ yes -> start index in r6 add r3,#1 @ increment substring counter ldrb r4,[r1,r3] @ and load next byte cmp r4,#0 @ zero final ? beq 3f @ yes -> search end add r2,#1 @ else increment string index b 1b @ and loop 3: mov r0,r6 @ return start index substring in the string 100: pop {r1-r6,lr} @ restaur registres bx lr   /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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.
#Rust
Rust
//! Simple calculator parser and evaluator     /// Binary operator #[derive(Debug)] pub enum Operator { Add, Substract, Multiply, Divide }   /// A node in the tree #[derive(Debug)] pub enum Node { Value(f64), SubNode(Box<Node>), Binary(Operator, Box<Node>,Box<Node>), }   /// parse a string into a node pub fn parse(txt :&str) -> Option<Node> { let chars = txt.chars().filter(|c| *c != ' ').collect(); parse_expression(&chars, 0).map(|(_,n)| n) }   /// parse an expression into a node, keeping track of the position in the character vector fn parse_expression(chars: &Vec<char>, pos: usize) -> Option<(usize,Node)> { match parse_start(chars, pos) { Some((new_pos, first)) => { match parse_operator(chars, new_pos) { Some((new_pos2,op)) => { if let Some((new_pos3, second)) = parse_expression(chars, new_pos2) { Some((new_pos3, combine(op, first, second))) } else { None } }, None => Some((new_pos,first)), } }, None => None, } }   /// combine nodes to respect associativity rules fn combine(op: Operator, first: Node, second: Node) -> Node { match second { Node::Binary(op2,v21,v22) => if precedence(&op)>=precedence(&op2) { Node::Binary(op2,Box::new(combine(op,first,*v21)),v22) } else { Node::Binary(op,Box::new(first),Box::new(Node::Binary(op2,v21,v22))) }, _ => Node::Binary(op,Box::new(first),Box::new(second)), } }   /// a precedence rank for operators fn precedence(op: &Operator) -> usize { match op{ Operator::Multiply | Operator::Divide => 2, _ => 1 } }   /// try to parse from the start of an expression (either a parenthesis or a value) fn parse_start(chars: &Vec<char>, pos: usize) -> Option<(usize,Node)> { match start_parenthesis(chars, pos){ Some (new_pos) => { let r = parse_expression(chars, new_pos); end_parenthesis(chars, r) }, None => parse_value(chars, pos), } }   /// match a starting parentheseis fn start_parenthesis(chars: &Vec<char>, pos: usize) -> Option<usize>{ if pos<chars.len() && chars[pos] == '(' { Some(pos+1) } else { None } }   /// match an end parenthesis, if successful will create a sub node contained the wrapped expression fn end_parenthesis(chars: &Vec<char>, wrapped :Option<(usize,Node)>) -> Option<(usize,Node)>{ match wrapped { Some((pos, node)) => if pos<chars.len() && chars[pos] == ')' { Some((pos+1,Node::SubNode(Box::new(node)))) } else { None }, None => None, } }   /// parse a value: an decimal with an optional minus sign fn parse_value(chars: &Vec<char>, pos: usize) -> Option<(usize,Node)>{ let mut new_pos = pos; if new_pos<chars.len() && chars[new_pos] == '-' { new_pos = new_pos+1; } while new_pos<chars.len() && (chars[new_pos]=='.' || (chars[new_pos] >= '0' && chars[new_pos] <= '9')) { new_pos = new_pos+1; } if new_pos>pos { if let Ok(v) = dbg!(chars[pos..new_pos].iter().collect::<String>()).parse() { Some((new_pos,Node::Value(v))) } else { None } } else { None }   }   /// parse an operator fn parse_operator(chars: &Vec<char>, pos: usize) -> Option<(usize,Operator)> { if pos<chars.len() { let ops_with_char = vec!(('+',Operator::Add),('-',Operator::Substract),('*',Operator::Multiply),('/',Operator::Divide)); for (ch,op) in ops_with_char { if chars[pos] == ch { return Some((pos+1, op)); } } } None }   /// eval a string pub fn eval(txt :&str) -> f64 { match parse(txt) { Some(t) => eval_term(&t), None => panic!("Cannot parse {}",txt), }   }   /// eval a term, recursively fn eval_term(t: &Node) -> f64 { match t { Node::Value(v) => *v, Node::SubNode(t) => eval_term(t), Node::Binary(Operator::Add,t1,t2) => eval_term(t1) + eval_term(t2), Node::Binary(Operator::Substract,t1,t2) => eval_term(t1) - eval_term(t2), Node::Binary(Operator::Multiply,t1,t2) => eval_term(t1) * eval_term(t2), Node::Binary(Operator::Divide,t1,t2) => eval_term(t1) / eval_term(t2), } }   #[cfg(test)] mod tests { use super::*;   #[test] fn test_eval(){ assert_eq!(2.0,eval("2")); assert_eq!(4.0,eval("2+2")); assert_eq!(11.0/4.0, eval("2+3/4")); assert_eq!(2.0, eval("2*3-4")); assert_eq!(3.0, eval("1+2*3-4")); assert_eq!(89.0/6.0, eval("2*(3+4)+5/6")); assert_eq!(14.0, eval("2 * (3 -1) + 2 * 5")); assert_eq!(7000.0, eval("2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10")); assert_eq!(-9.0/4.0, eval("2*-3--4+-.25")); assert_eq!(1.5, eval("1 - 5 * 2 / 20 + 1")); assert_eq!(3.5, eval("2 * (3 + ((5) / (7 - 11)))"));   } }    
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.
#Phix
Phix
with javascript_semantics sequence fib = {1,1} function zeckendorf(atom n) -- Same as Zeckendorf_number_representation#Phix atom r = 0 while fib[$]<n do fib &= fib[$] + fib[$-1] end while integer k = length(fib) while k>2 and n<fib[k] do k -= 1 end while for i=k to 2 by -1 do integer c = n>=fib[i] r += r+c n -= c*fib[i] end for return r end function function decimal(object z) -- Convert Zeckendorf number(s) to decimal if sequence(z) then sequence res = repeat(0,length(z)) for i=1 to length(z) do res[i] = decimal(z[i]) end for return res end if atom dec = 0, bit = 2 while z do if and_bits(z,1) then dec += fib[bit] end if bit += 1 if bit>length(fib) then fib &= fib[$] + fib[$-1] end if z = floor(z/2) end while return dec end function function to_bits(integer x) -- Simplified copy of int_to_bits(), but in reverse order, -- and +ve only but (also only) as many bits as needed, and -- ensures there are *two* trailing 0 (most significant) if x<0 then ?9/0 end if -- sanity/avoid infinite loop sequence bits = {} while 1 do bits &= remainder(x,2) if x=0 then exit end if x = floor(x/2) end while bits &= 0 -- (since eg 101+101 -> 10000) return bits end function function to_bits2(integer a,b) -- Apply to_bits() to a and b, and pad to the same length sequence sa = to_bits(a), sb = to_bits(b) integer diff = length(sa)-length(sb) if diff!=0 then if diff<0 then sa &= repeat(0,-diff) else sb &= repeat(0,+diff) end if end if return {sa,sb} end function function to_int(sequence bits) -- Copy of bits_to_int(), but in reverse order (lsb last) atom val = 0, p = 1 for i=length(bits) to 1 by -1 do if bits[i] then val += p end if p += p end for return val end function function zstr(object z) if sequence(z) then sequence res = repeat(0,length(z)) for i=1 to length(z) do res[i] = zstr(z[i]) end for return res end if return sprintf("%b",z) end function function rep(sequence res, integer ds, sequence was, wth) -- helper for cleanup, validates replacements integer de = ds+length(was)-1 if res[ds..de]!=was then ?9/0 end if if length(was)!=length(wth) then ?9/0 end if res = deep_copy(res) res[ds..de] = wth return res end function function zcleanup(sequence res) -- (shared by zadd and zsub) integer l = length(res) res = deep_copy(res) -- first stage, left to right, {020x -> 100x', 030x -> 110x', 021x->110x, 012x->101x} for i=1 to l-3 do sequence s3 = res[i..i+2] if s3={0,2,0} then res[i..i+2] = {1,0,0} res[i+3] += 1 elsif s3={0,3,0} then res[i..i+2] = {1,1,0} res[i+3] += 1 elsif s3={0,2,1} then res[i..i+2] = {1,1,0} elsif s3={0,1,2} then res[i..i+2] = {1,0,1} end if end for -- first stage cleanup if l>1 then if res[l-1]=3 then res = rep(res,l-2,{0,3,0},{1,1,1}) -- 030 -> 111 elsif res[l-1]=2 then if res[l-2]=0 then res = rep(res,l-2,{0,2,0},{1,0,1}) -- 020 -> 101 else res = rep(res,l-3,{0,1,2,0},{1,0,1,0}) -- 0120 -> 1010 end if end if end if if res[l]=3 then res = rep(res,l-1,{0,3},{1,1}) -- 03 -> 11 elsif res[l]=2 then if res[l-1]=0 then res = rep(res,l-1,{0,2},{1,0}) -- 02 -> 10 else res = rep(res,l-2,{0,1,2},{1,0,1}) -- 012 -> 101 end if end if -- second stage, pass 1, right to left, 011 -> 100 for i=length(res)-2 to 1 by -1 do if res[i..i+2]={0,1,1} then res[i..i+2] = {1,0,0} end if end for -- second stage, pass 2, left to right, 011 -> 100 for i=1 to length(res)-2 do if res[i..i+2]={0,1,1} then res[i..i+2] = {1,0,0} end if end for return to_int(res) end function function zadd(integer a, b) sequence {sa,sb} = to_bits2(a,b) return zcleanup(reverse(sq_add(sa,sb))) end function function zinc(integer a) return zadd(a,0b1) end function function zsub(integer a, b) sequence {sa,sb} = to_bits2(a,b) sequence res = reverse(sq_sub(sa,sb)) -- (/not/ combined with the first pass of the add routine!) for i=1 to length(res)-2 do sequence s3 = res[i..i+2] if s3={1, 0, 0} then res[i..i+2] = {0,1,1} elsif s3={1,-1, 0} then res[i..i+2] = {0,0,1} elsif s3={1,-1, 1} then res[i..i+2] = {0,0,2} elsif s3={1, 0,-1} then res[i..i+2] = {0,1,0} elsif s3={2, 0, 0} then res[i..i+2] = {1,1,1} elsif s3={2,-1, 0} then res[i..i+2] = {1,0,1} elsif s3={2,-1, 1} then res[i..i+2] = {1,0,2} elsif s3={2, 0,-1} then res[i..i+2] = {1,1,0} end if end for -- copied from PicoLisp: {1,-1} -> {0,1} and {2,-1} -> {1,1} for i=1 to length(res)-1 do sequence s2 = res[i..i+1] if s2={1,-1} then res[i..i+1] = {0,1} elsif s2={2,-1} then res[i..i+1] = {1,1} end if end for if find(-1,res) then ?9/0 end if -- sanity check return zcleanup(res) end function function zdec(integer a) return zsub(a,0b1) end function function zmul(integer a, b) sequence mult = {a,zadd(a,a)} -- (as per task desc) integer bits = 2 while bits<b do mult = append(mult,zadd(mult[$],mult[$-1])) bits *= 2 end while integer res = 0, bit = 1 while b do if and_bits(b,1) then res = zadd(res,mult[bit]) end if b = floor(b/2) bit += 1 end while return res end function function zdiv(integer a, b) sequence mult = {b,zadd(b,b)} integer bits = 2 while mult[$]<a do mult = append(mult,zadd(mult[$],mult[$-1])) bits *= 2 end while integer res = 0 for i=length(mult) to 1 by -1 do integer mi = mult[i] if mi<=a then res = zadd(res,bits) a = zsub(a,mi) if a=0 then exit end if end if bits = floor(bits/2) end for return {res,a} -- (a is the remainder) end function for i=0 to 20 do integer zi = zeckendorf(i) atom d = decimal(zi) printf(1,"%2d: %7b (%d)\n",{i,zi,d}) end for procedure test(atom a, string op, atom b, object res, string expected) string zres = iff(atom(res)?zstr(res):join(zstr(res)," rem ")), dres = sprintf(iff(atom(res)?"%d":"%d rem %d"),decimal(res)), aka = sprintf("aka %d %s %d = %s",{decimal(a),op,decimal(b),dres}), ok = iff(zres=expected?"":" *** ERROR ***!!") printf(1,"%s %s %s = %s, %s %s\n",{zstr(a),op,zstr(b),zres,aka,ok}) end procedure test(0b0,"+",0b0,zadd(0b0,0b0),"0") test(0b101,"+",0b101,zadd(0b101,0b101),"10000") test(0b10100,"-",0b1000,zsub(0b10100,0b1000),"1001") test(0b100100,"-",0b1000,zsub(0b100100,0b1000),"10100") test(0b1001,"*",0b101,zmul(0b1001,0b101),"1000100") test(0b1000101,"/",0b101,zdiv(0b1000101,0b101),"1001 rem 1") test(0b10,"+",0b10,zadd(0b10,0b10),"101") test(0b101,"+",0b10,zadd(0b101,0b10),"1001") test(0b1001,"+",0b1001,zadd(0b1001,0b1001),"10101") test(0b10101,"+",0b1000,zadd(0b10101,0b1000),"100101") test(0b100101,"+",0b10101,zadd(0b100101,0b10101),"1010000") test(0b1000,"-",0b101,zsub(0b1000,0b101),"1") test(0b10101010,"-",0b1010101,zsub(0b10101010,0b1010101),"1000000") test(0b1001,"*",0b101,zmul(0b1001,0b101),"1000100") test(0b101010,"+",0b101,zadd(0b101010,0b101),"1000100") test(0b10100,"+",0b1010,zadd(0b10100,0b1010),"101000") test(0b101000,"-",0b1010,zsub(0b101000,0b1010),"10100") test(0b100010,"*",0b100101,zmul(0b100010,0b100101),"100001000001") test(0b100001000001,"/",0b100,zdiv(0b100001000001,0b100),"101010001 rem 0") test(0b101000101,"*",0b101001,zmul(0b101000101,0b101001),"101010000010101") test(0b101010000010101,"/",0b100,zdiv(0b101010000010101,0b100),"1001010001001 rem 10") test(0b10100010010100,"+",0b1001000001,zadd(0b10100010010100,0b1001000001),"100000000010101") test(0b10100010010100,"-",0b1001000001,zsub(0b10100010010100,0b1001000001),"10010001000010") test(0b10000,"*",0b1001000001,zmul(0b10000,0b1001000001),"10100010010100") test(0b1010001010000001001,"/",0b100000000100000,zdiv(0b1010001010000001001,0b100000000100000),"10001 rem 10100001010101") test(0b10100,"+",0b1010,zadd(0b10100,0b1010),"101000") test(0b10100,"-",0b1010,zsub(0b10100,0b1010),"101") test(0b10100,"*",0b1010,zmul(0b10100,0b1010),"101000001") test(0b10100,"/",0b1010,zdiv(0b10100,0b1010),"1 rem 101") integer m = zmul(0b10100,0b1010) test(m,"/",0b1010,zdiv(m,0b1010),"10100 rem 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
#Nim
Nim
import math, strutils   template isEven(n: int): bool = (n and 1) == 0 template isOdd(n: int): bool = (n and 1) != 0     func getDivisors(n: int): seq[int] = result = @[1, n] for i in 2..sqrt(n.toFloat).int: if n mod i == 0: let j = n div i result.add i if i != j: result.add j     func isPartSum(divs: seq[int]; sum: int): bool = if sum == 0: return true if divs.len == 0: return false let last = divs[^1] let divs = divs[0..^2] result = isPartSum(divs, sum) if not result and last <= sum: result = isPartSum(divs, sum - last)     func isZumkeller(n: int): bool = let divs = n.getDivisors() let sum = sum(divs) # If "sum" is odd, it can't be split into two partitions with equal sums. if sum.isOdd: return false # If "n" is odd use "abundant odd number" optimization. if n.isOdd: let abundance = sum - 2 * n return abundance > 0 and abundance.isEven # If "n" and "sum" are both even, check if there's a partition which totals "sum / 2". result = isPartSum(divs, sum div 2)     when isMainModule:   echo "The first 220 Zumkeller numbers are:" var n = 2 var count = 0 while count < 220: if n.isZumkeller: stdout.write align($n, 3) inc count stdout.write if count mod 20 == 0: '\n' else: ' ' inc n echo()   echo "The first 40 odd Zumkeller numbers are:" n = 3 count = 0 while count < 40: if n.isZumkeller: stdout.write align($n, 5) inc count stdout.write if count mod 10 == 0: '\n' else: ' ' inc n, 2 echo()   echo "The first 40 odd Zumkeller numbers which don't end in 5 are:" n = 3 count = 0 while count < 40: if n mod 10 != 5 and n.isZumkeller: stdout.write align($n, 7) inc count stdout.write if count mod 8 == 0: '\n' else: ' ' inc n, 2
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
#Pascal
Pascal
program zumkeller; //https://oeis.org/A083206/a083206.txt {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON} // {$O+,I+} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils {$IFDEF WINDOWS},Windows{$ENDIF} ; //###################################################################### //prime decomposition const //HCN(86) > 1.2E11 = 128,501,493,120 count of divs = 4096 7 3 1 1 1 1 1 1 1 HCN_DivCnt = 4096; //stop never ending recursion RECCOUNTMAX = 100*1000*1000; DELTAMAX = 1000*1000; type tItem = Uint64; tDivisors = array [0..HCN_DivCnt-1] of tItem; tpDivisor = pUint64; const SizePrDeFe = 12697;//*72 <= 1 or 2 Mb ~ level 2 cache -32kB for DIVS type tdigits = packed record dgtDgts : array [0..31] of Uint32; end;   //the first number with 11 different divisors = // 2*3*5*7*11*13*17*19*23*29*31 = 2E11 tprimeFac = packed record pfSumOfDivs, pfRemain : Uint64; //n div (p[0]^[pPot[0] *...) can handle primes <=821641^2 = 6.7e11 pfpotPrim : array[0..9] of UInt32;//+10*4 = 56 Byte pfpotMax : array[0..9] of byte; //10 = 66 pfMaxIdx : Uint16; //68 pfDivCnt : Uint32; //72 end;   tPrimeDecompField = array[0..SizePrDeFe-1] of tprimeFac; tPrimes = array[0..65535] of Uint32;   var SmallPrimes: tPrimes; //###################################################################### //prime decomposition procedure InitSmallPrimes; //only odd numbers const MAXLIMIT = (821641-1) shr 1; var pr : array[0..MAXLIMIT] of byte; p,j,d,flipflop :NativeUInt; Begin SmallPrimes[0] := 2; fillchar(pr[0],SizeOf(pr),#0); p := 0; repeat repeat p +=1 until pr[p]= 0; j := (p+1)*p*2; if j>MAXLIMIT then BREAK; d := 2*p+1; repeat pr[j] := 1; j += d; until j>MAXLIMIT; until false;   SmallPrimes[1] := 3; SmallPrimes[2] := 5; j := 3; d := 7; flipflop := 3-1; p := 3; repeat if pr[p] = 0 then begin SmallPrimes[j] := d; inc(j); end; d += 2*flipflop; p+=flipflop; flipflop := 3-flipflop; until (p > MAXLIMIT) OR (j>High(SmallPrimes)); end;   function OutPots(const pD:tprimeFac;n:NativeInt):Ansistring; var s: String[31]; Begin str(n,s); result := s+' :'; with pd do begin str(pfDivCnt:3,s); result += s+' : '; For n := 0 to pfMaxIdx-1 do Begin if n>0 then result += '*'; str(pFpotPrim[n],s); result += s; if pfpotMax[n] >1 then Begin str(pfpotMax[n],s); result += '^'+s; end; end; If pfRemain >1 then Begin str(pfRemain,s); result += '*'+s; end; str(pfSumOfDivs,s); result += '_SoD_'+s+'<'; end; end;   function CnvtoBASE(var dgt:tDigits;n:Uint64;base:NativeUint):NativeInt; //n must be multiple of base var q,r: Uint64; i : NativeInt; Begin with dgt do Begin fillchar(dgtDgts,SizeOf(dgtDgts),#0); i := 0; // dgtNum:= n; n := n div base; result := 0; repeat r := n; q := n div base; r -= q*base; n := q; dgtDgts[i] := r; inc(i); until (q = 0);   result := 0; while (result<i) AND (dgtDgts[result] = 0) do inc(result); inc(result); end; end;   function IncByBaseInBase(var dgt:tDigits;base:NativeInt):NativeInt; var q :NativeInt; Begin with dgt do Begin result := 0; q := dgtDgts[result]+1; // inc(dgtNum,base); if q = base then begin repeat dgtDgts[result] := 0; inc(result); q := dgtDgts[result]+1; until q <> base; end; dgtDgts[result] := q; result +=1; end; end;   procedure SieveOneSieve(var pdf:tPrimeDecompField;n:nativeUInt); var dgt:tDigits; i, j, k,pr,fac : NativeUInt; begin //init for i := 0 to High(pdf) do with pdf[i] do Begin pfDivCnt := 1; pfSumOfDivs := 1; pfRemain := n+i; pfMaxIdx := 0; end;   //first 2 make n+i even i := n AND 1; repeat with pdf[i] do if n+i > 0 then begin j := BsfQWord(n+i); pfMaxIdx := 1; pfpotPrim[0] := 2; pfpotMax[0] := j; pfRemain := (n+i) shr j; pfSumOfDivs := (1 shl (j+1))-1; pfDivCnt := j+1; end; i += 2; until i >High(pdf);   // i now index in SmallPrimes i := 0; repeat //search next prime that is in bounds of sieve repeat inc(i); if i >= High(SmallPrimes) then BREAK; pr := SmallPrimes[i]; k := pr-n MOD pr; if (k = pr) AND (n>0) then k:= 0; if k < SizePrDeFe then break; until false; if i >= High(SmallPrimes) then BREAK; //no need to use higher primes if pr*pr > n+SizePrDeFe then BREAK;   // j is power of prime j := CnvtoBASE(dgt,n+k,pr); repeat with pdf[k] do Begin pfpotPrim[pfMaxIdx] := pr; pfpotMax[pfMaxIdx] := j; pfDivCnt *= j+1; fac := pr; repeat pfRemain := pfRemain DIV pr; dec(j); fac *= pr; until j<= 0; pfSumOfDivs *= (fac-1)DIV(pr-1); inc(pfMaxIdx); end; k += pr; j := IncByBaseInBase(dgt,pr); until k >= SizePrDeFe; until false;   //correct sum of & count of divisors for i := 0 to High(pdf) do Begin with pdf[i] do begin j := pfRemain; if j <> 1 then begin pfSumOFDivs *= (j+1); pfDivCnt *=2; end; end; end; end; //prime decomposition //###################################################################### procedure Init_Check_rec(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors);forward;   var {$ALIGN 32} PrimeDecompField:tPrimeDecompField; {$ALIGN 32} Divs :tDivisors; SumOfDivs : tDivisors; DivUsedIdx : tDivisors;   pDiv :tpDivisor; T0: Int64; count,rec_Cnt: NativeInt; depth : Int32; finished :Boolean;   procedure Check_rek_depth(SoD : Int64;i: NativeInt); var sum : Int64; begin if finished then EXIT; inc(rec_Cnt);   WHILE (i>0) AND (pDiv[i]>SoD) do dec(i);   while i >= 0 do Begin DivUsedIdx[depth] := pDiv[i]; sum := SoD-pDiv[i]; if sum = 0 then begin finished := true; EXIT; end; dec(i); inc(depth); if (i>= 0) AND (sum <= SumOfDivs[i]) then Check_rek_depth(sum,i); if finished then EXIT; // DivUsedIdx[depth] := 0; dec(depth); end; end;   procedure Out_One_Sol(const pd:tprimefac;n:NativeUInt;isZK : Boolean); var sum : NativeInt; Begin if n< 7 then exit; with pd do begin writeln(OutPots(pD,n)); if isZK then Begin Init_Check_rec(pD,Divs,SumOfDivs); Check_rek_depth(pfSumOfDivs shr 1-n,pFDivCnt-1); write(pfSumOfDivs shr 1:10,' = '); sum := n; while depth >= 0 do Begin sum += DivUsedIdx[depth]; write(DivUsedIdx[depth],'+'); dec(depth); end; write(n,' = ',sum); end else write(' no zumkeller '); end; end;   procedure InsertSort(pDiv:tpDivisor; Left, Right : NativeInt ); var I, J: NativeInt; Pivot : tItem; begin for i:= 1 + Left to Right do begin Pivot:= pDiv[i]; j:= i - 1; while (j >= Left) and (pDiv[j] > Pivot) do begin pDiv[j+1]:=pDiv[j]; Dec(j); end; pDiv[j+1]:= pivot; end; end;   procedure GetDivs(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors); var pDivs : tpDivisor; pPot : UInt64; i,len,j,l,p,k: Int32; Begin i := pD.pfDivCnt; pDivs := @Divs[0]; pDivs[0] := 1; len := 1; l := 1; with pD do Begin For i := 0 to pfMaxIdx-1 do begin //Multiply every divisor before with the new primefactors //and append them to the list k := pfpotMax[i]; p := pfpotPrim[i]; pPot :=1; repeat pPot *= p; For j := 0 to len-1 do Begin pDivs[l]:= pPot*pDivs[j]; inc(l); end; dec(k); until k<=0; len := l; end; p := pfRemain; If p >1 then begin For j := 0 to len-1 do Begin pDivs[l]:= p*pDivs[j]; inc(l); end; len := l; end; end; //Sort. Insertsort much faster than QuickSort in this special case InsertSort(pDivs,0,len-1);   pPot := 0; For i := 0 to len-1 do begin pPot += pDivs[i]; SumOfDivs[i] := pPot; end; end;   procedure Init_Check_rec(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors); begin GetDivs(pD,Divs,SUmOfDivs); finished := false; depth := 0; pDiv := @Divs[0]; end;   procedure Check_rek(SoD : Int64;i: NativeInt); var sum : Int64; begin if finished then EXIT; if rec_Cnt >RECCOUNTMAX then begin rec_Cnt := -1; finished := true; exit; end; inc(rec_Cnt);   WHILE (i>0) AND (pDiv[i]>SoD) do dec(i);   while i >= 0 do Begin sum := SoD-pDiv[i]; if sum = 0 then begin finished := true; EXIT; end; dec(i); if (i>= 0) AND (sum <= SumOfDivs[i]) then Check_rek(sum,i); if finished then EXIT; end; end;   function GetZumKeller(n: NativeUint;var pD:tPrimefac): boolean; var SoD,sum : Int64; Div_cnt,i,pracLmt: NativeInt; begin rec_Cnt := 0; SoD:= pd.pfSumOfDivs; //sum must be even and n not deficient if Odd(SoD) or (SoD<2*n) THEN EXIT(false); //if Odd(n) then Exit(Not(odd(sum)));// to be tested   SoD := SoD shr 1-n; If SoD < 2 then //0,1 is always true Exit(true);   Div_cnt := pD.pfDivCnt;   if Not(odd(n)) then if ((n mod 18) in [6,12]) then EXIT(true);   //Now one needs to get the divisors Init_check_rec(pD,Divs,SumOfDivs);   pracLmt:= 0; if Not(odd(n)) then begin For i := 1 to Div_Cnt do Begin sum := SumOfDivs[i]; If (sum+1<Divs[i+1]) AND (sum<SoD) then Begin pracLmt := i; BREAK; end; IF (sum>=SoD) then break; end; if pracLmt = 0 then Exit(true); end; //number is practical followed by one big prime if pracLmt = (Div_Cnt-1) shr 1 then begin i := SoD mod Divs[pracLmt+1]; with pD do begin if pfRemain > 1 then EXIT((pfRemain<=i) OR (i<=sum)) else EXIT((pfpotPrim[pfMaxIdx-1]<=i)OR (i<=sum)); end; end;   Begin IF Div_cnt <= HCN_DivCnt then Begin Check_rek(SoD,Div_cnt-1); IF rec_Cnt = -1 then exit(true); exit(finished); end; end; result := false; end;   var Ofs,i,n : NativeUInt; Max: NativeUInt;   procedure Init_Sieve(n:NativeUint); //Init Sieve i,oFs are Global begin i := n MOD SizePrDeFe; Ofs := (n DIV SizePrDeFe)*SizePrDeFe; SieveOneSieve(PrimeDecompField,Ofs); end;   procedure GetSmall(MaxIdx:Int32); var ZK: Array of Uint32; idx: UInt32; Begin If MaxIdx<1 then EXIT; writeln('The first ',MaxIdx,' zumkeller numbers'); Init_Sieve(0); setlength(ZK,MaxIdx); idx := Low(ZK); repeat if GetZumKeller(n,PrimeDecompField[i]) then Begin ZK[idx] := n; inc(idx); end; inc(i); inc(n); If i > High(PrimeDecompField) then begin dec(i,SizePrDeFe); inc(ofs,SizePrDeFe); SieveOneSieve(PrimeDecompField,Ofs); end; until idx >= MaxIdx; For idx := 0 to MaxIdx-1 do begin if idx MOD 20 = 0 then writeln; write(ZK[idx]:4); end; setlength(ZK,0); writeln; writeln; end;   procedure GetOdd(MaxIdx:Int32); var ZK: Array of Uint32; idx: UInt32; Begin If MaxIdx<1 then EXIT; writeln('The first odd 40 zumkeller numbers'); n := 1; Init_Sieve(n); setlength(ZK,MaxIdx); idx := Low(ZK); repeat if GetZumKeller(n,PrimeDecompField[i]) then Begin ZK[idx] := n; inc(idx); end; inc(i,2); inc(n,2); If i > High(PrimeDecompField) then begin dec(i,SizePrDeFe); inc(ofs,SizePrDeFe); SieveOneSieve(PrimeDecompField,Ofs); end; until idx >= MaxIdx; For idx := 0 to MaxIdx-1 do begin if idx MOD (80 DIV 8) = 0 then writeln; write(ZK[idx]:8); end; setlength(ZK,0); writeln; writeln; end;   procedure GetOddNot5(MaxIdx:Int32); var ZK: Array of Uint32; idx: UInt32; Begin If MaxIdx<1 then EXIT; writeln('The first odd 40 zumkeller numbers not ending in 5'); n := 1; Init_Sieve(n); setlength(ZK,MaxIdx); idx := Low(ZK); repeat if GetZumKeller(n,PrimeDecompField[i]) then Begin ZK[idx] := n; inc(idx); end; inc(i,2); inc(n,2); If n mod 5 = 0 then begin inc(i,2); inc(n,2); end; If i > High(PrimeDecompField) then begin dec(i,SizePrDeFe); inc(ofs,SizePrDeFe); SieveOneSieve(PrimeDecompField,Ofs); end; until idx >= MaxIdx; For idx := 0 to MaxIdx-1 do begin if idx MOD (80 DIV 8) = 0 then writeln; write(ZK[idx]:8); end; setlength(ZK,0); writeln; writeln; end; BEGIN InitSmallPrimes;   T0 := GetTickCount64; GetSmall(220); GetOdd(40); GetOddNot5(40);   writeln; n := 1;//8996229720;//1; Init_Sieve(n); writeln('Start ',n,' at ',i); T0 := GetTickCount64; MAX := (n DIV DELTAMAX+1)*DELTAMAX; count := 0; repeat writeln('Count of zumkeller numbers up to ',MAX:12); repeat if GetZumKeller(n,PrimeDecompField[i]) then inc(count); inc(i); inc(n); If i > High(PrimeDecompField) then begin dec(i,SizePrDeFe); inc(ofs,SizePrDeFe); SieveOneSieve(PrimeDecompField,Ofs); end; until n > MAX; writeln(n-1:10,' tested found ',count:10,' ratio ',count/n:10:7); MAX += DELTAMAX; until MAX>10*DELTAMAX; writeln('runtime ',(GetTickCount64-T0)/1000:8:3,' s'); writeln; writeln('Count of recursion 59,641,327 for 8,996,229,720'); n := 8996229720; Init_Sieve(n); T0 := GetTickCount64; Out_One_Sol(PrimeDecompField[i],n,true); writeln; writeln('runtime ',(GetTickCount64-T0)/1000:8:3,' s'); END.  
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
#EchoLisp
EchoLisp
  ;; to save space and time, we do'nt stringify Ω = 5^4^3^2 , ;; but directly extract tail and head and number of decimal digits   (lib 'bigint) ;; arbitrary size integers   (define e10000 (expt 10 10000)) ;; 10^10000   (define (last-n big (n 20)) (string-append "..." (number->string (modulo big (expt 10 n)))))   (define (first-n big (n 20)) (while (> big e10000) (set! big (/ big e10000))) ;; cut 10000 digits at a time (string-append (take (number->string big) n) "..."))   ;; faster than directly using (number-length big) (define (digits big (digits 0)) (while (> big e10000) (set! big (/ big e10000)) (set! digits (1+ digits))) (+ (* digits 10000) (number-length big)))   (define Ω (expt 5 (expt 4 (expt 3 2))))   (last-n Ω ) → "...92256259918212890625" (first-n Ω ) → "62060698786608744707..." (digits Ω ) → 183231      
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
nB[mat_] := Delete[mat // Flatten, 5] // Total;   nA[mat_] := Module[{l}, l = Flatten[mat][[{2, 3, 6, 9, 8, 7, 4, 1, 2}]]; Total[Map[If[#[[1]] == 0 && #[[2]] == 1, 1, 0] &, Partition[l, 2, 1]]] ];   iW1[mat_] := Module[{l = Flatten[mat]}, If[Apply[Times, l[[{2, 6, 8}]]] + Apply[Times, l[[{4, 6, 8}]]] == 0, 0, 1]]; iW2[mat_] := Module[{l = Flatten[mat]}, If[Apply[Times, l[[{2, 6, 4}]]] + Apply[Times, l[[{4, 2, 8}]]] == 0, 0, 1]];   check[i_, j_, dat_, t_] := Module[{mat, d = Dimensions[dat], r, c}, r = d[[1]]; c = d[[2]]; If[i > 1 && i < r && j > 1 && j < c, mat = dat[[i - 1 ;; i + 1, j - 1 ;; j + 1]]; If[dat[[i, j]] == 1 && nA[mat] == 1 && 2 <= nB[mat] <= 6 && If[t == 1, iW1[mat], iW2[mat]] == 0, 0, dat[[i, j]]], dat[[i, j]] ]];   iter[dat_] := Module[{i = Flatten[Outer[List, Range[Dimensions[dat][[1]]], Range[Dimensions[dat][[2]]]], 1], tmp}, tmp = Partition[check[#[[1]], #[[2]], dat, 1] & /@ i, Dimensions[dat][[2]]]; Partition[check[#[[1]], #[[2]], tmp, 2] & /@ i, Dimensions[tmp][[2]]]];     FixedPoint[iter, dat]
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
#Nim
Nim
import math, sequtils, strutils   type Bit = 0..1 BitMatrix = seq[seq[Bit]] # Two-dimensional array of 0/1. Neighbors = array[2..9, Bit] # Neighbor values.   const Symbols = [Bit(0): '.', Bit(1): '#']     func toBitMatrix(s: openArray[string]): BitMatrix = ## Convert an array of 01 strings into a BitMatrix. for row in s: assert row.allCharsInSet({'0', '1'}) result.add row.mapIt(Bit(ord(it) - ord('0')))     proc `$`(m: BitMatrix): string = ## Return the string representation of a BitMatrix. for row in m: echo row.mapIt(Symbols[it]).join()   # Templates to allow using double indexing. template `[]`(m: BitMatrix; i, j: Natural): Bit = m[i][j] template `[]=`(m: var BitMatrix; i, j: Natural; val: Bit) = m[i][j] = val     func neighbors(m: BitMatrix; i, j: int): Neighbors = ## Return the array of neighbors. [m[i-1, j], m[i-1, j+1], m[i, j+1], m[i+1, j+1], m[i+1, j], m[i+1, j-1], m[i, j-1], m[i-1, j-1]]   func transitions(p: Neighbors): int = ## Return the numbers of transitions from P2 to P9. for (i, j) in [(2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 2)]: result += ord(p[i] == 0 and p[j] == 1)   func thinned(m: BitMatrix): BitMatrix = ## Return a thinned version of "m". const Pair1 = [2, 8] const Pair2 = [4, 6] let rowMax = m.high let colMax = m[0].high result = m   while true: var changed = false   for step in 1..2: let (p1, p2) = if step == 1: (Pair1, Pair2) else: (Pair2, Pair1) var m = result for i in 1..<rowMax: for j in 1..<colMax:   # Check criteria. if m[i, j] == 0: # criterion 0. continue let p = m.neighbors(i, j) if sum(p) notin 2..6: # criterion 1. continue if transitions(p) != 1: # criterion 2. continue if p[p1[0]] + p[p2[0]] + p[p2[1]] == 3 or # criterion 3. p[p1[1]] + p[p2[0]] + p[p2[1]] == 3: # criterion 4. continue   # All criteria satisfied. Store a 0 in "result". result[i, j] = 0 changed = true   if not changed: break     when isMainModule:   const Input = ["00000000000000000000000000000000", "01111111110000000111111110000000", "01110001111000001111001111000000", "01110000111000001110000111000000", "01110001111000001110000000000000", "01111111110000001110000000000000", "01110111100000001110000111000000", "01110011110011101111001111011100", "01110001111011100111111110011100", "00000000000000000000000000000000"]   let input = Input.toBitMatrix() let output = input.thinned() echo "Input image:" echo input echo() echo "Output image:" echo output
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
#Factor
Factor
USING: formatting kernel locals make math sequences ;   :: fib<= ( n -- seq ) 1 2 [ [ dup n <= ] [ 2dup + [ , ] 2dip ] while drop , ] { } make ;   :: zeck ( n -- str ) 0 :> s! n fib<= <reversed> [ dup s + n <= [ s + s! 49 ] [ drop 48 ] if ] "" map-as ;   21 <iota> [ dup zeck "%2d: %6s\n" printf ] each
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
#Forth
Forth
: fib<= ( n -- n ) >r 0 1 BEGIN dup r@ <= WHILE tuck + REPEAT drop rdrop ;   : z. ( n -- ) dup fib<= dup . - BEGIN ?dup WHILE dup fib<= dup [char] + emit space . - REPEAT ;   : tab 9 emit ;   : zeckendorf ( -- ) 21 0 DO cr i 2 .r tab i z. LOOP ;
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.
#C.2B.2B
C++
#include <iostream>   int main() { bool is_open[100] = { false };   // do the 100 passes for (int pass = 0; pass < 100; ++pass) for (int door = pass; door < 100; door += pass+1) is_open[door] = !is_open[door];   // output the result for (int door = 0; door < 100; ++door) std::cout << "door #" << door+1 << (is_open[door]? " is open." : " is closed.") << std::endl; 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)
#ERRE
ERRE
DIM A%[100]  ! integer array DIM S$[50]  ! string array DIM R[50]  ! real array DIM R#[70]  ! long real array
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Pop11
Pop11
lvars a = 1.0 +: 1.0, b = 2.0 +: 5.0 ; a+b => a*b => 1/a => a-b => a-a => a/b => a/a =>   ;;; The same, but using exact values 1 +: 1 -> a; 2 +: 5 -> b; a+b => a*b => 1/a => a-b => a-a => a/b => a/a =>
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠'). Define standard coercion operators for casting int to frac etc. If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.). Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors. Related task   Perfect Numbers
#Ruby
Ruby
  for candidate in 2 .. 2**19 sum = Rational(1, candidate) for factor in 2 .. Integer.sqrt(candidate) if candidate % factor == 0 sum += Rational(1, factor) + Rational(1, candidate / factor) end end if sum.denominator == 1 puts "Sum of recipr. factors of %d = %d exactly %s" % [candidate, sum.to_i, sum == 1 ? "perfect!" : ""] end end
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#UNIX_Shell
UNIX Shell
function agm { float a=$1 g=$2 eps=${3:-1e-11} tmp while (( abs(a-g) > eps )); do print "debug: a=$a\tg=$g" tmp=$(( (a+g)/2.0 )) g=$(( sqrt(a*g) )) a=$tmp done echo $a }   agm $((1/sqrt(2))) 1
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as a g m ( a , g ) {\displaystyle \mathrm {agm} (a,g)} , and is equal to the limit of the sequence: a 0 = a ; g 0 = g {\displaystyle a_{0}=a;\qquad g_{0}=g} a n + 1 = 1 2 ( a n + g n ) ; g n + 1 = a n g n . {\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.} Since the limit of a n − g n {\displaystyle a_{n}-g_{n}} tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: a g m ( 1 , 1 / 2 ) {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})} Also see   mathworld.wolfram.com/Arithmetic-Geometric Mean
#VBA
VBA
Private Function agm(a As Double, g As Double, Optional tolerance As Double = 0.000000000000001) As Double Do While Abs(a - g) > tolerance tmp = a a = (a + g) / 2 g = Sqr(tmp * g) Debug.Print a Loop agm = a End Function Public Sub main() Debug.Print agm(1, 1 / Sqr(2)) End Sub
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
#J
J
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
#Java
Java
System.out.println(Math.pow(0, 0));
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#APL
APL
zz ← {⍵⍴⎕IO-⍨⍋⊃,/{(2|⍴⍵):⌽⍵⋄⍵}¨(⊂w)/¨⍨w{↓⍵∘.=⍨∪⍵}+/[1]⍵⊤w←⎕IO-⍨⍳×/⍵} ⍝ General zigzag (any rectangle) zzSq ← {zz,⍨⍵} ⍝ Square zigzag zzSq 5 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. Example a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). Task Find and show as output the first  30  Yellowstone numbers. Extra Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. Related tasks   Greatest common divisor.   Plot coordinate pairs. See also   The OEIS entry:   A098550 The Yellowstone permutation.   Applegate et al, 2015: The Yellowstone Permutation [1].
#Delphi
Delphi
  program Yellowstone_sequence;   {$APPTYPE CONSOLE}   uses System.SysUtils, Boost.Generics.Collection, Boost.Process;   function gdc(x, y: Integer): Integer; begin while y <> 0 do begin var tmp := x; x := y; y := tmp mod y; end; Result := x; end;   function Yellowstone(n: Integer): TArray<Integer>; var m: TDictionary<Integer, Boolean>; a: TArray<Integer>; begin m.Init; SetLength(a, n + 1); for var i := 1 to 3 do begin a[i] := i; m[i] := True; end;   var min := 4;   for var c := 4 to n do begin var i := min; repeat if not m[i, false] and (gdc(a[c - 1], i) = 1) and (gdc(a[c - 2], i) > 1) then begin a[c] := i; m[i] := true; if i = min then inc(min); Break; end; inc(i); until false; end;   Result := copy(a, 1, length(a)); end;   begin var x: TArray<Integer>; SetLength(x, 100); for var i in Range(100) do x[i] := i + 1;   var y := yellowstone(High(x));   writeln('The first 30 Yellowstone numbers are:'); for var i := 0 to 29 do Write(y[i], ' '); Writeln;   //Plotting   var plot := TPipe.Create('gnuplot -p', True); plot.WritelnA('unset key; plot ''-''');   for var i := 0 to High(x) do plot.WriteA('%d %d'#10, [x[i], y[i]]); plot.WritelnA('e');   writeln('Press enter to close'); Readln; plot.Kill; plot.Free; end.
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#AutoHotkey
AutoHotkey
test: yahooSearch("test", 1) yahooSearch("test", 2) return   yahooSearch(query, page) { global start := ((page - 1) * 10) + 1 filedelete, search.txt urldownloadtofile, % "http://search.yahoo.com/search?p=" . query . "&b=" . start, search.txt fileread, content, search.txt reg = <a class="yschttl spt" href=".+?" >(.+?)</a></h3></div><div class="abstr">(.+?)</div><span class=url>(.+?)</span>   index := found := 1 while (found := regexmatch(content, reg, self, found + 1)) { msgbox % title%A_Index% := fix(self1) content%A_Index% := fix(self2) url%A_Index% := fix(self3) } }   fix(url) { if pos := instr(url, "</a></h3></div>") StringLeft, url, url, pos - 1 url := regexreplace(url, "<.*?>") return url }
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.
#Scala
Scala
  package org.rosetta.arithmetic_evaluator.scala   object ArithmeticParser extends scala.util.parsing.combinator.RegexParsers {   def readExpression(input: String) : Option[()=>Int] = { parseAll(expr, input) match { case Success(result, _) => Some(result) case other => println(other) None } }   private def expr : Parser[()=>Int] = { (term<~"+")~expr ^^ { case l~r => () => l() + r() } | (term<~"-")~expr ^^ { case l~r => () => l() - r() } | term }   private def term : Parser[()=>Int] = { (factor<~"*")~term ^^ { case l~r => () => l() * r() } | (factor<~"/")~term ^^ { case l~r => () => l() / r() } | factor }   private def factor : Parser[()=>Int] = { "("~>expr<~")" | "\\d+".r ^^ { x => () => x.toInt } | failure("Expected a value") } }   object Main { def main(args: Array[String]) { println("""Please input the expressions. Type "q" to quit.""") var input: String = ""   do { input = readLine("> ") if (input != "q") { ArithmeticParser.readExpression(input).foreach(f => println(f())) } } while (input != "q") } }  
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.
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8)))   (de unpad (Lst) (while (=0 (car Lst)) (pop 'Lst) ) Lst )   (de numz (N) (let Fibs (1 1) (while (>= N (+ (car Fibs) (cadr Fibs))) (push 'Fibs (+ (car Fibs) (cadr Fibs))) ) (make (for I (uniq Fibs) (if (> I N) (link 0) (link 1) (dec 'N I) ) ) ) ) )   (de znum (Lst) (let Fibs (1 1) (do (dec (length Lst)) (push 'Fibs (+ (car Fibs) (cadr Fibs))) ) (sum '((X Y) (unless (=0 X) Y)) Lst (uniq Fibs) ) ) )   (de incz (Lst) (addz Lst (1)) )   (de decz (Lst) (subz Lst (1)) )   (de addz (Lst1 Lst2) (let Max (max (length Lst1) (length Lst2)) (reorg (mapcar + (need Max Lst1 0) (need Max Lst2 0)) ) ) )   (de subz (Lst1 Lst2) (use (@A @B) (let (Max (max (length Lst1) (length Lst2)) Lst (mapcar - (need Max Lst1 0) (need Max Lst2 0)) ) (loop (while (match '(@A 1 0 0 @B) Lst) (setq Lst (append @A (0 1 1) @B)) ) (while (match '(@A 1 -1 0 @B) Lst) (setq Lst (append @A (0 0 1) @B)) ) (while (match '(@A 1 -1 1 @B) Lst) (setq Lst (append @A (0 0 2) @B)) ) (while (match '(@A 1 0 -1 @B) Lst) (setq Lst (append @A (0 1 0) @B)) ) (while (match '(@A 2 0 0 @B) Lst) (setq Lst (append @A (1 1 1) @B)) ) (while (match '(@A 2 -1 0 @B) Lst) (setq Lst (append @A (1 0 1) @B)) ) (while (match '(@A 2 -1 1 @B) Lst) (setq Lst (append @A (1 0 2) @B)) ) (while (match '(@A 2 0 -1 @B) Lst) (setq Lst (append @A (1 1 0) @B)) ) (while (match '(@A 1 -1) Lst) (setq Lst (append @A (0 1))) ) (while (match '(@A 2 -1) Lst) (setq Lst (append @A (1 1))) ) (NIL (match '(@A -1 @B) Lst)) ) (reorg (unpad Lst)) ) ) )   (de mulz (Lst1 Lst2) (let (Sums (list Lst1) Mulz (0)) (mapc '((X) (when (= 1 (car X)) (setq Mulz (addz (cdr X) Mulz)) ) Mulz ) (mapcar '((X) (cons X (push 'Sums (addz (car Sums) (cadr Sums))) ) ) (reverse Lst2) ) ) ) )   (de divz (Lst1 Lst2) (let Q 0 (while (lez Lst2 Lst1) (setq Lst1 (subz Lst1 Lst2)) (setq Q (incz Q)) ) (list Q (or Lst1 (0))) ) )   (de reorg (Lst) (use (@A @B) (let Lst (reverse Lst) (loop (while (match '(@A 1 1 @B) Lst) (if @B (inc (nth @B 1)) (setq @B (1)) ) (setq Lst (append @A (0 0) @B) ) ) (while (match '(@A 2 @B) Lst) (inc (if (cdr @A) (tail 2 @A) @A ) ) (if @B (inc (nth @B 1)) (setq @B (1)) ) (setq Lst (append @A (0) @B)) ) (NIL (or (match '(@A 1 1 @B) Lst) (match '(@A 2 @B) Lst) ) ) ) (reverse Lst) ) ) )   (de lez (Lst1 Lst2) (let Max (max (length Lst1) (length Lst2)) (<= (need Max Lst1 0) (need Max Lst2 0)) ) )   (let (X 0 Y 0) (do 1024 (setq X (rand 1 1024)) (setq Y (rand 1 1024)) (test (numz (+ X Y)) (addz (numz X) (numz Y))) (test (numz (* X Y)) (mulz (numz X) (numz Y))) (test (numz (+ X 1)) (incz (numz X))) )   (do 1024 (setq X (rand 129 1024)) (setq Y (rand 1 128)) (test (numz (- X Y)) (subz (numz X) (numz Y))) (test (numz (/ X Y)) (car (divz (numz X) (numz Y)))) (test (numz (% X Y)) (cadr (divz (numz X) (numz Y)))) (test (numz (- X 1)) (decz (numz X))) ) )   (bye)
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.
#Python
Python
import copy   class Zeckendorf: def __init__(self, x='0'): q = 1 i = len(x) - 1 self.dLen = int(i / 2) self.dVal = 0 while i >= 0: self.dVal = self.dVal + (ord(x[i]) - ord('0')) * q q = q * 2 i = i -1   def a(self, n): i = n while True: if self.dLen < i: self.dLen = i j = (self.dVal >> (i * 2)) & 3 if j == 0 or j == 1: return if j == 2: if (self.dVal >> ((i + 1) * 2) & 1) != 1: return self.dVal = self.dVal + (1 << (i * 2 + 1)) return if j == 3: temp = 3 << (i * 2) temp = temp ^ -1 self.dVal = self.dVal & temp self.b((i + 1) * 2) i = i + 1   def b(self, pos): if pos == 0: self.inc() return if (self.dVal >> pos) & 1 == 0: self.dVal = self.dVal + (1 << pos) self.a(int(pos / 2)) if pos > 1: self.a(int(pos / 2) - 1) else: temp = 1 << pos temp = temp ^ -1 self.dVal = self.dVal & temp self.b(pos + 1) self.b(pos - (2 if pos > 1 else 1))   def c(self, pos): if (self.dVal >> pos) & 1 == 1: temp = 1 << pos temp = temp ^ -1 self.dVal = self.dVal & temp return self.c(pos + 1) if pos > 0: self.b(pos - 1) else: self.inc()   def inc(self): self.dVal = self.dVal + 1 self.a(0)   def __add__(self, rhs): copy = self rhs_dVal = rhs.dVal limit = (rhs.dLen + 1) * 2 for gn in range(0, limit): if ((rhs_dVal >> gn) & 1) == 1: copy.b(gn) return copy   def __sub__(self, rhs): copy = self rhs_dVal = rhs.dVal limit = (rhs.dLen + 1) * 2 for gn in range(0, limit): if (rhs_dVal >> gn) & 1 == 1: copy.c(gn) while (((copy.dVal >> ((copy.dLen * 2) & 31)) & 3) == 0) or (copy.dLen == 0): copy.dLen = copy.dLen - 1 return copy   def __mul__(self, rhs): na = copy.deepcopy(rhs) nb = copy.deepcopy(rhs) nr = Zeckendorf() dVal = self.dVal for i in range(0, (self.dLen + 1) * 2): if ((dVal >> i) & 1) > 0: nr = nr + nb nt = copy.deepcopy(nb) nb = nb + na na = copy.deepcopy(nt) return nr   def __str__(self): dig = ["00", "01", "10"] dig1 = ["", "1", "10"]   if self.dVal == 0: return '0' idx = (self.dVal >> ((self.dLen * 2) & 31)) & 3 sb = dig1[idx] i = self.dLen - 1 while i >= 0: idx = (self.dVal >> (i * 2)) & 3 sb = sb + dig[idx] i = i - 1 return sb   # main print "Addition:" 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
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory <is_prime divisor_sum divisors vecsum forcomb lastfor>;   sub in_columns { my($columns, $values) = @_; my @v = split ' ', $values; my $width = int(80/$columns); printf "%${width}d"x$columns."\n", @v[$_*$columns .. -1+(1+$_)*$columns] for 0..-1+@v/$columns; print "\n"; }   sub is_Zumkeller { my($n) = @_; return 0 if is_prime($n); my @divisors = divisors($n); return 0 unless @divisors > 2 && 0 == @divisors % 2; my $sigma = divisor_sum($n); return 0 unless 0 == $sigma%2 && ($sigma/2) >= $n; if (1 == $n%2) { return 1 } else { my $Z = 0; forcomb { $Z++, lastfor if vecsum(@divisors[@_]) == $sigma/2 } @divisors; return $Z; } }   use constant Inf => 1e10;   say 'First 220 Zumkeller numbers:'; my $n = 0; my $z; $z .= do { $n < 220 ? (is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf; in_columns(20, $z);   say 'First 40 odd Zumkeller numbers:'; $n = 0; $z = ''; $z .= do { $n < 40 ? (!!($_%2) and is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf; in_columns(10, $z);   say 'First 40 odd Zumkeller numbers not divisible by 5:'; $n = 0; $z = ''; $z .= do { $n < 40 ? (!!($_%2 and $_%5) and is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf; in_columns(10, $z);
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
#Elixir
Elixir
defmodule Arbitrary do def pow(_,0), do: 1 def pow(b,e) when e > 0, do: pow(b,e,1)   defp pow(b,1,acc), do: acc * b defp pow(b,p,acc) when rem(p,2)==0, do: pow(b*b,div(p,2),acc) defp pow(b,p,acc), do: pow(b,p-1,acc*b)   def test do s = pow(5,pow(4,pow(3,2))) |> to_string l = String.length(s) prefix = String.slice(s,0,20) suffix = String.slice(s,-20,20) IO.puts "Length: #{l}\nPrefix:#{prefix}\nSuffix:#{suffix}" end end Arbitrary.test
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
#Emacs_Lisp
Emacs Lisp
(let* ((integer-width (* 65536 16)) ; raise bignum limit from 65536 bits to avoid overflow error (answer (number-to-string (expt 5 (expt 4 (expt 3 2))))) (length (length answer))) (message "%s has %d digits" (if (> length 40) (format "%s...%s" (substring answer 0 20) (substring answer (- length 20) length)) answer) length))
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
#Perl
Perl
use List::Util qw(sum min);   $source = <<'END'; ............................................................ ..#################...................#############......... ..##################...............################......... ..###################............##################......... ..########.....#######..........###################......... ....######.....#######.........#######.......######......... ....######.....#######........#######....................... ....#################.........#######....................... ....################..........#######....................... ....#################.........#######....................... ....######.....#######........#######....................... ....######.....#######........#######....................... ....######.....#######.........#######.......######......... ..########.....#######..........###################......... ..########.....#######.######....##################.######.. ..########.....#######.######......################.######.. ..########.....#######.######.........#############.######.. ............................................................ END   for $line (split "\n", $source) { push @lines, [map { 1 & ord $_ } split '', $line] }   $v = @lines; $h = @{$lines[0]}; push @black, @$_ for @lines; @p8 = ((-$h-1), (-$h+0), (-$h+1), # flatland distances to 8 neighbors. 0-1, 0+1, $h-1, $h+0, $h+1)[1,2,4,7,6,5,3,0]; # (in cycle order)   # Candidates have 8 neighbors and are known black @cand = grep { $black[$_] } map { my $x = $_; map $_*$h + $x, 1..$v-2 } 1..$h-2;   do { sub seewhite { my($w1,$w2) = @_; my(@results); sub cycles { my(@neighbors)=@_; my $c; $c += $neighbors[$_] < $neighbors[($_+1)%8] for 0..$#neighbors; return $c } sub blacks { my(@neighbors)=@_; sum @neighbors }   @prior = @cand; @cand = (); for $p (@prior) { @n = @black[map { $_+$p } @p8]; if (cycles(@n) == 1 and 2 <= sum(blacks(@n)) and sum(blacks(@n)) <= 6 and min(@n[@$w1]) == 0 and min(@n[@$w2]) == 0) { push @results, $p; } else { push @cand, $p } } return @results; }   @goners1 = seewhite [0,2,4], [2,4,6]; @black[@goners1] = 0 x @goners1; @goners2 = seewhite [0,2,6], [0,4,6]; @black[@goners2] = 0 x @goners2; } until @goners1 == 0 and @goners2 == 0;   while (@black) { push @thinned, join '', qw<. #>[splice(@black,0,$h)] }   print join "\n", @thinned;
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
#Fortran
Fortran
F(N) = ((1 + SQRT(5))**N - (1 - SQRT(5))**N)/(SQRT(5)*2**N)