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/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#PureBasic
PureBasic
EnableExplicit DisableDebugger   Procedure.d maxXY(a.d,b.d,c.d,d.d) If a<b : Swap a,b : EndIf If a<c : Swap a,c : EndIf If a<d : Swap a,d : EndIf ProcedureReturn a EndProcedure   Procedure.d minXY(a.d,b.d,c.d,d.d) If a>b : Swap a,b : EndIf If a>c : Swap a,c : EndIf If a>d : Swap a,d : EndIf ProcedureReturn a EndProcedure   Procedure Ptree(x1.d, y1.d, x2.d, y2.d, d.i=0) If d>10 : ProcedureReturn : EndIf   Define dx.d=x2-x1, dy.d=y1-y2, x3.d=x2-dy, y3.d=y2-dx, x4.d=x1-dy, y4.d=y1-dx, x5.d=x4+(dx-dy)/2.0, y5.d=y4-(dx+dy)/2.0, p1.d=(maxXY(x1,x2,x3,x4)+minXY(x1,x2,x3,x4))/2.0, p2.d=(maxXY(y1,y2,y3,y4)+minXY(y1,y2,y3,y4))/2.0, p3.d=(maxXY(x1,x2,x3,x4)-minXY(x1,x2,x3,x4))   FrontColor(RGB(Random(125,1),Random(255,125),Random(125,1))) LineXY(x1,y1,x2,y2) LineXY(x2,y2,x3,y3) LineXY(x3,y3,x4,y4) LineXY(x4,y4,x1,y1) BoxedGradient(minXY(x1,x2,x3,x4),minXY(y1,y2,y3,y4),p3,p3) FillArea(p1,p2,-1)   Ptree(x4,y4,x5,y5,d+1) Ptree(x5,y5,x3,y3,d+1)   EndProcedure   Define w1.i=800, h1.i=w1*11/16, w2.i=w1/2, di.i=w1/12   If OpenWindow(0,#PB_Ignore,#PB_Ignore,w1,h1,"Pythagoras tree") If CreateImage(0,w1,h1,24,0) And StartDrawing(ImageOutput(0)) DrawingMode(#PB_2DDrawing_Gradient) BackColor($000000) Ptree(w2-di,h1-10,w2+di,h1-10) StopDrawing() EndIf ImageGadget(0,0,0,0,0,ImageID(0)) Repeat : Until WaitWindowEvent(50)=#PB_Event_CloseWindow EndIf End
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#C.23
C#
using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double;     class Program {   static void Main(string[] args) { Matrix<double> A = DenseMatrix.OfArray(new double[,] { { 12, -51, 4 }, { 6, 167, -68 }, { -4, 24, -41 } }); Console.WriteLine("A:"); Console.WriteLine(A); var qr = A.QR(); Console.WriteLine(); Console.WriteLine("Q:"); Console.WriteLine(qr.Q); Console.WriteLine(); Console.WriteLine("R:"); Console.WriteLine(qr.R); } }
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#68000_Assembly
68000 Assembly
LEA $000200,A3 JSR PrintString ;(my print routine is 255-terminated and there just so happens to be an FF after the name of the game.)
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#AArch64_Assembly
AArch64 Assembly
sp+0 = argc sp+8 = argv[0] sp+16 = argv[1] ...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Common_Lisp
Common Lisp
(defun mmul (a b) (loop for x in a collect (loop for y in x for z in b sum (* y z))))   (defun count-tri (lim &aux (prim 0) (cnt 0)) (labels ((count1 (tr &aux (peri (reduce #'+ tr))) (when (<= peri lim) (incf prim) (incf cnt (truncate lim peri)) (count1 (mmul '(( 1 -2 2) ( 2 -1 2) ( 2 -2 3)) tr)) (count1 (mmul '(( 1 2 2) ( 2 1 2) ( 2 2 3)) tr)) (count1 (mmul '((-1 2 2) (-2 1 2) (-2 2 3)) tr))))) (count1 '(3 4 5)) (format t "~a: ~a prim, ~a all~%" lim prim cnt)))   (loop for p from 2 do (count-tri (expt 10 p)))
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Scheme
Scheme
((lambda (s) (display (list s (list (quote quote) s)))) (quote (lambda (s) (display (list s (list (quote quote) s))))))
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of gen #1 */ x2 = [0, 0, 0] /* list of three last values of gen #2 */ method seed(u64 seed_state) assert seed_state in range >0 and < d x1 = [seed_state, 0, 0] x2 = [seed_state, 0, 0] end method method next_int() x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1 x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2 x1 = [x1i, x1[0], x1[1]] /* Keep last three */ x2 = [x2i, x2[0], x2[1]] /* Keep last three */ z = (x1i - x2i) % m1 answer = (z + 1) return answer end method method next_float(): return float next_int() / d end method end class MRG32k3a Use: random_gen = instance MRG32k3a random_gen.seed(1234567) print(random_gen.next_int()) /* 1459213977 */ print(random_gen.next_int()) /* 2827710106 */ print(random_gen.next_int()) /* 4245671317 */ print(random_gen.next_int()) /* 3877608661 */ print(random_gen.next_int()) /* 2595287583 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers generated with the seed `1234567` are as shown above Show that for an initial seed of '987654321' the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931 Show your output here, on this page.
#Sidef
Sidef
class MRG32k3a(seed) {   define( m1 = (2**32 - 209) m2 = (2**32 - 22853) )   define( a1 = %n< 0 1403580 -810728> a2 = %n<527612 0 -1370589> )   has x1 = [seed, 0, 0] has x2 = x1.clone   method next_int { x1.unshift(a1.map_kv {|k,v| v * x1[k] }.sum % m1); x1.pop x2.unshift(a2.map_kv {|k,v| v * x2[k] }.sum % m2); x2.pop (x1[0] - x2[0]) % (m1 + 1) }   method next_float { self.next_int / (m1 + 1) -> float } }   say "Seed: 1234567, first 5 values:" var rng = MRG32k3a(seed: 1234567) 5.of { rng.next_int }.each { .say }   say "\nSeed: 987654321, values histogram:"; var rng = MRG32k3a(seed: 987654321) var freq = 100_000.of { rng.next_float * 5 -> int }.freq freq.sort.each_2d {|k,v| say "#{k} #{v}" }
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Ring
Ring
# Project : Pythagorean quadruples   limit = 2200 pq = list(limit) for n = 1 to limit for m = 1 to limit for p = 1 to limit for x = 1 to limit if pow(x,2) = pow(n,2) + pow(m,2) + pow(p,2) pq[x] = 1 ok next next next next pqstr = "" for d = 1 to limit if pq[d] = 0 pqstr = pqstr + d + " " ok next see pqstr + nl  
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Ruby
Ruby
n = 2200 l_add, l = {}, {} 1.step(n) do |x| x2 = x*x x.step(n) {|y| l_add[x2 + y*y] = true} end   s = 3 1.step(n) do |x| s1 = s s += 2 s2 = s (x+1).step(n) do |y| l[y] = true if l_add[s1] s1 += s2 s2 += 2 end end   puts (1..n).reject{|x| l[x]}.join(" ")  
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Python
Python
from turtle import goto, pu, pd, color, done   def level(ax, ay, bx, by, depth=0): if depth > 0: dx,dy = bx-ax, ay-by x3,y3 = bx-dy, by-dx x4,y4 = ax-dy, ay-dx x5,y5 = x4 + (dx - dy)/2, y4 - (dx + dy)/2 goto(ax, ay), pd() for x, y in ((bx, by), (x3, y3), (x4, y4), (ax, ay)): goto(x, y) pu() level(x4,y4, x5,y5, depth - 1) level(x5,y5, x3,y3, depth - 1)   if __name__ == '__main__': color('red', 'yellow') pu() level(-100, 500, 100, 500, depth=8) done()
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#11l
11l
I problem exit(1)
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#C.2B.2B
C++
/* * g++ -O3 -Wall --std=c++11 qr_standalone.cpp -o qr_standalone */ #include <cstdio> #include <cstdlib> #include <cstring> // for memset #include <limits> #include <iostream> #include <vector>   #include <math.h>   class Vector;   class Matrix {   public: // default constructor (don't allocate) Matrix() : m(0), n(0), data(nullptr) {}   // constructor with memory allocation, initialized to zero Matrix(int m_, int n_) : Matrix() { m = m_; n = n_; allocate(m_,n_); }   // copy constructor Matrix(const Matrix& mat) : Matrix(mat.m,mat.n) {   for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) (*this)(i,j) = mat(i,j); }   // constructor from array template<int rows, int cols> Matrix(double (&a)[rows][cols]) : Matrix(rows,cols) {   for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) (*this)(i,j) = a[i][j]; }   // destructor ~Matrix() { deallocate(); }     // access data operators double& operator() (int i, int j) { return data[i+m*j]; } double operator() (int i, int j) const { return data[i+m*j]; }   // operator assignment Matrix& operator=(const Matrix& source) {   // self-assignment check if (this != &source) { if ( (m*n) != (source.m * source.n) ) { // storage cannot be reused allocate(source.m,source.n); // re-allocate storage } // storage can be used, copy data std::copy(source.data, source.data + source.m*source.n, data); } return *this; }   // compute minor void compute_minor(const Matrix& mat, int d) {   allocate(mat.m, mat.n);   for (int i = 0; i < d; i++) (*this)(i,i) = 1.0; for (int i = d; i < mat.m; i++) for (int j = d; j < mat.n; j++) (*this)(i,j) = mat(i,j);   }   // Matrix multiplication // c = a * b // c will be re-allocated here void mult(const Matrix& a, const Matrix& b) {   if (a.n != b.m) { std::cerr << "Matrix multiplication not possible, sizes don't match !\n"; return; }   // reallocate ourself if necessary i.e. current Matrix has not valid sizes if (a.m != m or b.n != n) allocate(a.m, b.n);   memset(data,0,m*n*sizeof(double));   for (int i = 0; i < a.m; i++) for (int j = 0; j < b.n; j++) for (int k = 0; k < a.n; k++) (*this)(i,j) += a(i,k) * b(k,j);   }   void transpose() { for (int i = 0; i < m; i++) { for (int j = 0; j < i; j++) { double t = (*this)(i,j); (*this)(i,j) = (*this)(j,i); (*this)(j,i) = t; } } }   // take c-th column of m, put in v void extract_column(Vector& v, int c);   // memory allocation void allocate(int m_, int n_) {   // if already allocated, memory is freed deallocate();   // new sizes m = m_; n = n_;   data = new double[m_*n_]; memset(data,0,m_*n_*sizeof(double));   } // allocate   // memory free void deallocate() {   if (data) delete[] data;   data = nullptr;   }   int m, n;   private: double* data;   }; // struct Matrix   // column vector class Vector {   public: // default constructor (don't allocate) Vector() : size(0), data(nullptr) {}   // constructor with memory allocation, initialized to zero Vector(int size_) : Vector() { size = size_; allocate(size_); }   // destructor ~Vector() { deallocate(); }   // access data operators double& operator() (int i) { return data[i]; } double operator() (int i) const { return data[i]; }   // operator assignment Vector& operator=(const Vector& source) {   // self-assignment check if (this != &source) { if ( size != (source.size) ) { // storage cannot be reused allocate(source.size); // re-allocate storage } // storage can be used, copy data std::copy(source.data, source.data + source.size, data); } return *this; }   // memory allocation void allocate(int size_) {   deallocate();   // new sizes size = size_;   data = new double[size_]; memset(data,0,size_*sizeof(double));   } // allocate   // memory free void deallocate() {   if (data) delete[] data;   data = nullptr;   }   // ||x|| double norm() { double sum = 0; for (int i = 0; i < size; i++) sum += (*this)(i) * (*this)(i); return sqrt(sum); }   // divide data by factor void rescale(double factor) { for (int i = 0; i < size; i++) (*this)(i) /= factor; }   void rescale_unit() { double factor = norm(); rescale(factor); }   int size;   private: double* data;   }; // class Vector   // c = a + b * s void vmadd(const Vector& a, const Vector& b, double s, Vector& c) { if (c.size != a.size or c.size != b.size) { std::cerr << "[vmadd]: vector sizes don't match\n"; return; }   for (int i = 0; i < c.size; i++) c(i) = a(i) + s * b(i); }   // mat = I - 2*v*v^T // !!! m is allocated here !!! void compute_householder_factor(Matrix& mat, const Vector& v) {   int n = v.size; mat.allocate(n,n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat(i,j) = -2 * v(i) * v(j); for (int i = 0; i < n; i++) mat(i,i) += 1; }   // take c-th column of a matrix, put results in Vector v void Matrix::extract_column(Vector& v, int c) { if (m != v.size) { std::cerr << "[Matrix::extract_column]: Matrix and Vector sizes don't match\n"; return; }   for (int i = 0; i < m; i++) v(i) = (*this)(i,c); }   void matrix_show(const Matrix& m, const std::string& str="") { std::cout << str << "\n"; for(int i = 0; i < m.m; i++) { for (int j = 0; j < m.n; j++) { printf(" %8.3f", m(i,j)); } printf("\n"); } printf("\n"); }   // L2-norm ||A-B||^2 double matrix_compare(const Matrix& A, const Matrix& B) { // matrices must have same size if (A.m != B.m or A.n != B.n) return std::numeric_limits<double>::max();   double res=0; for(int i = 0; i < A.m; i++) { for (int j = 0; j < A.n; j++) { res += (A(i,j)-B(i,j)) * (A(i,j)-B(i,j)); } }   res /= A.m*A.n; return res; }   void householder(Matrix& mat, Matrix& R, Matrix& Q) {   int m = mat.m; int n = mat.n;   // array of factor Q1, Q2, ... Qm std::vector<Matrix> qv(m);   // temp array Matrix z(mat); Matrix z1;   for (int k = 0; k < n && k < m - 1; k++) {   Vector e(m), x(m); double a;   // compute minor z1.compute_minor(z, k);   // extract k-th column into x z1.extract_column(x, k);   a = x.norm(); if (mat(k,k) > 0) a = -a;   for (int i = 0; i < e.size; i++) e(i) = (i == k) ? 1 : 0;   // e = x + a*e vmadd(x, e, a, e);   // e = e / ||e|| e.rescale_unit();   // qv[k] = I - 2 *e*e^T compute_householder_factor(qv[k], e);   // z = qv[k] * z1 z.mult(qv[k], z1);   }   Q = qv[0];   // after this loop, we will obtain Q (up to a transpose operation) for (int i = 1; i < n && i < m - 1; i++) {   z1.mult(qv[i], Q); Q = z1;   }   R.mult(Q, mat); Q.transpose(); }   double in[][3] = { { 12, -51, 4}, { 6, 167, -68}, { -4, 24, -41}, { -1, 1, 0}, { 2, 0, 3}, };   int main() { Matrix A(in); Matrix Q, R;   matrix_show(A,"A");   // compute QR decompostion householder(A, R, Q);   matrix_show(Q,"Q"); matrix_show(R,"R");   // compare Q*R to the original matrix A Matrix A_check; A_check.mult(Q, R);   // compute L2 norm ||A-A_check||^2 double l2 = matrix_compare(A,A_check);   // display Q*R matrix_show(A_check, l2 < 1e-12 ? "A == Q * R ? yes" : "A == Q * R ? no");   return EXIT_SUCCESS; }  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Ada
Ada
with Ada.Command_Line, Ada.Text_IO;   procedure Command_Name is begin Ada.Text_IO.Put_Line(Ada.Command_Line.Command_Name); end Command_Name;
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Aime
Aime
o_text(argv(0)); o_byte('\n');
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Crystal
Crystal
class PythagoranTriplesCounter def initialize(limit = 0) @limit = limit @total = 0 @primitives = 0 generate_triples(3, 4, 5) end   def total; @total end def primitives; @primitives end   private def generate_triples(a, b, c) perim = a + b + c return if perim > @limit   @primitives += 1 @total += @limit // perim   generate_triples( a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c ) generate_triples( a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c ) generate_triples(-a+2*b+2*c,-2*a+b+2*c,-2*a+2*b+3*c ) end end   perim = 10 while perim <= 100_000_000 c = PythagoranTriplesCounter.new perim p [perim, c.total, c.primitives] perim *= 10 end
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Seed7
Seed7
$ include "seed7_05.s7i"; const array string: prog is []( "$ include \"seed7_05.s7i\";", "const array string: prog is [](", "const proc: main is func", " local var integer: number is 0;", " begin", " for number range 1 to 2 do writeln(prog[number]); end for;", " for number range 1 to 11 do", " writeln(literal(prog[number]) <& \",\");", " end for;", " writeln(literal(prog[12]) <& \");\");", " for number range 3 to 12 do writeln(prog[number]); end for;", " end func;"); const proc: main is func local var integer: number is 0; begin for number range 1 to 2 do writeln(prog[number]); end for; for number range 1 to 11 do writeln(literal(prog[number]) <& ","); end for; writeln(literal(prog[12]) <& ");"); for number range 3 to 12 do writeln(prog[number]); end for; end func;
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Shale
Shale
i var i "i var i %c%s%c = 34 i 34 i printf" = 34 i 34 i printf
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of gen #1 */ x2 = [0, 0, 0] /* list of three last values of gen #2 */ method seed(u64 seed_state) assert seed_state in range >0 and < d x1 = [seed_state, 0, 0] x2 = [seed_state, 0, 0] end method method next_int() x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1 x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2 x1 = [x1i, x1[0], x1[1]] /* Keep last three */ x2 = [x2i, x2[0], x2[1]] /* Keep last three */ z = (x1i - x2i) % m1 answer = (z + 1) return answer end method method next_float(): return float next_int() / d end method end class MRG32k3a Use: random_gen = instance MRG32k3a random_gen.seed(1234567) print(random_gen.next_int()) /* 1459213977 */ print(random_gen.next_int()) /* 2827710106 */ print(random_gen.next_int()) /* 4245671317 */ print(random_gen.next_int()) /* 3877608661 */ print(random_gen.next_int()) /* 2595287583 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers generated with the seed `1234567` are as shown above Show that for an initial seed of '987654321' the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931 Show your output here, on this page.
#uBasic.2F4tH
uBasic/4tH
@(0) = 0 ' First generator @(1) = 1403580 @(2) = -810728 m = SHL(1, 32) - 209   @(3) = 527612 ' Second generator @(4) = 0 @(5) = -1370589 n = SHL(1, 32) - 22853   d = SHL(1, 32) - 209 + 1 ' m + 1   Proc _Seed(1234567) Print FUNC(_NextInt) Print FUNC(_NextInt) Print FUNC(_NextInt) Print FUNC(_NextInt) Print FUNC(_NextInt) Print End   _Mod Param(2) Local(1) c@ = a@ % b@ If c@ < 0 Then If b@ < 0 Then Return (c@-b@) Else Return (c@+b@) Endif EndIf Return (c@)   _Seed Param(1) ' seed the PRNG @(6) = a@ @(7) = 0 @(8) = 0   @(9) = a@ @(10) = 0 @(11) = 0 Return   _NextInt ' get the next random integer value Local(3)   a@ = FUNC(_Mod((@(0) * @(6) + @(1) * @(7) + @(2) * @(8)), m)) b@ = FUNC(_Mod((@(3) * @(9) + @(4) * @(10) + @(5) * @(11)), n)) c@ = FUNC(_Mod(a@ - b@, m))   ' keep last three values of the first generator @(8) = @(7) @(7) = @(6) @(6) = a@   ' keep last three values of the second generator @(11) = @(10) @(10) = @(9) @(9) = b@   Return (c@ + 1)
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of gen #1 */ x2 = [0, 0, 0] /* list of three last values of gen #2 */ method seed(u64 seed_state) assert seed_state in range >0 and < d x1 = [seed_state, 0, 0] x2 = [seed_state, 0, 0] end method method next_int() x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1 x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2 x1 = [x1i, x1[0], x1[1]] /* Keep last three */ x2 = [x2i, x2[0], x2[1]] /* Keep last three */ z = (x1i - x2i) % m1 answer = (z + 1) return answer end method method next_float(): return float next_int() / d end method end class MRG32k3a Use: random_gen = instance MRG32k3a random_gen.seed(1234567) print(random_gen.next_int()) /* 1459213977 */ print(random_gen.next_int()) /* 2827710106 */ print(random_gen.next_int()) /* 4245671317 */ print(random_gen.next_int()) /* 3877608661 */ print(random_gen.next_int()) /* 2595287583 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers generated with the seed `1234567` are as shown above Show that for an initial seed of '987654321' the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931 Show your output here, on this page.
#Wren
Wren
// constants var A1 = [0, 1403580, -810728] var M1 = 2.pow(32) - 209 var A2 = [527612, 0, -1370589] var M2 = 2.pow(32) - 22853 var D = M1 + 1   // Python style modulus var Mod = Fn.new { |x, y| var m = x % y return (m < 0) ? m + y.abs : m }   class MRG32k3a { construct new() { _x1 = [0, 0, 0] _x2 = [0, 0, 0] }   seed(seedState) { if (seedState <= 0 || seedState >= D) { Fiber.abort("Argument must be in the range [0, %(D)].") } _x1 = [seedState, 0, 0] _x2 = [seedState, 0, 0] }   nextInt { var x1i = Mod.call(A1[0]*_x1[0] + A1[1]*_x1[1] + A1[2]*_x1[2], M1) var x2i = Mod.call(A2[0]*_x2[0] + A2[1]*_x2[1] + A2[2]*_x2[2], M2) _x1 = [x1i, _x1[0], _x1[1]] /* keep last three */ _x2 = [x2i, _x2[0], _x2[1]] /* keep last three */ return Mod.call(x1i - x2i, M1) + 1 }   nextFloat { nextInt / D } }   var randomGen = MRG32k3a.new() randomGen.seed(1234567) for (i in 0..4) System.print(randomGen.nextInt)   var counts = List.filled(5, 0) randomGen.seed(987654321) for (i in 1..1e5) { var i = (randomGen.nextFloat * 5).floor counts[i] = counts[i] + 1 } System.print("\nThe counts for 100,000 repetitions are:") for (i in 0..4) System.print("  %(i) : %(counts[i])")
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Rust
Rust
  use std::collections::BinaryHeap;   fn a094958_iter() -> Vec<u16> { (0..12) .map(|n| vec![1 << n, 5 * (1 << n)]) .flatten() .filter(|x| x < &2200) .collect::<BinaryHeap<u16>>() .into_sorted_vec() }   fn a094958_filter() -> Vec<u16> { (1..2200) // ported from Sidef .filter(|n| ((n & (n - 1) == 0) || (n % 5 == 0 && ((n / 5) & (n / 5 - 1) == 0)))) .collect() }   fn a094958_loop() -> Vec<u16> { let mut v = vec![]; for n in 0..12 { v.push(1 << n); if 5 * (1 << n) < 2200 { v.push(5 * (1 << n)); } } v.sort(); return v; }   fn main() { println!("{:?}", a094958_iter()); println!("{:?}", a094958_loop()); println!("{:?}", a094958_filter()); }   #[cfg(test)] mod tests { use super::*; static HAPPY: &str = "[1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64, 80, 128, 160, 256, 320, 512, 640, 1024, 1280, 2048]"; #[test] fn test_a094958_iter() { assert!(format!("{:?}", a094958_iter()) == HAPPY); } #[test] fn test_a094958_loop() { assert!(format!("{:?}", a094958_loop()) == HAPPY); } #[test] fn test_a094958_filter() { assert!(format!("{:?}", a094958_filter()) == HAPPY); } }  
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Scala
Scala
object PythagoreanQuadruple extends App { val MAX = 2200 val MAX2: Int = MAX * MAX * 2 val found = Array.ofDim[Boolean](MAX + 1) val a2b2 = Array.ofDim[Boolean](MAX2 + 1) var s = 3 for (a <- 1 to MAX) { val a2 = a * a   for (b <- a to MAX) a2b2(a2 + b * b) = true }   for (c <- 1 to MAX) { var s1 = s s += 2 var s2 = s for (d <- (c + 1) to MAX) { if (a2b2(s1)) found(d) = true s1 += s2 s2 += 2 } }   println(f"The values of d <= ${MAX}%d which can't be represented:") val notRepresented = (1 to MAX).filterNot(d => found(d) ) println(notRepresented.mkString(" "))   }
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#R
R
## Recursive PT plotting pythtree <- function(ax,ay,bx,by,d) { if(d<0) {return()}; clr="darkgreen"; dx=bx-ax; dy=ay-by; x3=bx-dy; y3=by-dx; x4=ax-dy; y4=ay-dx; x5=x4+(dx-dy)/2; y5=y4-(dx+dy)/2; segments(ax,-ay,bx,-by, col=clr); segments(bx,-by,x3,-y3, col=clr); segments(x3,-y3,x4,-y4, col=clr); segments(x4,-y4,ax,-ay, col=clr); pythtree(x4,y4,x5,y5,d-1); pythtree(x5,y5,x3,y3,d-1); } ## Plotting Pythagoras Tree. aev 3/27/17 ## x1,y1,x2,y2 - starting position ## ord - order/depth, fn - file name, ttl - plot title. pPythagorasT <- function(x1, y1,x2, y2, ord, fn="", ttl="") { cat(" *** START PYTHT:", date(), "\n"); m=640; i=j=k=m1=m-2; x=y=d=dm=0; if(fn=="") {pf=paste0("PYTHTR", ord, ".png")} else {pf=paste0(fn, ".png")}; if(ttl=="") {ttl=paste0("Pythagoras tree, order - ", ord)}; cat(" *** Plot file -", pf, "title:", ttl, "\n"); plot(NA, xlim=c(0,m), ylim=c(-m,0), xlab="", ylab="", main=ttl); pythtree(x1,y1, x2,y2, ord); dev.copy(png, filename=pf, width=m, height=m); dev.off(); graphics.off(); cat(" *** END PYTHT:",date(),"\n"); } ## Executing: pPythagorasT(275,500,375,500,9) pPythagorasT(275,500,375,500,7)
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#QB64
QB64
_Title "Pythagoras Tree"   Dim As Integer sw, sh sw = 640 sh = 480   Screen _NewImage(sw, sh, 32)   Call pythTree(sw / 2 - sw / 12, sh - 30, sw / 2 + sw / 12, sh - 30, 0)   Sleep System   Sub pythTree (ax As Integer, ay As Integer, bx As Integer, by As Integer, depth As Integer) Dim As Single cx, cy, dx, dy, ex, ey Dim As Integer c   cx = ax - ay + by cy = ax + ay - bx dx = bx + by - ay dy = ax - bx + by ex = (cx - cy + dx + dy) * 0.5 ey = (cx + cy - dx + dy) * 0.5 c = depth * 15 Color _RGB(c Mod 256, Abs((255 - c)) Mod 256, (144 + c) Mod 256) Line (cx, cy)-(ax, ay) Line (ax, ay)-(bx, by) Line (bx, by)-(dx, dy) Line (dx, dy)-(cx, cy) Line (cx, cy)-(ex, ey) Line (ex, ey)-(dx, dy) If depth < 12 Then Call pythTree(cx, cy, ex, ey, depth + 1) Call pythTree(ex, ey, dx, dy, depth + 1) End If End Sub
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#6502_Assembly
6502 Assembly
;assuming this is not a subroutine and runs inline. cmp TestValue ;a label for a memory address that contains some value we want to test the accumulator against beq continue rts  ;unlike the Z80 there is no conditional return so we have to branch around the return instruction. continue:
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program ending64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Initialized data */ /*******************************************/ .data /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program   OK: // end program OK mov x0,0 // return code b 100f NONOK: // if error detected end program no ok mov x0,1 // return code 100: // standard end of the program mov x8,EXIT // request to exit program svc 0 // perform the system call Linux /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#Common_Lisp
Common Lisp
(defun sign (x) (if (zerop x) x (/ x (abs x))))   (defun norm (x) (let ((len (car (array-dimensions x)))) (sqrt (loop for i from 0 to (1- len) sum (expt (aref x i 0) 2)))))   (defun make-unit-vector (dim) (let ((vec (make-array `(,dim ,1) :initial-element 0.0d0))) (setf (aref vec 0 0) 1.0d0) vec))   ;; Return a nxn identity matrix. (defun eye (n) (let ((I (make-array `(,n ,n) :initial-element 0))) (loop for j from 0 to (- n 1) do (setf (aref I j j) 1)) I))   (defun array-range (A ma mb na nb) (let* ((mm (1+ (- mb ma))) (nn (1+ (- nb na))) (B (make-array `(,mm ,nn) :initial-element 0.0d0)))   (loop for i from 0 to (1- mm) do (loop for j from 0 to (1- nn) do (setf (aref B i j) (aref A (+ ma i) (+ na j))))) B))   (defun rows (A) (car (array-dimensions A))) (defun cols (A) (cadr (array-dimensions A))) (defun mcol (A n) (array-range A 0 (1- (rows A)) n n)) (defun mrow (A n) (array-range A n n 0 (1- (cols A))))   (defun array-embed (A B row col) (let* ((ma (rows A)) (na (cols A)) (mb (rows B)) (nb (cols B)) (C (make-array `(,ma ,na) :initial-element 0.0d0)))   (loop for i from 0 to (1- ma) do (loop for j from 0 to (1- na) do (setf (aref C i j) (aref A i j))))   (loop for i from 0 to (1- mb) do (loop for j from 0 to (1- nb) do (setf (aref C (+ row i) (+ col j)) (aref B i j))))   C))  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#ALGOL_68
ALGOL 68
  BEGIN print ((program idf, newline)) END  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Amazing_Hopper
Amazing Hopper
  #include <hbasic.h> Begin GetParam(name File) Print("My Program name: ", name File,Newl) End  
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#D
D
void main() @safe { import std.stdio, std.range, std.algorithm, std.typecons, std.numeric;   enum triples = (in uint n) pure nothrow @safe /*@nogc*/ => iota(1, n + 1) .map!(z => iota(1, z + 1) .map!(x => iota(x, z + 1).map!(y => tuple(x, y, z)))) .joiner.joiner .filter!(t => t[0] ^^ 2 + t[1] ^^ 2 == t[2] ^^ 2 && t[].only.sum <= n) .map!(t => tuple(t[0 .. 2].gcd == 1, t[]));   auto xs = triples(100); writeln("Up to 100 there are ", xs.count, " triples, ", xs.filter!q{ a[0] }.count, " are primitive."); }
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Sidef
Sidef
s = %(s = %%(%s); printf(s, s); ); printf(s, s);
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Smalltalk
Smalltalk
[:s| Transcript show: s, s printString; cr ] value: '[:s| Transcript show: s, s printString; cr ] value: '  
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Sidef
Sidef
# Finds all solutions (a,b) such that: a^2 + b^2 = n^2 func sum_of_two_squares(n) is cached {   n == 0 && return [[0, 0]]   var prod1 = 1 var prod2 = 1   var prime_powers = []   for p,e in (n.factor_exp) { if (p % 4 == 3) { # p = 3 (mod 4) e.is_even || return [] # power must be even prod2 *= p**(e >> 1) } elsif (p == 2) { # p = 2 if (e.is_even) { # power is even prod2 *= p**(e >> 1) } else { # power is odd prod1 *= p prod2 *= p**((e - 1) >> 1) prime_powers.append([p, 1]) } } else { # p = 1 (mod 4) prod1 *= p**e prime_powers.append([p, e]) } }   prod1 == 1 && return [[prod2, 0]] prod1 == 2 && return [[prod2, prod2]]   # All the solutions to the congruence: x^2 = -1 (mod prod1) var square_roots = gather { gather { for p,e in (prime_powers) { var pp = p**e var r = sqrtmod(-1, pp) take([[r, pp], [pp - r, pp]]) } }.cartesian { |*a| take(Math.chinese(a...)) } }   var solutions = []   for r in (square_roots) {   var s = r var q = prod1   while (s*s > prod1) { (s, q) = (q % s, s) }   solutions.append([prod2 * s, prod2 * (q % s)]) }   for p,e in (prime_powers) { for (var i = e%2; i < e; i += 2) {   var sq = p**((e - i) >> 1) var pp = p**(e - i)   solutions += ( __FUNC__(prod1 / pp).map { |pair| pair.map {|r| sq * prod2 * r } } ) } }   solutions.map {|pair| pair.sort } \ .uniq_by {|pair| pair[0] } \ .sort_by {|pair| pair[0] } }   # Finds all solutions (a,b,c) such that: a^2 + b^2 + c^2 = n^2 func sum_of_three_squares(n) { gather { for k in (1 .. n//3) { var t = sum_of_two_squares(n**2 - k**2) || next take(t.map { [k, _...] }...) } } }   say gather { for n in (1..2200) { sum_of_three_squares(n) || take(n) } }
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Racket
Racket
#lang racket (require racket/draw pict)   (define (draw-pythagoras-tree order x0 y0 x1 y1) (λ (the-dc dx dy) (define (inr order x0 y0 x1 y1) (when (positive? order) (let* ((y0-1 (- y0 y1)) (x1-0 (- x1 x0)) (x2 (+ x1 y0-1)) (y2 (+ y1 x1-0)) (x3 (+ x0 y0-1)) (y3 (+ y0 x1-0)) (x4 (+ x2 x3 (/ (+ x0 x2) -2))) (y4 (+ y2 y3 (/ (+ y0 y2) -2))) (path (new dc-path%))) (send* path [move-to x0 y0] [line-to x1 y1] [line-to x2 y2] [line-to x3 y3] [close]) (send the-dc draw-path path dx dy) (inr (sub1 order) x3 y3 x4 y4) (inr (sub1 order) x4 y4 x2 y2))))   (define old-brush (send the-dc get-brush)) (define old-pen (send the-dc get-pen)) (send the-dc set-pen (new pen% [width 1] [color "black"])) (inr (add1 order) x0 y0 x1 y1) (send the-dc set-brush old-brush) (send the-dc set-pen old-pen)))   (dc (draw-pythagoras-tree 7 (+ 200 32) 255 (- 200 32) 255) 400 256)
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Action.21
Action!
PROC Main() DO IF Rand(0)=10 THEN PrintE("Terminate program by Break() procedure") Break() FI OD PrintE("This is a dead code") RETURN
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Ada
Ada
with Ada.Task_Identification; use Ada.Task_Identification;   procedure Main is -- Create as many task objects as your program needs begin -- whatever logic is required in your Main procedure if some_condition then Abort_Task (Current_Task); end if; end Main;
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#D
D
import std.stdio, std.math, std.algorithm, std.traits, std.typecons, std.numeric, std.range, std.conv;   template elementwiseMat(string op) { T[][] elementwiseMat(T)(in T[][] A, in T B) pure nothrow { if (A.empty) return null; auto R = new typeof(return)(A.length, A[0].length); foreach (immutable r, const row; A) R[r][] = mixin("row[] " ~ op ~ "B"); return R; }   T[][] elementwiseMat(T, U)(in T[][] A, in U[][] B) pure nothrow if (is(Unqual!T == Unqual!U)) { assert(A.length == B.length); if (A.empty) return null; auto R = new typeof(return)(A.length, A[0].length); foreach (immutable r, const row; A) { assert(row.length == B[r].length); R[r][] = mixin("row[] " ~ op ~ "B[r][]"); } return R; } }   alias mSum = elementwiseMat!q{ + }, mSub = elementwiseMat!q{ - }, pMul = elementwiseMat!q{ * }, pDiv = elementwiseMat!q{ / };   bool isRectangular(T)(in T[][] mat) pure nothrow { return mat.all!(r => r.length == mat[0].length); }   T[][] matMul(T)(in T[][] a, in T[][] b) pure nothrow in { assert(a.isRectangular && b.isRectangular && a[0].length == b.length); } body { auto result = new T[][](a.length, b[0].length); auto aux = new T[b.length]; foreach (immutable j; 0 .. b[0].length) { foreach (immutable k; 0 .. b.length) aux[k] = b[k][j]; foreach (immutable i; 0 .. a.length) result[i][j] = a[i].dotProduct(aux); } return result; }   Unqual!T[][] transpose(T)(in T[][] m) pure nothrow { auto r = new Unqual!T[][](m[0].length, m.length); foreach (immutable nr, row; m) foreach (immutable nc, immutable c; row) r[nc][nr] = c; return r; }   T norm(T)(in T[][] m) pure nothrow { return transversal(m, 0).map!q{ a ^^ 2 }.sum.sqrt; }   Unqual!T[][] makeUnitVector(T)(in size_t dim) pure nothrow { auto result = new Unqual!T[][](dim, 1); foreach (row; result) row[] = 0; result[0][0] = 1; return result; }   /// Return a nxn identity matrix. Unqual!T[][] matId(T)(in size_t n) pure nothrow { auto Id = new Unqual!T[][](n, n); foreach (immutable r, row; Id) { row[] = 0; row[r] = 1; } return Id; }   T[][] slice2D(T)(in T[][] A, in size_t ma, in size_t mb, in size_t na, in size_t nb) pure nothrow { auto B = new T[][](mb - ma + 1, nb - na + 1); foreach (immutable i, brow; B) brow[] = A[ma + i][na .. na + brow.length]; return B; }   size_t rows(T)(in T[][] A) pure nothrow { return A.length; }   size_t cols(T)(in T[][] A) pure nothrow { return A.length ? A[0].length : 0; }   T[][] mcol(T)(in T[][] A, in size_t n) pure nothrow { return slice2D(A, 0, A.rows - 1, n, n); }   T[][] matEmbed(T)(in T[][] A, in T[][] B, in size_t row, in size_t col) pure nothrow { auto C = new T[][](rows(A), cols(A)); foreach (immutable i, const arow; A) C[i][] = arow[]; // Some wasted copies. foreach (immutable i, const brow; B) C[row + i][col .. col + brow.length] = brow[]; return C; }   // Main routines ---------------   T[][] makeHouseholder(T)(in T[][] a) { immutable m = a.rows; immutable T s = a[0][0].sgn; immutable e = makeUnitVector!T(m); immutable u = mSum(a, pMul(e, a.norm * s)); immutable v = pDiv(u, u[0][0]); immutable beta = 2.0 / v.transpose.matMul(v)[0][0]; return mSub(matId!T(m), pMul(v.matMul(v.transpose), beta)); }   Tuple!(T[][],"Q", T[][],"R") QRdecomposition(T)(T[][] A) { immutable m = A.rows; immutable n = A.cols; auto Q = matId!T(m);   // Work on n columns of A. foreach (immutable i; 0 .. (m == n ? n - 1 : n)) { // Select the i-th submatrix. For i=0 this means the original // matrix A. immutable B = slice2D(A, i, m - 1, i, n - 1);   // Take the first column of the current submatrix B. immutable x = mcol(B, 0);   // Create the Householder matrix for the column and embed it // into an mxm identity. immutable H = matEmbed(matId!T(m), x.makeHouseholder, i, i);   // The product of all H matrices from the right hand side is // the orthogonal matrix Q. Q = Q.matMul(H);   // The product of all H matrices with A from the LHS is the // upper triangular matrix R. A = H.matMul(A); }   // Return Q and R. return typeof(return)(Q, A); }   // Polynomial regression ---------------   /// Solve an upper triangular system by back substitution. T[][] solveUpperTriangular(T)(in T[][] R, in T[][] b) pure nothrow { immutable n = R.cols; auto x = new T[][](n, 1);   foreach_reverse (immutable k; 0 .. n) { T tot = 0; foreach (immutable j; k + 1 .. n) tot += R[k][j] * x[j][0]; x[k][0] = (b[k][0] - tot) / R[k][k]; }   return x; }   /// Solve a linear least squares problem by QR decomposition. T[][] lsqr(T)(T[][] A, in T[][] b) pure nothrow { const qr = A.QRdecomposition; immutable n = qr.R.cols; return solveUpperTriangular( slice2D(qr.R, 0, n - 1, 0, n - 1), slice2D(qr.Q.transpose.matMul(b), 0, n - 1, 0, 0)); }   T[][] polyFit(T)(in T[][] x, in T[][] y, in size_t n) pure nothrow { immutable size_t m = x.cols; auto A = new T[][](m, n + 1); foreach (immutable i, row; A) foreach (immutable j, ref item; row) item = x[0][i] ^^ j; return lsqr(A, y.transpose); }   void main() { // immutable (Q, R) = QRdecomposition([[12.0, -51, 4], immutable qr = QRdecomposition([[12.0, -51, 4], [ 6.0, 167, -68], [-4.0, 24, -41]]); immutable form = "[%([%(%2.3f, %)]%|,\n %)]\n"; writefln(form, qr.Q); writefln(form, qr.R);   immutable x = [[0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]; immutable y = [[1.0, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]]; polyFit(x, y, 2).writeln; }
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Applesoft_BASIC
Applesoft BASIC
  10 GOSUB 40"GET PROGRAM NAME 20 PRINT N$ 30 END   40 REMGET PROGRAM NAME 50 GOSUB 100"GET INPUT BUFFER 60 GOSUB 200"REMOVE RUN PREFIX 70 GOSUB 300"REMOVE , SUFFIXES 80 GOSUB 400"TRIM SPACES 90 RETURN   100 REMGET INPUT BUFFER 110 N$ = "" 120 FOR I = 512 TO 767 130 B = PEEK (I) - 128 140 IF B < 32 THEN RETURN 150 N$ = N$ + CHR$ (B) 160 NEXT I 170 RETURN   200 REMREMOVE RUN PREFIX 210 P = 1 220 FOR I = 1 TO 3 230 FOR J = P TO LEN(N$) 240 C$ = MID$ (N$,J,1) 250 P = P + 1 260 IF C$ = " " THEN NEXT J 270 IF C$ = MID$("RUN",I,1) THEN NEXT I:N$ = MID$(N$,P,LEN(N$)-P+1):RETURN 280 PRINT "YOU NEED TO RUN THIS PROGRAM USING THE RUN COMMAND FROM DOS." 290 END   300 REMREMOVE , SUFFIXES 310 L = LEN (N$) 320 FOR I = 1 TO L 330 C$ = MID$ (N$,I,1) 340 IF C$ = "," THEN N$ = LEFT$(N$,I - 1): RETURN 350 NEXT I 360 RETURN   400 REMTRIM SPACES 410 GOSUB 600   500 REMLEFT TRIM SPACES 510 L = LEN(N$) - 1 520 FOR I = L TO 0 STEP -1 530 IF I < 0 THEN RETURN 540 IF LEFT$ (N$,1) <> " " THEN RETURN 550 IF I THEN N$ = RIGHT$ (N$, I) 560 NEXT I 570 N$ = " 580 RETURN   600 REMRIGHT TRIM SPACES 610 L = LEN(N$) - 1 620 FOR I = L TO 0 STEP -1 630 IF I < 0 THEN RETURN 640 IF RIGHT$ (N$,1) <> " " THEN RETURN 650 IF I THEN N$ = LEFT$ (N$, I) 660 NEXT I 670 N$ = " 680 RETURN  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program namepgm.s */ /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1 /* Initialized data */ .data szMessage: .asciz "Program : " @ szRetourLigne: .asciz "\n"     .text .global main main: push {fp,lr} /* save des 2 registres */ add fp,sp,#8 /* fp <- adresse début */ ldr r0, iAdrszMessage @ adresse of message bl affichageMess @ call function ldr r0,[fp,#4] @ recup name of program in command line bl affichageMess @ call function ldr r0, iAdrszRetourLigne @ adresse of message bl affichageMess @ call function   /* fin standard du programme */ mov r0, #0 @ return code pop {fp,lr} @restaur des 2 registres mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrszMessage: .int szMessage iAdrszRetourLigne: .int szRetourLigne /******************************************************************/ /* affichage des messages avec calcul longueur */ /******************************************************************/ /* r0 contient l adresse du message */ affichageMess: push {fp,lr} /* save des 2 registres */ push {r0,r1,r2,r7} /* save des autres registres */ mov r2,#0 /* compteur longueur */ 1: /*calcul de la longueur */ ldrb r1,[r0,r2] /* recup octet position debut + indice */ cmp r1,#0 /* si 0 c est fini */ beq 1f add r2,r2,#1 /* sinon on ajoute 1 */ b 1b 1: /* donc ici r2 contient la longueur du message */ mov r1,r0 /* adresse du message en r1 */ mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */ mov r7, #WRITE /* code de l appel systeme "write" */ swi #0 /* appel systeme */ pop {r0,r1,r2,r7} /* restaur des autres registres */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* retour procedure */    
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Delphi
Delphi
  [Pythagorean triples for Rosetta code. Counts (1) all Pythagorean triples (2) primitive Pythagorean triples, with perimeter not greater than a given value.   Library subroutine M3, Prints header and is then overwritten. Here, the last character sets the teleprinter to figures.] ..PZ [simulate blank tape] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF @&*!MAX!PERIM!!!!!TOTAL!!!!!!PRIM@&#. ..PZ   [Library subroutine P7, prints long strictly positive integer; 10 characters, right justified, padded left with spaces. Closed, even; 35 storage locations; working position 4D.] T 56 K GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@   [Subroutine for positive integer division. Input: 4D = dividend, 6D = divisor. Output: 4D = remainder, 6D = quotient. 37 locations; working locations 0D, 8D.] T 100 K GKA3FT35@A6DU8DTDA4DRDSDG13@T36@ADLDE4@T36@T6DA4DSDG23@ T4DA6DYFYFT6DT36@A8DSDE35@T36@ADRDTDA6DLDT6DE15@EFPF   [Subroutine to return GCD of two non-negative 35-bit integers. Input: Integers at 4D, 6D. Output: GCD at 4D; changes 6D. 41 locations; working location 0D.] T 200 K GKA3FT39@S4DE37@T40@A4DTDA6DRDSDG15@T40@ADLDE6@T40@A6DSDG20@T6D T40@A4DSDE29@T40@ADRDTDE16@S6DE39@TDA4DT6DSDT4DE5@A6DT4DEFPF   [************************ ROSETTA CODE TASK ************************* Subroutine to count Pythagorean triples with given maximum perimeter. Input: 0D = maximum perimeter. Output: 4D = number of triples, 6D = number of primitive. 0D is changed. Must be loaded at an even address. Uses the well-known fact that a primitive Pythagorean triple is of the form (m^2 - n^2, 2*m*n, m^2 + n^2) where m, n are coprime and of opposite parity.] T 300 K G K A 3 F [make link] E 16 @ [jump over variables and constants]   [Double values are put here to ensure even address] [Variables] [2] P F P F [maximum perimeter] [4] P F P F [total number of Pythagorean triples] [6] P F P F [number of primitive Pythagorean triples] [8] P F P F [m] [10] P F P F [n] [Constants] T12#Z PF T12Z [clears sandwich digit between 12 and 13] [12] P D P F [double-value 1] T14#Z PF T14Z [clears sandwich digit between 14 and 15] [14] P1F P F [double-value 2]   [Continue with code] [16] T 69 @ [plant link for return] A D [load maximum perimeter] T 2#@ [store locally] T 4#@ [initialize counts of triangles to 0] T 6#@ A 12#@ [load 1] T 8#@ [m := 1] [Next m, inc by 1] [23] T F [clear acc] A 8#@ [load m] A 12#@ [add 1] T 8#@ [update m] H 8#@ [mult reg := m] C 12#@ [acc := m AND 1] A 12#@ [add 1] T 10#@ [n := 1 if m even, 2 if m odd] [Here to count triangles arising from m, n. It's assumed m and n are known coprime.] [31] A 31 @ [call the count subroutine,] G 70 @ [result is in 6D] S 6 D [load negative count] G 40 @ [jump if count > 0] [No triangles found for this n. If n = 1 or 2 then whole thing is finished. Else move on to next m.] T F [clear acc] A 14#@ [load 2] S 10#@ [2 - n] G 23 @ [if n > 2, go to next m] E 64 @ [if n <= 2, exit] [Found triangles, count is in 6D] [40] T F [clear acc] A 4#@ [load total count] A 6 D [add count just found] T 4#@ [update total count] A 6#@ [load primitive count] A 12#@ [add 1] T 6#@ [update primitive count] [47] T F [clear acc] A 10#@ [load n] A 14#@ [add 2] U 10#@ [update n] S 8#@ [is n > m?] E 23 @ [if so, loop back for next m] [Test whether m and n are coprime.] T F [clear acc] A 8#@ [load m] T 4 D [to 4D for GCD routine] A 10#@ [load n] T 6 D [to 6D for GCD routine] A 58 @ [call GCD routine,] G 200 F [GCD is returned in 4D] A 4 D [load GCD] S 14#@ [is GCD = 1? (test by subtracting 2)] E 47 @ [no, go straight to next n] G 31 @ [yes, count triangles, then next n] [64] T F [exit, clear acc] A 4#@ [load total number of triples] T 4 D [return in 4D] A 6#@ [load number of primitive triples] T 6 D [return in 6D] [69] E F   [2nd-level subroutine to count triangles arising from m, n. Assumes m, n are coprime and of opposite parity, and m is in the multiplier register. Result is returned in 6D.] [70] A 3 F [make and plant link for return] T 91 @ A 2#@ [acc := maximum perimeter] T 4 D [to 4D for division routine] A 8#@ [load m] A 10#@ [add n] T D [m + n to 0D] V D [acc := m*(m + n)] [Need to shift product 34 left to restore integer scaling. Since we want 2*m*(m+n), shift 35 left.] L F [13 left (maximum possible)] L F [13 more] L 128 F [9 more] T 6 D [perimeter to 6D for division routine] A 4 D [load maximum perimeter] S 6 D [is perimeter > maximum?] G 89 @ [quick exit if so] T F [clear acc] A 86 @ [call division routine,] G 100 F [leaves count in 6D] E 91 @ [jump to exit] [89] T F [acc := 0] T 6 D [return count = 0] [91] E F   [Main routine. Load at an even address.] T 500 K G K [The initial maximum perimeter is repeatedly multiplied by 10] T#Z PF TZ [clears sandwich digit between 0 and 1] [0] P50F PF [initial maximum perimeter <---------- EDIT HERE] [2] P 3 F [number of values to calculate <---------- EDIT HERE] [3] P D [1] [4] P F P F [maximum perimeter] [6] P F P F [total number of triples] [8] P F P F [number of primitive triples] [10] P F [negative count of values] [11] # F [figures shift] [12] @ F [carriage return] [13] & F [line feed] [14] K 4096 F [null char] [Enter with acc = 0] [15] S 2 @ [initialize a negative counter] T 10 @ [(standard EDSAC practice)] A #@ [initialize maximum perimeter] T 4#@ [19] T F [clear acc] A 4#@ [load maximum perimeter] T D [to 0D for subroutine] A 22 @ [call subroutine to count triples] G 300 F A 4 D [returns total number in 4D] T 6#@ [save locally] A 6 D [returns number of primitive in 6D] T 8#@ [save locally] [Print the result] A 4#@ [load maximum perimeter] T D [to 0D for print subroutine] A 30 @ [call print subroutine] G 56 F A 6#@ [repeat for total number of triples] T D A 34 @ G 56 F A 8#@ [repeat for number of primitive triples] T D A 38 @ G 56 F O 12 @ O 13 @ A 10 @ [load negative count] A 3 @ [add 1] E 53 @ [out if reached 0] T 10 @ [else update count] A 4#@ [load max perimeter] U D [temp store] L 1 F [times 4] A D [times 5] L D [times 10] T 4#@ [update] E 19 @ [loop back] [53] O 14 @ [done; print null to flush printer buffer] Z F [stop] E 15 Z [define entry point] P F [acc = 0 on entry]  
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#SmileBASIC
SmileBASIC
Q$="Q$=%SPRINT FORMAT$(Q$,CHR$(34)+Q$+CHR$(34)+CHR$(10))" PRINT FORMAT$(Q$,CHR$(34)+Q$+CHR$(34)+CHR$(10))
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Swift
Swift
func missingD(upTo n: Int) -> [Int] { var a2 = 0, s = 3, s1 = 0, s2 = 0 var res = [Int](repeating: 0, count: n + 1) var ab = [Int](repeating: 0, count: n * n * 2 + 1)   for a in 1...n { a2 = a * a   for b in a...n { ab[a2 + b * b] = 1 } }   for c in 1..<n { s1 = s s += 2 s2 = s   for d in c+1...n { if ab[s1] != 0 { res[d] = 1 }   s1 += s2 s2 += 2 } }   return (1...n).filter({ res[$0] == 0 }) }   print(missingD(upTo: 2200))
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#VBA
VBA
Const n = 2200 Public Sub pq() Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3 Dim l(n) As Boolean, l_add(9680000) As Boolean '9680000=n * n * 2 For x = 1 To n x2 = x * x For y = x To n l_add(x2 + y * y) = True Next y Next x For x = 1 To n s1 = s s = s + 2 s2 = s For y = x + 1 To n If l_add(s1) Then l(y) = True s1 = s1 + s2 s2 = s2 + 2 Next Next For x = 1 To n If Not l(x) Then Debug.Print x; Next Debug.Print End Sub
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Raku
Raku
class Square { has Complex ($.position, $.edge); method size { $!edge.abs } method svg-polygon { qq[<polygon points="{join ' ', map { ($!position + $_ * $!edge).reals.join(',') }, 0, 1, 1+1i, 1i}" style="fill:lime;stroke=black" />] } method left-child { self.new: position => $!position + i*$!edge, edge => sqrt(2)/2*cis(pi/4)*$!edge; } method right-child { self.new: position => $!position + i*$!edge + self.left-child.edge, edge => sqrt(2)/2*cis(-pi/4)*$!edge; } }   BEGIN say '<svg width="500" height="500">'; END say '</svg>';   sub tree(Square $s, $level = 0) { return if $level > 8; say $s.svg-polygon; tree($s.left-child, $level+1); tree($s.right-child, $level+1); }   tree Square.new: :position(250+0i), :edge(60+0i);
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Aime
Aime
void f1(integer a) { if (a) { exit(1); } }   integer main(void) { f1(3);   return 0; }
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#ALGOL_68
ALGOL 68
IF problem = 1 THEN stop FI
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#F.23
F#
  // QR decomposition. Nigel Galloway: January 11th., 2022 let n=[[12.0;-51.0;4.0];[6.0;167.0;-68.0];[-4.0;24.0;-41.0]]|>MathNet.Numerics.LinearAlgebra.MatrixExtensions.matrix let g=n|>MathNet.Numerics.LinearAlgebra.Matrix.qr printfn $"Matrix\n------\n%A{n}\nQ\n-\n%A{g.Q}\nR\n-\n%A{g.R}"  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#AutoHotkey
AutoHotkey
  MsgBox, % A_ScriptName  
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#EDSAC_order_code
EDSAC order code
  [Pythagorean triples for Rosetta code. Counts (1) all Pythagorean triples (2) primitive Pythagorean triples, with perimeter not greater than a given value.   Library subroutine M3, Prints header and is then overwritten. Here, the last character sets the teleprinter to figures.] ..PZ [simulate blank tape] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF @&*!MAX!PERIM!!!!!TOTAL!!!!!!PRIM@&#. ..PZ   [Library subroutine P7, prints long strictly positive integer; 10 characters, right justified, padded left with spaces. Closed, even; 35 storage locations; working position 4D.] T 56 K GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@   [Subroutine for positive integer division. Input: 4D = dividend, 6D = divisor. Output: 4D = remainder, 6D = quotient. 37 locations; working locations 0D, 8D.] T 100 K GKA3FT35@A6DU8DTDA4DRDSDG13@T36@ADLDE4@T36@T6DA4DSDG23@ T4DA6DYFYFT6DT36@A8DSDE35@T36@ADRDTDA6DLDT6DE15@EFPF   [Subroutine to return GCD of two non-negative 35-bit integers. Input: Integers at 4D, 6D. Output: GCD at 4D; changes 6D. 41 locations; working location 0D.] T 200 K GKA3FT39@S4DE37@T40@A4DTDA6DRDSDG15@T40@ADLDE6@T40@A6DSDG20@T6D T40@A4DSDE29@T40@ADRDTDE16@S6DE39@TDA4DT6DSDT4DE5@A6DT4DEFPF   [************************ ROSETTA CODE TASK ************************* Subroutine to count Pythagorean triples with given maximum perimeter. Input: 0D = maximum perimeter. Output: 4D = number of triples, 6D = number of primitive. 0D is changed. Must be loaded at an even address. Uses the well-known fact that a primitive Pythagorean triple is of the form (m^2 - n^2, 2*m*n, m^2 + n^2) where m, n are coprime and of opposite parity.] T 300 K G K A 3 F [make link] E 16 @ [jump over variables and constants]   [Double values are put here to ensure even address] [Variables] [2] P F P F [maximum perimeter] [4] P F P F [total number of Pythagorean triples] [6] P F P F [number of primitive Pythagorean triples] [8] P F P F [m] [10] P F P F [n] [Constants] T12#Z PF T12Z [clears sandwich digit between 12 and 13] [12] P D P F [double-value 1] T14#Z PF T14Z [clears sandwich digit between 14 and 15] [14] P1F P F [double-value 2]   [Continue with code] [16] T 69 @ [plant link for return] A D [load maximum perimeter] T 2#@ [store locally] T 4#@ [initialize counts of triangles to 0] T 6#@ A 12#@ [load 1] T 8#@ [m := 1] [Next m, inc by 1] [23] T F [clear acc] A 8#@ [load m] A 12#@ [add 1] T 8#@ [update m] H 8#@ [mult reg := m] C 12#@ [acc := m AND 1] A 12#@ [add 1] T 10#@ [n := 1 if m even, 2 if m odd] [Here to count triangles arising from m, n. It's assumed m and n are known coprime.] [31] A 31 @ [call the count subroutine,] G 70 @ [result is in 6D] S 6 D [load negative count] G 40 @ [jump if count > 0] [No triangles found for this n. If n = 1 or 2 then whole thing is finished. Else move on to next m.] T F [clear acc] A 14#@ [load 2] S 10#@ [2 - n] G 23 @ [if n > 2, go to next m] E 64 @ [if n <= 2, exit] [Found triangles, count is in 6D] [40] T F [clear acc] A 4#@ [load total count] A 6 D [add count just found] T 4#@ [update total count] A 6#@ [load primitive count] A 12#@ [add 1] T 6#@ [update primitive count] [47] T F [clear acc] A 10#@ [load n] A 14#@ [add 2] U 10#@ [update n] S 8#@ [is n > m?] E 23 @ [if so, loop back for next m] [Test whether m and n are coprime.] T F [clear acc] A 8#@ [load m] T 4 D [to 4D for GCD routine] A 10#@ [load n] T 6 D [to 6D for GCD routine] A 58 @ [call GCD routine,] G 200 F [GCD is returned in 4D] A 4 D [load GCD] S 14#@ [is GCD = 1? (test by subtracting 2)] E 47 @ [no, go straight to next n] G 31 @ [yes, count triangles, then next n] [64] T F [exit, clear acc] A 4#@ [load total number of triples] T 4 D [return in 4D] A 6#@ [load number of primitive triples] T 6 D [return in 6D] [69] E F   [2nd-level subroutine to count triangles arising from m, n. Assumes m, n are coprime and of opposite parity, and m is in the multiplier register. Result is returned in 6D.] [70] A 3 F [make and plant link for return] T 91 @ A 2#@ [acc := maximum perimeter] T 4 D [to 4D for division routine] A 8#@ [load m] A 10#@ [add n] T D [m + n to 0D] V D [acc := m*(m + n)] [Need to shift product 34 left to restore integer scaling. Since we want 2*m*(m+n), shift 35 left.] L F [13 left (maximum possible)] L F [13 more] L 128 F [9 more] T 6 D [perimeter to 6D for division routine] A 4 D [load maximum perimeter] S 6 D [is perimeter > maximum?] G 89 @ [quick exit if so] T F [clear acc] A 86 @ [call division routine,] G 100 F [leaves count in 6D] E 91 @ [jump to exit] [89] T F [acc := 0] T 6 D [return count = 0] [91] E F   [Main routine. Load at an even address.] T 500 K G K [The initial maximum perimeter is repeatedly multiplied by 10] T#Z PF TZ [clears sandwich digit between 0 and 1] [0] P50F PF [initial maximum perimeter <---------- EDIT HERE] [2] P 3 F [number of values to calculate <---------- EDIT HERE] [3] P D [1] [4] P F P F [maximum perimeter] [6] P F P F [total number of triples] [8] P F P F [number of primitive triples] [10] P F [negative count of values] [11] # F [figures shift] [12] @ F [carriage return] [13] & F [line feed] [14] K 4096 F [null char] [Enter with acc = 0] [15] S 2 @ [initialize a negative counter] T 10 @ [(standard EDSAC practice)] A #@ [initialize maximum perimeter] T 4#@ [19] T F [clear acc] A 4#@ [load maximum perimeter] T D [to 0D for subroutine] A 22 @ [call subroutine to count triples] G 300 F A 4 D [returns total number in 4D] T 6#@ [save locally] A 6 D [returns number of primitive in 6D] T 8#@ [save locally] [Print the result] A 4#@ [load maximum perimeter] T D [to 0D for print subroutine] A 30 @ [call print subroutine] G 56 F A 6#@ [repeat for total number of triples] T D A 34 @ G 56 F A 8#@ [repeat for number of primitive triples] T D A 38 @ G 56 F O 12 @ O 13 @ A 10 @ [load negative count] A 3 @ [add 1] E 53 @ [out if reached 0] T 10 @ [else update count] A 4#@ [load max perimeter] U D [temp store] L 1 F [times 4] A D [times 5] L D [times 10] T 4#@ [update] E 19 @ [loop back] [53] O 14 @ [done; print null to flush printer buffer] Z F [stop] E 15 Z [define entry point] P F [acc = 0 on entry]  
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#SNOBOL4
SNOBOL4
S = ' OUTPUT = " S = 0" S "0"; OUTPUT = REPLACE(S,+"","0");END' OUTPUT = " S = '" S ""; OUTPUT = REPLACE(S,+"","'");END
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Wren
Wren
var N = 2200 var N2 = N * N * 2 var s = 3 var s1 = 0 var s2 = 0 var r = List.filled(N + 1, false) var ab = List.filled(N2 + 1, false)   for (a in 1..N) { var a2 = a * a for (b in a..N) ab[a2 + b*b] = true }   for (c in 1..N) { s1 = s s = s + 2 s2 = s var d = c + 1 while (d <= N) { if (ab[s1]) r[d] = true s1 = s1 + s2 s2 = s2 + 2 d = d + 1 } }   for (d in 1..N) { if (!r[d]) System.write("%(d) ") } System.print()
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Ring
Ring
# Project : Pythagoras tree   load "guilib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("Pythagoras tree") setgeometry(100,100,800,600) label1 = new qlabel(win1) { setgeometry(10,10,800,600) settext("") } new qpushbutton(win1) { setgeometry(150,500,100,30) settext("draw") setclickevent("draw()") } show() } exec() }   func draw p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(1) } paint = new qpainter() { begin(p1) setpen(pen)   w = 800 h = floor(w*11/16) w2 = floor(w/2) diff = floor(w/12)   pythagorastree(w2 - diff,h -10,w2 + diff ,h -10 ,0)   endpaint() } label1 { setpicture(p1) show() } return     func pythagorastree(x1,y1,x2,y2,depth) if depth > 10 return ok dx = x2 - x1 dy = y1 - y2 x3 = x2 - dy y3 = y2 - dx x4 = x1 - dy y4 = y1 - dx x5 = x4 + floor((dx - dy) / 2) y5 = y4 - floor((dx + dy) / 2) paint.drawline(x1,y1,x2,y2) paint.drawline(x2,y2,x3,y3) paint.drawline(x4,y4,x1,y1) pythagorastree(x4, y4, x5, y5, depth +1) pythagorastree(x5, y5, x3, y3, depth +1)
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#ALGOL_W
ALGOL W
if anErrorOccured then assert( false );
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#AppleScript
AppleScript
if (someCondition) then error number -128
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#Fortran
Fortran
program qrtask implicit none integer, parameter :: n = 4 real(8) :: durer(n, n) = reshape(dble([ & 16, 5, 9, 4, & 3, 10, 6, 15, & 2, 11, 7, 14, & 13, 8, 12, 1 & ]), [n, n]) real(8) :: q(n, n), r(n, n), qr(n, n), id(n, n), tau(n) integer, parameter :: lwork = 1024 real(8) :: work(lwork) integer :: info, i, j   q = durer call dgeqrf(n, n, q, n, tau, work, lwork, info)   r = 0d0 forall (i = 1:n, j = 1:n, j >= i) r(i, j) = q(i, j)   call dorgqr(n, n, n, q, n, tau, work, lwork, info)   qr = matmul(q, r) id = matmul(q, transpose(q))   call show(4, durer, "A") call show(4, q, "Q") call show(4, r, "R") call show(4, qr, "Q*R") call show(4, id, "Q*Q'") contains subroutine show(n, a, s) character(*) :: s integer :: n, i real(8) :: a(n, n)   print *, s do i = 1, n print 1, a(i, :) 1 format (*(f12.6,:,' ')) end do end subroutine end program
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#AWK
AWK
  # syntax: TAWK -f PROGRAM_NAME.AWK # # GAWK can provide the invoking program name from ARGV[0] but is unable to # provide the AWK script name that follows -f. Thompson Automation's TAWK # version 5.0c, last released in 1998 and no longer commercially available, can # provide the AWK script name that follows -f from the PROGFN built-in # variable. It should also provide the invoking program name, E.G. TAWK, from # ARGV[0] but due to a bug it holds the fully qualified -f name instead. # # This example is posted here with hopes the TAWK built-in variables PROGFN # (PROGram File Name) and PROGLN (PROGram Line Number) be added to GAWK by its # developers. # BEGIN { printf("%s -f %s\n",ARGV[0],PROGFN) printf("line number %d\n",PROGLN) exit(0) }  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#BASIC
BASIC
appname = COMMAND$(0)
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make local perimeter: INTEGER do perimeter := 100 from until perimeter > 1000000 loop total := 0 primitive_triples := 0 count_pythagorean_triples (3, 4, 5, perimeter) io.put_string ("There are " + total.out + " triples, below " + perimeter.out + ". Of which " + primitive_triples.out + " are primitives.%N") perimeter := perimeter * 10 end end   count_pythagorean_triples (a, b, c, perimeter: INTEGER) -- Total count of pythagorean triples and total count of primitve triples below perimeter. local p: INTEGER do p := a + b + c if p <= perimeter then primitive_triples := primitive_triples + 1 total := total + perimeter // p count_pythagorean_triples (a + 2 * (- b + c), 2 * (a + c) - b, 2 * (a - b + c) + c, perimeter) count_pythagorean_triples (a + 2 * (b + c), 2 * (a + c) + b, 2 * (a + b + c) + c, perimeter) count_pythagorean_triples (- a + 2 * (b + c), 2 * (- a + c) + b, 2 * (- a + b + c) + c, perimeter) end end   feature {NONE}   primitive_triples: INTEGER   total: INTEGER   end  
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#SPL
SPL
d='JC5wcmludCgiZD0nIitkKyInOyIrJC5iNjRkZWNvZGUoZCkp';$.print("d='"+d+"';"+$.b64decode(d))  
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#SPWN
SPWN
d='JC5wcmludCgiZD0nIitkKyInOyIrJC5iNjRkZWNvZGUoZCkp';$.print("d='"+d+"';"+$.b64decode(d))  
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Yabasic
Yabasic
limite = 2200 s = 3 dim l(limite) dim ladd(limite * limite * 2)   for x = 1 to limite x2 = x * x for y = x to limite ladd(x2 + y * y) = 1 next y next x   for x = 1 to limite s1 = s s = s + 2 s2 = s for y = x +1 to limite if ladd(s1) = 1 l(y) = 1 s1 = s1 + s2 s2 = s2 + 2 next y next x   for x = 1 to limite if l(x) = 0 print str$(x), " "; next x print end
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#zkl
zkl
# find values of d where d^2 =/= a^2 + b^2 + c^2 for any integers a, b, c # # where d in [1..2200], a, b, c =/= 0 # # max number to check # const max_number = 2200; const max_square = max_number * max_number; # table of numbers that can be the sum of two squares # sum_of_two_squares:=Data(max_square+1,Int).fill(0); # 4 meg byte array foreach a in ([1..max_number]){ a2 := a * a; foreach b in ([a..max_number]){ sum2 := ( b * b ) + a2; if(sum2 <= max_square) sum_of_two_squares[ sum2 ] = True; # True-->1 } } # now find d such that d^2 - c^2 is in sum of two squares # solution:=Data(max_number+1,Int).fill(0); # another byte array foreach d in ([1..max_number]){ d2 := d * d; foreach c in ([1..d-1]){ diff2 := d2 - ( c * c ); if(sum_of_two_squares[ diff2 ]){ solution[ d ] = True; break; } } } # print the numbers whose squares are not the sum of three squares # foreach d in ([1..max_number]){ if(not solution[ d ]) print(d, " "); } println();
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Ruby
Ruby
  # frozen_string_literal: true   def setup sketch_title 'Pythagoras Tree' background(255) stroke(0, 255, 0) tree(width / 2.3, height, width / 1.8, height, 10) end   def tree(x1, y1, x2, y2, depth) return if depth <= 0   dx = (x2 - x1) dy = (y1 - y2)   x3 = (x2 - dy) y3 = (y2 - dx) x4 = (x1 - dy) y4 = (y1 - dx) x5 = (x4 + 0.5 * (dx - dy)) y5 = (y4 - 0.5 * (dx + dy)) # square begin_shape fill(0.0, 255.0 / depth, 0.0) vertex(x1, y1) vertex(x2, y2) vertex(x3, y3) vertex(x4, y4) vertex(x1, y1) end_shape # triangle begin_shape fill(0.0, 255.0 / depth, 0.0) vertex(x3, y3) vertex(x4, y4) vertex(x5, y5) vertex(x3, y3) end_shape tree(x4, y4, x5, y5, depth - 1) tree(x5, y5, x3, y3, depth - 1) end   def settings size(800, 400) end    
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#APL
APL
  #!/usr/local/bin/apl --script --   ⍝⍝ GNU APL script ⍝⍝ Usage: errout.apl <code> ⍝⍝ ⍝⍝ $ echo $? ## to see exit code ⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝ args ← 2↓⎕ARG~'--script' '--' ⍝⍝ strip off script args we don't need   err ← ⍎⊃args[1]   ∇main →(0=err)/ok error: 'Error! exiting.' ⍎')off 1' ⍝⍝ NOTE: exit code arg was added to )OFF in SVN r1499 Nov 2021 ok: 'No error, continuing...' ⍎')off' ∇   main  
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program ending.s */   /* Constantes */ .equ EXIT, 1 @ Linux syscall   /* Initialized data */ .data   /* code section */ .text .global main main: @ entry of program push {fp,lr} @ saves registers   OK: @ end program OK mov r0, #0 @ return code b 100f NONOK: @ if error detected end program no ok mov r0, #1 @ return code 100: @ standard end of the program pop {fp,lr} @restaur registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call Linux    
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#Futhark
Futhark
  import "lib/github.com/diku-dk/linalg/linalg"   module linalg_f64 = mk_linalg f64   let eye (n: i32): [n][n]f64 = let arr = map (\ind -> let (i,j) = (ind/n,ind%n) in if (i==j) then 1.0 else 0.0) (iota (n*n)) in unflatten n n arr   let norm v = linalg_f64.dotprod v v |> f64.sqrt   let qr [n] [m] (a: [m][n]f64): ([m][m]f64, [m][n]f64) =   let make_householder [d] (x: [d]f64): [d][d]f64 = let div = if x[0] > 0 then x[0] + norm x else x[0] - norm x let v = map (/div) x let v[0] = 1 let fac = 2.0 / linalg_f64.dotprod v v in map2 (map2 (-)) (eye d) (map (map (*fac)) (linalg_f64.outer v v))   let step ((x,y):([m][m]f64,[m][n]f64)) (i:i32): ([m][m]f64,[m][n]f64) = let h = eye m let h[i:m,i:m] = make_householder y[i:m,i] let q': [m][m]f64 = linalg_f64.matmul x h let a': [m][n]f64 = linalg_f64.matmul h y in (q',a')   let q = eye m in foldl step (q,a) (iota n)   entry main = qr [[12.0, -51.0, 4.0],[6.0, 167.0, -68.0],[-4.0, 24.0, -41.0]]  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Blue
Blue
global _start   : syscall ( num:eax -- result:eax ) syscall ;   : exit ( status:edi -- noret ) 60 syscall ; : bye ( -- noret ) 0 exit ;   : write ( buf:esi len:edx fd:edi -- ) 1 syscall drop ;   1 const stdout   : print ( buf len -- ) stdout write ;   : newline ( -- ) s" \n" print ; : println ( buf len -- ) print newline ;   : find0 ( start:rsi -- end:rsi ) lodsb 0 cmp latest xne ; : cstrlen ( str:rdi -- len:rsi ) dup find0 swap sub dec ; : cstr>str ( cstr:rdx -- str:rsi len:rdx ) dup cstrlen xchg ;   : print-arg ( arg -- ) cstr>str println ;   : arg0 ( rsp -- rsp ) 8 add @ ; inline   : _start ( rsp -- noret ) arg0 print-arg bye ;
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#C
C
#include <stdio.h>   int main(int argc, char **argv) { printf("Executable: %s\n", argv[0]);   return 0; }
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Elixir
Elixir
defmodule RC do def count_triples(limit), do: count_triples(limit,3,4,5)   defp count_triples(limit, a, b, c) when limit<(a+b+c), do: {0,0} defp count_triples(limit, a, b, c) do {p1, t1} = count_triples(limit, a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c) {p2, t2} = count_triples(limit, a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c) {p3, t3} = count_triples(limit,-a+2*b+2*c,-2*a+b+2*c,-2*a+2*b+3*c) {1+p1+p2+p3, div(limit, a+b+c)+t1+t2+t3} end end   list = for n <- 1..8, do: Enum.reduce(1..n, 1, fn(_,acc)->10*acc end) Enum.each(list, fn n -> IO.inspect {n, RC.count_triples(n)} end)
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Standard_ML
Standard ML
(fn s => print (s ^ "\"" ^ String.toString s ^ "\";\n")) "(fn s => print (s ^ \"\\\"\" ^ String.toString s ^ \"\\\";\\n\")) ";
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Swift
Swift
({print($0+$0.debugDescription+")")})("({print($0+$0.debugDescription+\")\")})(")
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Rust
Rust
/* add to file Cargo.toml: [dependencies] svg = "0.10.0" */   use svg::node::element::{Group, Polygon};   fn main() { let mut doc = svg::Document::new().set("stroke", "white"); let mut base: Vec<[(f64, f64); 2]> = vec![[(-200.0, 0.0), (200.0, 0.0)]]; for lvl in 0..12u8 { let rg = |step| lvl.wrapping_mul(step).wrapping_add(80 - step * 2); let mut group = Group::new().set("fill", format!("#{:02X}{:02X}18", rg(20), rg(30))); // level color let mut next_base = Vec::new(); for [a, b] in base { let v = (b.0 - a.0, b.1 - a.1); let c = (a.0 + v.1, a.1 - v.0); let d = (c.0 + v.0, c.1 + v.1); let e = (c.0 + 0.5 * (v.0 + v.1), c.1 + 0.5 * (v.1 - v.0)); group = group.add(Polygon::new().set("points", vec![a, c, e, d, c, d, b])); next_base.extend([[c, e], [e, d]]); } base = next_base; doc = doc.add(group); } let (x0, y0) = (base.iter()).fold((0.0, 0.0), |(x0, y0), [(x, y), _]| (x.min(x0), y.min(y0))); let file = "pythagoras_tree.svg"; match svg::save(file, &doc.set("viewBox", (x0, y0, -x0 * 2.0, -y0))) { Ok(_) => println!("{file} file written successfully!"), Err(e) => println!("failed to write {file}: {e}"), } }
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Arturo
Arturo
problem: true   if problem -> exit
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#AutoHotkey
AutoHotkey
If (problem) ExitApp
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#Go
Go
package main   import ( "fmt" "math"   "github.com/skelterjohn/go.matrix" )   func sign(s float64) float64 { if s > 0 { return 1 } else if s < 0 { return -1 } return 0 }   func unitVector(n int) *matrix.DenseMatrix { vec := matrix.Zeros(n, 1) vec.Set(0, 0, 1) return vec }   func householder(a *matrix.DenseMatrix) *matrix.DenseMatrix { m := a.Rows() s := sign(a.Get(0, 0)) e := unitVector(m) u := matrix.Sum(a, matrix.Scaled(e, a.TwoNorm()*s)) v := matrix.Scaled(u, 1/u.Get(0, 0)) // (error checking skipped in this solution) prod, _ := v.Transpose().TimesDense(v) β := 2 / prod.Get(0, 0)   prod, _ = v.TimesDense(v.Transpose()) return matrix.Difference(matrix.Eye(m), matrix.Scaled(prod, β)) }   func qr(a *matrix.DenseMatrix) (q, r *matrix.DenseMatrix) { m := a.Rows() n := a.Cols() q = matrix.Eye(m)   last := n - 1 if m == n { last-- } for i := 0; i <= last; i++ { // (copy is only for compatibility with an older version of gomatrix) b := a.GetMatrix(i, i, m-i, n-i).Copy() x := b.GetColVector(0) h := matrix.Eye(m) h.SetMatrix(i, i, householder(x)) q, _ = q.TimesDense(h) a, _ = h.TimesDense(a) } return q, a }   func main() { // task 1: show qr decomp of wp example a := matrix.MakeDenseMatrixStacked([][]float64{ {12, -51, 4}, {6, 167, -68}, {-4, 24, -41}}) q, r := qr(a) fmt.Println("q:\n", q) fmt.Println("r:\n", r)   // task 2: use qr decomp for polynomial regression example x := matrix.MakeDenseMatrixStacked([][]float64{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}) y := matrix.MakeDenseMatrixStacked([][]float64{ {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}}) fmt.Println("\npolyfit:\n", polyfit(x, y, 2)) }   func polyfit(x, y *matrix.DenseMatrix, n int) *matrix.DenseMatrix { m := x.Cols() a := matrix.Zeros(m, n+1) for i := 0; i < m; i++ { for j := 0; j <= n; j++ { a.Set(i, j, math.Pow(x.Get(0, i), float64(j))) } } return lsqr(a, y.Transpose()) }   func lsqr(a, b *matrix.DenseMatrix) *matrix.DenseMatrix { q, r := qr(a) n := r.Cols() prod, _ := q.Transpose().TimesDense(b) return solveUT(r.GetMatrix(0, 0, n, n), prod.GetMatrix(0, 0, n, 1)) }   func solveUT(r, b *matrix.DenseMatrix) *matrix.DenseMatrix { n := r.Cols() x := matrix.Zeros(n, 1) for k := n - 1; k >= 0; k-- { sum := 0. for j := k + 1; j < n; j++ { sum += r.Get(k, j) * x.Get(j, 0) } x.Set(k, 0, (b.Get(k, 0)-sum)/r.Get(k, k)) } return x }
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#C.23
C#
using System; namespace ProgramName { class Program { static void Main(string[] args) { Console.Write(Environment.CommandLine); } } }
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#C.2B.2B
C++
#include <iostream>   using namespace std;   int main(int argc, char **argv) { char *program = argv[0]; cout << "Program: " << program << endl; }
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Erlang
Erlang
%% %% Pythagorian triples in Erlang, J.W. Luiten %% -module(triples). -export([main/1]).   %% Transformations t1, t2 and t3 to generate new triples t1(A, B, C) -> {A-2*B+2*C, 2*A-B+2*C, 2*A-2*B+3*C}. t2(A, B, C) -> {A+2*B+2*C, 2*A+B+2*C, 2*A+2*B+3*C}. t3(A, B, C) -> {2*B+2*C-A, B+2*C-2*A, 2*B+3*C-2*A}.   %% Generation of triples count_triples(A, B, C, Tot_acc, Cnt_acc, Max_perimeter) when (A+B+C) =< Max_perimeter -> Tot1 = Tot_acc + Max_perimeter div (A+B+C), {A1, B1, C1} = t1(A, B, C), {Tot2, Cnt2} = count_triples(A1, B1, C1, Tot1, Cnt_acc+1, Max_perimeter),   {A2, B2, C2} = t2(A, B, C), {Tot3, Cnt3} = count_triples(A2, B2, C2, Tot2, Cnt2, Max_perimeter),   {A3, B3, C3} = t3(A, B, C), {Tot4, Cnt4} = count_triples(A3, B3, C3, Tot3, Cnt3, Max_perimeter), {Tot4, Cnt4}; count_triples(_A, _B, _C, Tot_acc, Cnt_acc, _Max_perimeter) -> {Tot_acc, Cnt_acc}.   count_triples(A, B, C, Pow) -> Max = trunc(math:pow(10, Pow)), {Tot, Prim} = count_triples(A, B, C, 0, 0, Max), {Pow, Tot, Prim}.   count_triples(Pow) -> count_triples(3, 4, 5, Pow).   %% Display a single result. display_result({Pow, Tot, Prim}) -> io:format("Up to 10 ** ~w : ~w triples, ~w primitives~n", [Pow, Tot, Prim]).   main(Max) -> L = lists:seq(1, Max), Answer = lists:map(fun(X) -> count_triples(X) end, L), lists:foreach(fun(Result) -> display_result(Result) end, Answer).
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Tcl
Tcl
join { {} A B } any_string => any_stringAany_stringB
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Turbo_Pascal
Turbo Pascal
program quine;   const apos: Char = Chr(39); comma: Char = Chr(44); lines: Array[1..17] of String[80] = ( 'program quine;', '', 'const', ' apos: Char = Chr(39);', ' comma: Char = Chr(44);', ' lines: Array[1..17] of String[80] = (', ' );', '', 'var', ' num: Integer;', '', 'begin', ' for num := 1 to 6 do writeln(lines[num]);', ' for num := 1 to 16 do writeln(apos, lines[num], apos, comma);', '% writeln(apos, lines[17], apos);', ' for num := 7 to 17 do writeln(lines[num]);', 'end.' );   var num: Integer;   begin for num := 1 to 6 do writeln(lines[num]); for num := 1 to 16 do writeln(apos, lines[num], apos, comma); writeln(apos, lines[17], apos); for num := 7 to 17 do writeln(lines[num]); end.
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Scala
Scala
import java.awt._ import java.awt.geom.Path2D   import javax.swing.{JFrame, JPanel, SwingUtilities, WindowConstants}   object PythagorasTree extends App {   SwingUtilities.invokeLater(() => { new JFrame {   class PythagorasTree extends JPanel { setPreferredSize(new Dimension(640, 640)) setBackground(Color.white)   override def paintComponent(g: Graphics): Unit = { val (depthLimit, hue) = (7, 0.15f)   def drawTree(g: Graphics2D, x1: Float, y1: Float, x2: Float, y2: Float, depth: Int): Unit = { if (depth == depthLimit) return val (dx, dy) = (x2 - x1, y1 - y2) val (x3, y3) = (x2 - dy, y2 - dx) val (x4, y4) = (x1 - dy, y1 - dx) val (x5, y5) = (x4 + 0.5F * (dx - dy), y4 - 0.5F * (dx + dy)) val square = new Path2D.Float { moveTo(x1, y1); lineTo(x2, y2); lineTo(x3, y3); lineTo(x4, y4); closePath() } val triangle = new Path2D.Float { moveTo(x3, y3); lineTo(x4, y4); lineTo(x5, y5); closePath() } g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1)) g.fill(square) g.setColor(Color.lightGray) g.draw(square) g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1)) g.fill(triangle) g.setColor(Color.lightGray) g.draw(triangle) drawTree(g, x4, y4, x5, y5, depth + 1) drawTree(g, x5, y5, x3, y3, depth + 1) }   super.paintComponent(g) drawTree(g.asInstanceOf[Graphics2D], 275, 500, 375, 500, 0) } }   setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) setTitle("Pythagoras Tree") setResizable(false) add(new PythagorasTree, BorderLayout.CENTER) pack() setLocationRelativeTo(null) setVisible(true) } })   }
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#AutoIt
AutoIt
If problem Then Exit Endif
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#AWK
AWK
if(problem)exit 1
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#Haskell
Haskell
  import Data.List import Text.Printf (printf)   eps = 1e-6 :: Double   -- a matrix is represented as a list of columns mmult :: Num a => [[a]] -> [[a]] -> [[a]] nth :: Num a => [[a]] -> Int -> Int -> a mmult_num :: Num a => [[a]] -> a -> [[a]] madd :: Num a => [[a]] -> [[a]] -> [[a]] idMatrix :: Num a => Int -> Int -> [[a]]   adjustWithE :: [[Double]] -> Int -> [[Double]]   mmult a b = [ [ sum $ zipWith (*) ak bj | ak <- (transpose a) ] | bj <- b ] nth mA i j = (mA !! j) !! i mmult_num mA n = map (\c -> map (*n) c) mA madd mA mB = zipWith (\c1 c2 -> zipWith (+) c1 c2) mA mB idMatrix n m = [ [if (i==j) then 1 else 0 | i <- [1..n]] | j <- [1..m]]   adjustWithE mA n = let lA = length mA in (idMatrix n (n - lA)) ++ (map (\c -> (take (n - lA) (repeat 0.0)) ++ c ) mA)   -- auxiliary functions sqsum :: Floating a => [a] -> a norm :: Floating a => [a] -> a epsilonize :: [[Double]] -> [[Double]]   sqsum a = foldl (\x y -> x + y*y) 0 a norm a = sqrt $! sqsum a epsilonize mA = map (\c -> map (\x -> if abs x <= eps then 0 else x) c) mA   -- Householder transformation; householder A = (Q, R) uTransform :: [Double] -> [Double] hMatrix :: [Double] -> Int -> Int -> [[Double]] householder :: [[Double]] -> ([[Double]], [[Double]])   -- householder_rec Q R A householder_rec :: [[Double]] -> [[Double]] -> Int -> ([[Double]], [[Double]])   uTransform a = let t = (head a) + (signum (head a))*(norm a) in 1 : map (\x -> x/t) (tail a)   hMatrix a n i = let u = uTransform (drop i a) in madd (idMatrix (n-i) (n-i)) (mmult_num (mmult [u] (transpose [u])) ((/) (-2) (sqsum u)))   householder_rec mQ mR 0 = (mQ, mR) householder_rec mQ mR n = let mSize = length mR in let mH = adjustWithE (hMatrix (mR!!(mSize - n)) mSize (mSize - n)) mSize in householder_rec (mmult mQ mH) (mmult mH mR) (n - 1)   householder mA = let mSize = length mA in let (mQ, mR) = householder_rec (idMatrix mSize mSize) mA mSize in (epsilonize mQ, epsilonize mR)   backSubstitution :: [[Double]] -> [Double] -> [Double] -> [Double] backSubstitution mR [] res = res backSubstitution mR@(hR:tR) q@(h:t) res = let x = (h / (head hR)) in backSubstitution (map tail tR) (tail (zipWith (-) q (map (*x) hR))) (x : res)   showMatrix :: [[Double]] -> String showMatrix mA = concat $ intersperse "\n" (map (\x -> unwords $ printf "%10.4f" <$> (x::[Double])) (transpose mA))   mY = [[12, 6, -4], [-51, 167, 24], [4, -68, -41]] :: [[Double]] q = [21, 245, 35] :: [Double] main = let (mQ, mR) = householder mY in putStrLn ("Q: \n" ++ showMatrix mQ) >> putStrLn ("R: \n" ++ showMatrix mR) >> putStrLn ("q: \n" ++ show q) >> putStrLn ("x: \n" ++ show (backSubstitution (reverse (map reverse mR)) (reverse q) []))  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Clojure
Clojure
":";exec lein exec $0 ${1+"$@"} ":";exit   (ns scriptname (:gen-class))   (defn -main [& args] (let [program (first *command-line-args*)] (println "Program:" program)))   (when (.contains (first *command-line-args*) *source-path*) (apply -main (rest *command-line-args*)))
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#COBOL
COBOL
identification division. program-id. sample.   data division. working-storage section. 01 progname pic x(16).   procedure division. sample-main.   display 0 upon argument-number accept progname from argument-value display "argument-value zero :" progname ":"   display "function module-id  :" function module-id ":"   goback. end program sample.
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#11l
11l
F get_primes(primes_count) V limit = 17 * primes_count V is_prime = [0B] * 2 [+] [1B] * (limit - 1) L(n) 0 .< Int(limit ^ 0.5 + 1.5) I is_prime[n] L(i) (n * n .< limit + 1).step(n) is_prime[i] = 0B   [Int] primes L(prime) is_prime I prime primes.append(L.index) I primes.len == primes_count L.break R primes   V primes = get_primes(100000)   F primorial(n) BigInt r = 1 L(i) 0 .< n r *= :primes[i] R r   print(‘First ten primorials: ’(0.<10).map(n -> primorial(n))) L(e) 6 V n = 10 ^ e print(‘primorial(#.) has #. digits’.format(n, String(primorial(n)).len))
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#ERRE
ERRE
PROGRAM PIT   BEGIN   PRINT(CHR$(12);) !CLS PRINT(TIME$)   FOR POWER=1 TO 7 DO PLIMIT=10#^POWER UPPERBOUND=INT(1+PLIMIT^0.5) PRIMITIVES=0 TRIPLES=0 EXTRAS=0  ! will count the in-range multiples of any primitive   FOR M=2 TO UPPERBOUND DO FOR N=1+(M MOD 2=1) TO M-1 STEP 2 DO TERM1=2*M*N TERM2=M*M-N*N TERM3=M*M+N*N PERIMETER=TERM1+TERM2+TERM3   IF PERIMETER<=PLIMIT THEN TRIPLES=TRIPLES+1   A=TERM1 B=TERM2   REPEAT R=A-B*INT(A/B) A=B B=R UNTIL R<=0    ! we've found a primitive triple if a = 1, since hcf =1.  ! and it is inside perimeter range. Save it in an array IF (A=1) AND (PERIMETER<=PLIMIT) THEN PRIMITIVES=PRIMITIVES+1    !-----------------------------------------------  !swap so in increasing order of side length  !----------------------------------------------- IF TERM1>TERM2 THEN SWAP(TERM1,TERM2)  !-----------------------------------------------  !we have the primitive & removed any multiples.  !Now calculate ALL the multiples in range.  !----------------------------------------------- NEX=INT(PLIMIT/PERIMETER) EXTRAS=EXTRAS+NEX END IF    !scan END FOR END FOR   PRINT("Primit. with perimeter <=";10#^power;"is";primitives;"&";extras;"non-prim.triples.") PRINT(TIME$) END FOR   PRINT PRINT("** End **") END PROGRAM
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#TXR
TXR
@(deffilter me ("ME" "@(bind me &quot;ME&quot;)&#10;@(output)&#10;@@(deffilter me (&quot;ME&quot; &quot;@{me :filter me}&quot;))&#10;@{me :filter (me :from_html)}&#10;@(end)")) @(bind me "ME") @(output) @@(deffilter me ("ME" "@{me :filter me}")) @{me :filter (me :from_html)} @(end)
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#UNIX_Shell
UNIX Shell
#!/bin/sh cat < "$0"
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Scilab
Scilab
side = 1; //side length of the square depth = 8; //final number of branch levels   //L-system definition: //Alphabet: UTDB+-[] //U: go upwards T: top of the square //D: go downwards B: bottom of the square //[: start new branch ]: end current branch //+: branch to the right -: branch to the left //Axiom: UTDB //Rule: T -> [+UTD-UTD]   //L-system sentence generation sentence = 'UTDB' rule = '[+UTD-UTD]'; for i=1:depth sentence = strsubst(sentence,'T',rule); end sentence = strsplit(sentence)';   //Empty tree tree_size = 1.0... + length(find(sentence == "U" | sentence == "T" |... sentence == "D" | sentence == "B"))... + 2 * length(find(sentence == "]" | sentence == "-" |... sentence == "+")); tree=zeros(tree_size,1);   //Vectorial operation to calculate a new point in the tree deff('z = new_point(origin,rho,theta)',... 'z = origin + rho * exp(%i*theta)');   //Drawing the tree curr_angle = %pi/2; curr_pos = 1; ratio = 1/sqrt(2); for ind = 1:size(sentence,'c') charac = sentence(ind);   select charac case 'U' then //Draw line upwards tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle); curr_pos = curr_pos + 1;   case 'T' then //Draw top of the square curr_angle = curr_angle - %pi/2; tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle); curr_pos = curr_pos + 1;   case 'D' then //Draw line downwards curr_angle = curr_angle - %pi/2; tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle); curr_pos = curr_pos + 1;   case 'B' then //Draw the bottom curr_angle = curr_angle - %pi/2; tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle); curr_pos = curr_pos + 1;   case '[' then //Start branch side = side * ratio;   case '+' then //Start going to the left curr_angle = curr_angle - %pi/4; // tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle); // tree(curr_pos+2) = new_point(tree(curr_pos+1),side,%pi+curr_angle); // curr_pos = curr_pos + 2; curr_angle = curr_angle + %pi/2;   case '-' then //Start going to the left // tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle); // tree(curr_pos+2) = new_point(tree(curr_pos+1),side,%pi+curr_angle); // curr_pos = curr_pos + 2; curr_angle = curr_angle + %pi/2; case ']' then side = side / ratio; curr_angle = curr_angle - %pi/4; // tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle); // tree(curr_pos+2) = new_point(tree(curr_pos+1),side,%pi+curr_angle); // curr_pos = curr_pos + 2; curr_angle = curr_angle + %pi;   else error('L-system sentence error'); end end   scf(); clf(); xname('Pythagoras tree: '+string(depth)+' levels') plot2d(real(tree),imag(tree),14); set(gca(),'isoview','on'); set(gca(),'axes_visible',['off','off','off']);
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#Sidef
Sidef
require('Imager')   func tree(img, x1, y1, x2, y2, depth) {   depth <= 0 && return()   var dx = (x2 - x1) var dy = (y1 - y2)   var x3 = (x2 - dy) var y3 = (y2 - dx) var x4 = (x1 - dy) var y4 = (y1 - dx) var x5 = (x4 + 0.5*(dx - dy)) var y5 = (y4 - 0.5*(dx + dy))   # square img.polygon( points => [ [x1, y1], [x2, y2], [x3, y3], [x4, y4], ], color => [0, 255/depth, 0], )   # triangle img.polygon( points => [ [x3, y3], [x4, y4], [x5, y5], ], color => [0, 255/depth, 0], )   tree(img, x4, y4, x5, y5, depth - 1) tree(img, x5, y5, x3, y3, depth - 1) }   var (width=1920, height=1080) var img = %O<Imager>.new(xsize => width, ysize => height) img.box(filled => 1, color => 'white') tree(img, width/2.3, height, width/1.8, height, 10) img.write(file => 'pythagoras_tree.png')
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Axe
Axe
Returnʳ
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#BASIC
BASIC
IF problem = 1 THEN END END IF
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#J
J
QR =: 128!:0
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#CoffeeScript
CoffeeScript
#!/usr/bin/env coffee   main = () -> program = __filename console.log "Program: " + program   if not module.parent then main()
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Common_Lisp
Common Lisp
;;; Play nice with shebangs (set-dispatch-macro-character #\# #\! (lambda (stream character n) (declare (ignore character n)) (read-line stream nil nil t) nil))
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#C
C
  #include <inttypes.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <gmp.h>   /* Eratosthenes bit-sieve */ int es_check(uint32_t *sieve, uint64_t n) { if ((n != 2 && !(n & 1)) || (n < 2)) return 0; else return !(sieve[n >> 6] & (1 << (n >> 1 & 31))); }   uint32_t *es_sieve(const uint64_t nth, uint64_t *es_size) { *es_size = nth * log(nth) + nth * (log(log(nth)) - 0.9385f) + 1; uint32_t *sieve = calloc((*es_size >> 6) + 1, sizeof(uint32_t));   for (uint64_t i = 3; i < sqrt(*es_size) + 1; i += 2) if (!(sieve[i >> 6] & (1 << (i >> 1 & 31)))) for (uint64_t j = i * i; j < *es_size; j += (i << 1)) sieve[j >> 6] |= (1 << (j >> 1 & 31));   return sieve; }   size_t mpz_number_of_digits(const mpz_t op) { char *opstr = mpz_get_str(NULL, 10, op); const size_t oplen = strlen(opstr); free(opstr); return oplen; }   #define PRIMORIAL_LIMIT 1000000   int main(void) { /* Construct a sieve of the first 1,000,000 primes */ uint64_t sieve_size; uint32_t *sieve = es_sieve(PRIMORIAL_LIMIT, &sieve_size);   mpz_t primorial; mpz_init_set_ui(primorial, 1);   uint64_t prime_count = 0; int print = 1; double unused;   for (uint64_t i = 2; i < sieve_size && prime_count <= PRIMORIAL_LIMIT; ++i) { if (print) { if (prime_count < 10) gmp_printf("Primorial(%" PRIu64 ") = %Zd\n", prime_count, primorial); /* Is the current number a power of 10? */ else if (!modf(log10(prime_count), &unused)) printf("Primorial(%" PRIu64 ") has %zu digits\n", prime_count, mpz_number_of_digits(primorial)); print = 0; }   if (es_check(sieve, i)) { mpz_mul_ui(primorial, primorial, i); prime_count++; print = 1; }   }   free(sieve); mpz_clear(primorial); return 0; }  
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Euphoria
Euphoria
function tri(atom lim, sequence in) sequence r atom p p = in[1] + in[2] + in[3] if p > lim then return {0, 0} end if r = {1, floor(lim / p)} r += tri(lim, { in[1]-2*in[2]+2*in[3], 2*in[1]-in[2]+2*in[3], 2*in[1]-2*in[2]+3*in[3]}) r += tri(lim, { in[1]+2*in[2]+2*in[3], 2*in[1]+in[2]+2*in[3], 2*in[1]+2*in[2]+3*in[3]}) r += tri(lim, {-in[1]+2*in[2]+2*in[3], -2*in[1]+in[2]+2*in[3], -2*in[1]+2*in[2]+3*in[3]}) return r end function   atom max_peri max_peri = 10 while max_peri <= 100000000 do printf(1,"%d: ", max_peri) ? tri(max_peri, {3, 4, 5}) max_peri *= 10 end while
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Unlambda
Unlambda
``d`.v`.vv```s``si`k`ki``si`k`d`..`.``.d`.``.c`.s`.``.``.s`.``.``.vv``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.dv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.vv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.vv``s``sc`d`.vv``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.sv``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.sv``s``sc`d`.iv``s``sc`d`.`v``s``sc`d`.kv``s``sc`d`.`v``s``sc`d`.kv``s``sc`d`.iv``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.sv``s``sc`d`.iv``s``sc`d`.`v``s``sc`d`.kv``s``sc`d`.`v``s``sc`d`.dv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.dv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.cv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.sv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.sv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.vvv
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#V
V
[p [put ' 'put] map ' ' puts].