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/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. Pseudo code var seed = 675248 function random() var s = str(seed * seed) 'str: turn a number into string do while not len(s) = 12 s = "0" + s 'add zeroes before the string end do seed = val(mid(s, 4, 6)) 'mid: string variable, start, length 'val: turn a string into number return seed end function Middle-square method use for i = 1 to 5 print random() end for Task Generate a class/set of functions that generates pseudo-random numbers (6 digits) as shown above. Show the first five integers generated with the seed 675248 as shown above. Show your output here, on this page.
#VBA
VBA
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. Pseudo code var seed = 675248 function random() var s = str(seed * seed) 'str: turn a number into string do while not len(s) = 12 s = "0" + s 'add zeroes before the string end do seed = val(mid(s, 4, 6)) 'mid: string variable, start, length 'val: turn a string into number return seed end function Middle-square method use for i = 1 to 5 print random() end for Task Generate a class/set of functions that generates pseudo-random numbers (6 digits) as shown above. Show the first five integers generated with the seed 675248 as shown above. Show your output here, on this page.
#Visual_Basic
Visual Basic
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. Pseudo code var seed = 675248 function random() var s = str(seed * seed) 'str: turn a number into string do while not len(s) = 12 s = "0" + s 'add zeroes before the string end do seed = val(mid(s, 4, 6)) 'mid: string variable, start, length 'val: turn a string into number return seed end function Middle-square method use for i = 1 to 5 print random() end for Task Generate a class/set of functions that generates pseudo-random numbers (6 digits) as shown above. Show the first five integers generated with the seed 675248 as shown above. Show your output here, on this page.
#Wren
Wren
var random = Fn.new { |seed| ((seed * seed)/1e3).floor % 1e6 }   var seed = 675248 for (i in 1..5) System.print(seed = random.call(seed))
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.
#Pony
Pony
actor Main new create(env: Env) => let a = """env.out.print("actor Main\nnew create(env: Env) =>\nlet a = \"\"\""+a+"\"\"\"\n"+a)""" env.out.print("actor Main\nnew create(env: Env) =>\nlet a = \"\"\""+a+"\"\"\"\n"+a)
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.
#C.2B.2B
C++
#include <array> #include <iostream>   int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; }   class RNG { private: // First generator const std::array<int64_t, 3> a1{ 0, 1403580, -810728 }; const int64_t m1 = (1LL << 32) - 209; std::array<int64_t, 3> x1; // Second generator const std::array<int64_t, 3> a2{ 527612, 0, -1370589 }; const int64_t m2 = (1LL << 32) - 22853; std::array<int64_t, 3> x2; // other const int64_t d = (1LL << 32) - 209 + 1; // m1 + 1   public: void seed(int64_t state) { x1 = { state, 0, 0 }; x2 = { state, 0, 0 }; }   int64_t next_int() { int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1); int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2); int64_t z = mod(x1i - x2i, m1);   // keep last three values of the first generator x1 = { x1i, x1[0], x1[1] }; // keep last three values of the second generator x2 = { x2i, x2[0], x2[1] };   return z + 1; }   double next_float() { return static_cast<double>(next_int()) / d; } };   int main() { RNG rng;   rng.seed(1234567); std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << '\n';   std::array<int, 5> counts{ 0, 0, 0, 0, 0 }; rng.seed(987654321); for (size_t i = 0; i < 100000; i++) { auto value = floor(rng.next_float() * 5.0); counts[value]++; } for (size_t i = 0; i < counts.size(); i++) { std::cout << i << ": " << counts[i] << '\n'; }   return 0; }
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#Phix
Phix
puts(1,"NB: These are not expected to match the task spec!\n") set_rand(42) for i=1 to 5 do printf(1,"%d\n",rand(-1)) end for set_rand(987654321) sequence s = repeat(0,5) for i=1 to 100000 do s[floor(rnd()*5)+1] += 1 end for ?s
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.
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => { const xs = takeWhileGen( x => 2200 >= x, mergeInOrder( powersOfTwo(), fmapGen(x => 5 * x, powersOfTwo()) ) );   return ( console.log(JSON.stringify(xs)), xs ); }   // powersOfTwo :: Gen [Int] const powersOfTwo = () => iterate(x => 2 * x, 1);   // mergeInOrder :: Gen [Int] -> Gen [Int] -> Gen [Int] const mergeInOrder = (ga, gb) => { function* go(ma, mb) { let a = ma, b = mb; while (!a.Nothing && !b.Nothing) { let ta = a.Just, tb = b.Just; if (fst(ta) < fst(tb)) { yield(fst(ta)); a = uncons(snd(ta)) } else { yield(fst(tb)); b = uncons(snd(tb)) } } } return go(uncons(ga), uncons(gb)) };     // GENERIC FUNCTIONS ----------------------------   // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b] function* fmapGen(f, gen) { const g = gen; let v = take(1, g); while (0 < v.length) { yield(f(v)) v = take(1, g) } }   // fst :: (a, b) -> a const fst = tpl => tpl[0];   // iterate :: (a -> a) -> a -> Generator [a] function* iterate(f, x) { let v = x; while (true) { yield(v); v = f(v); } }   // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x });   // Returns Infinity over objects without finite length // this enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc   // length :: [a] -> Int const length = xs => xs.length || Infinity;   // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, });   // snd :: (a, b) -> b const snd = tpl => tpl[1];   // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => xs.constructor.constructor.name !== 'GeneratorFunction' ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));   // takeWhileGen :: (a -> Bool) -> Generator [a] -> [a] const takeWhileGen = (p, xs) => { const ys = []; let nxt = xs.next(), v = nxt.value; while (!nxt.done && p(v)) { ys.push(v); nxt = xs.next(); v = nxt.value } return ys; };   // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // uncons :: [a] -> Maybe (a, [a]) const uncons = xs => { const lng = length(xs); return (0 < lng) ? ( lng < Infinity ? ( Just(Tuple(xs[0], xs.slice(1))) // Finite list ) : (() => { const nxt = take(1, xs); return 0 < nxt.length ? ( Just(Tuple(nxt[0], xs)) ) : Nothing(); })() // Lazy generator ) : Nothing(); };   // MAIN --- return main(); })();
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
#J
J
gnuplot --persist -e 'plot"<ijconsole /tmp/pt.ijs"w l'
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes several fairly rigorous PRNG "fitness" tests that some more complex algorithms fail. Splitmix64 is not recommended for demanding random number requirements, but is often used to calculate initial states for other more complex pseudo-random number generators. The "standard" splitmix64 maintains one 64 bit state variable and returns 64 bits of random data with each call. Basic pseudocode algorithm: uint64 state /* The state can be seeded with any (upto) 64 bit integer value. */ next_int() { state += 0x9e3779b97f4a7c15 /* increment the state variable */ uint64 z = state /* copy the state to a working variable */ z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9 /* xor the variable with the variable right bit shifted 30 then multiply by a constant */ z = (z ^ (z >> 27)) * 0x94d049bb133111eb /* xor the variable with the variable right bit shifted 27 then multiply by a constant */ return z ^ (z >> 31) /* return the variable xored with itself right bit shifted 31 */ } next_float() { return next_int() / (1 << 64) /* divide by 2^64 to return a value between 0 and 1 */ } The returned value should hold 64 bits of numeric data. If your language does not support unsigned 64 bit integers directly you may need to apply appropriate bitmasks during bitwise operations. In keeping with the general layout of several recent pseudo-random number tasks: Task Write a class or set of functions that generates pseudo-random numbers using splitmix64. Show the first five integers generated using the seed 1234567. 6457827717110365317 3203168211198807973 9817491932198370423 4593380528125082431 16408922859458223821 Show that for an initial seed of 987654321, the counts of 100_000 repetitions of floor next_float() * 5 is as follows: 0: 20027, 1: 19892, 2: 20073, 3: 19978, 4: 20030 Show your output here, on this page. See also Java docs for splitmix64 Public domain C code used in many PRNG implementations; by Sebastiano Vigna Related tasks Pseudo-random numbers/Combined recursive generator MRG32k3a‎‎ Pseudo-random numbers/PCG32‎‎ Pseudo-random_numbers/Xorshift_star
#Raku
Raku
class splitmix64 { has $!state;   submethod BUILD ( Int :$seed where * >= 0 = 1 ) { $!state = $seed }   method next-int { my $next = $!state = ($!state + 0x9e3779b97f4a7c15) +& (2⁶⁴ - 1); $next = ($next +^ ($next +> 30)) * 0xbf58476d1ce4e5b9 +& (2⁶⁴ - 1); $next = ($next +^ ($next +> 27)) * 0x94d049bb133111eb +& (2⁶⁴ - 1); ($next +^ ($next +> 31)) +& (2⁶⁴ - 1); }   method next-rat { self.next-int / 2⁶⁴ } }   # Test next-int say 'Seed: 1234567; first five Int values'; my $rng = splitmix64.new( :seed(1234567) ); .say for $rng.next-int xx 5;     # Test next-rat (since these are rational numbers by default) say "\nSeed: 987654321; first 1e5 Rat values histogram"; $rng = splitmix64.new( :seed(987654321) ); say ( ($rng.next-rat * 5).floor xx 100_000 ).Bag;
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
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 DECLARE EXTERNAL SUB tri 110 ! 120 PUBLIC NUMERIC U0(3,3), U1(3,3), U2(3,3), all, prim 130 DIM seed(3) 140 MAT READ U0, U1, U2 150 DATA 1, -2, 2, 2, -1, 2, 2, -2, 3 160 DATA 1, 2, 2, 2, 1, 2, 2, 2, 3 170 DATA -1, 2, 2, -2, 1, 2, -2, 2, 3 180 ! 190 MAT READ seed 200 DATA 3, 4, 5 210 FOR power = 1 TO 7 220 LET all = 0 230 LET prim = 0 240 CALL tri(seed, 10^power , all , prim) 250 PRINT "Up to 10^";power, 260 PRINT USING "######### triples ######### primitives":all,prim 270 NEXT power 280 END 290 ! 300 EXTERNAL SUB tri(i(), mp, all, prim) 310 DECLARE EXTERNAL FUNCTION SUM 320 DECLARE NUMERIC t(3) 330 ! 340 IF SUM(i) > mp THEN EXIT SUB 350 LET prim = prim + 1 360 LET all = all + INT(mp / SUM(i)) 370 ! 380 MAT t = U0 * i 390 CALL tri(t, mp , all , prim) 400 MAT t = U1 * i 410 CALL tri(t, mp , all , prim) 420 MAT t = U2 * i 430 CALL tri(t, mp , all , prim) 440 END SUB 450 ! 460 EXTERNAL FUNCTION SUM(a()) 470 LET temp = 0 480 FOR i=LBOUND(a) TO UBOUND(a) 490 LET temp = temp + a(i) 500 NEXT i 510 LET SUM = temp 520 END FUNCTION
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. Pseudo code var seed = 675248 function random() var s = str(seed * seed) 'str: turn a number into string do while not len(s) = 12 s = "0" + s 'add zeroes before the string end do seed = val(mid(s, 4, 6)) 'mid: string variable, start, length 'val: turn a string into number return seed end function Middle-square method use for i = 1 to 5 print random() end for Task Generate a class/set of functions that generates pseudo-random numbers (6 digits) as shown above. Show the first five integers generated with the seed 675248 as shown above. Show your output here, on this page.
#XPL0
XPL0
real Seed; func Random; [Seed:= Floor(Mod(Seed*Seed/1e3, 1e6)); return fix(Seed); ];   int N; [Seed:= 675248.; for N:= 1 to 5 do [IntOut(0, Random); ChOut(0, ^ )]; ]
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.
#PowerBASIC
PowerBASIC
FUNCTION PBMAIN () AS LONG REDIM s(1 TO DATACOUNT) AS STRING o$ = READ$(1) d$ = READ$(2) FOR n& = 1 TO DATACOUNT s(n&) = READ$(n&) NEXT OPEN o$ FOR OUTPUT AS 1 FOR n& = 3 TO DATACOUNT - 1 PRINT #1, s(n&) NEXT PRINT #1, FOR n& = 1 TO DATACOUNT PRINT #1, d$ & $DQ & s(n&) & $DQ NEXT PRINT #1, s(DATACOUNT) CLOSE   DATA "output.src" DATA " DATA " DATA "FUNCTION PBMAIN () AS LONG" DATA " REDIM s(1 TO DATACOUNT) AS STRING" DATA " o$ = READ$(1)" DATA " d$ = READ$(2)" DATA " FOR n& = 1 TO DATACOUNT" DATA " s(n&) = READ$(n&)" DATA " NEXT" DATA " OPEN o$ FOR OUTPUT AS 1" DATA " FOR n& = 3 TO DATACOUNT - 1" DATA " PRINT #1, s(n&)" DATA " NEXT" DATA " PRINT #1," DATA " FOR n& = 1 TO DATACOUNT" DATA " PRINT #1, d$ & $DQ & s(n&) & $DQ" DATA " NEXT" DATA " PRINT #1, s(DATACOUNT)" DATA " CLOSE" DATA "END FUNCTION" END FUNCTION
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.
#D
D
import std.math; import std.stdio;   long mod(long x, long y) { long m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; }   class RNG { private: // First generator immutable(long []) a1 = [0, 1403580, -810728]; immutable long m1 = (1L << 32) - 209; long[3] x1; // Second generator immutable(long []) a2 = [527612, 0, -1370589]; immutable long m2 = (1L << 32) - 22853; long[3] x2; // other immutable long d = m1 + 1;   public: void seed(long state) { x1 = [state, 0, 0]; x2 = [state, 0, 0]; }   long next_int() { long x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1); long x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2); long z = mod(x1i - x2i, m1);   // keep the last three values of the first generator x1 = [x1i, x1[0], x1[1]]; // keep the last three values of the second generator x2 = [x2i, x2[0], x2[1]];   return z + 1; }   double next_float() { return cast(double) next_int() / d; } }   void main() { auto rng = new RNG();   rng.seed(1234567); writeln(rng.next_int); writeln(rng.next_int); writeln(rng.next_int); writeln(rng.next_int); writeln(rng.next_int); writeln;   int[5] counts; rng.seed(987654321); foreach (i; 0 .. 100_000) { auto value = cast(int) floor(rng.next_float * 5.0); counts[value]++; } foreach (i,v; counts) { writeln(i, ": ", v); } }
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#Python
Python
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 CONST = 6364136223846793005     class PCG32():   def __init__(self, seed_state=None, seed_sequence=None): if all(type(x) == int for x in (seed_state, seed_sequence)): self.seed(seed_state, seed_sequence) else: self.state = self.inc = 0   def seed(self, seed_state, seed_sequence): self.state = 0 self.inc = ((seed_sequence << 1) | 1) & mask64 self.next_int() self.state = (self.state + seed_state) self.next_int()   def next_int(self): "return random 32 bit unsigned int" old = self.state self.state = ((old * CONST) + self.inc) & mask64 xorshifted = (((old >> 18) ^ old) >> 27) & mask32 rot = (old >> 59) & mask32 answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)) answer = answer &mask32   return answer   def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 32)     if __name__ == '__main__': random_gen = PCG32() random_gen.seed(42, 54) for i in range(5): print(random_gen.next_int())   random_gen.seed(987654321, 1) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
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.
#jq
jq
# Emit a proof that the input is a pythagorean quad, or else false def is_pythagorean_quad: . as $d | (.*.) as $d2 | first( label $continue_a | range(1; $d) | . as $a | (.*.) as $a2 | if 3*$a2 > $d2 then break $continue_a else . end | label $continue_b | range($a; $d) | . as $b | (.*.) as $b2 | if $a2 + 2 * $b2 > $d2 then break $continue_b else . end | (($d2-($a2+$b2)) | sqrt) as $c | if ($c | floor) == $c then [$a, $b, $c] else empty end ) // false;   # The specific task:   [range(1; 2201) | select( is_pythagorean_quad | not )] | join(" ")
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.
#Julia
Julia
function quadruples(N::Int=2200) r = falses(N) ab = falses(2N ^ 2)   for a in 1:N, b in a:N ab[a ^ 2 + b ^ 2] = true end   s = 3 for c in 1:N s1, s, s2 = s, s + 2, s + 2 for d in c+1:N if ab[s1] r[d] = true end s1 += s2 s2 += 2 end end   return findall(!, r) end   println("Pythagorean quadruples up to 2200: ", join(quadruples(), ", "))
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
#Java
Java
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*;   public class PythagorasTree extends JPanel { final int depthLimit = 7; float hue = 0.15f;   public PythagorasTree() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); }   private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2, int depth) {   if (depth == depthLimit) return;   float dx = x2 - x1; float dy = y1 - y2;   float x3 = x2 - dy; float y3 = y2 - dx; float x4 = x1 - dy; float y4 = y1 - dx; float x5 = x4 + 0.5F * (dx - dy); float y5 = y4 - 0.5F * (dx + dy);   Path2D square = new Path2D.Float(); square.moveTo(x1, y1); square.lineTo(x2, y2); square.lineTo(x3, y3); square.lineTo(x4, y4); square.closePath();   g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1)); g.fill(square); g.setColor(Color.lightGray); g.draw(square);   Path2D triangle = new Path2D.Float(); triangle.moveTo(x3, y3); triangle.lineTo(x4, y4); triangle.lineTo(x5, y5); triangle.closePath();   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); }   @Override public void paintComponent(Graphics g) { super.paintComponent(g); drawTree((Graphics2D) g, 275, 500, 375, 500, 0); }   public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pythagoras Tree"); f.setResizable(false); f.add(new PythagorasTree(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes several fairly rigorous PRNG "fitness" tests that some more complex algorithms fail. Splitmix64 is not recommended for demanding random number requirements, but is often used to calculate initial states for other more complex pseudo-random number generators. The "standard" splitmix64 maintains one 64 bit state variable and returns 64 bits of random data with each call. Basic pseudocode algorithm: uint64 state /* The state can be seeded with any (upto) 64 bit integer value. */ next_int() { state += 0x9e3779b97f4a7c15 /* increment the state variable */ uint64 z = state /* copy the state to a working variable */ z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9 /* xor the variable with the variable right bit shifted 30 then multiply by a constant */ z = (z ^ (z >> 27)) * 0x94d049bb133111eb /* xor the variable with the variable right bit shifted 27 then multiply by a constant */ return z ^ (z >> 31) /* return the variable xored with itself right bit shifted 31 */ } next_float() { return next_int() / (1 << 64) /* divide by 2^64 to return a value between 0 and 1 */ } The returned value should hold 64 bits of numeric data. If your language does not support unsigned 64 bit integers directly you may need to apply appropriate bitmasks during bitwise operations. In keeping with the general layout of several recent pseudo-random number tasks: Task Write a class or set of functions that generates pseudo-random numbers using splitmix64. Show the first five integers generated using the seed 1234567. 6457827717110365317 3203168211198807973 9817491932198370423 4593380528125082431 16408922859458223821 Show that for an initial seed of 987654321, the counts of 100_000 repetitions of floor next_float() * 5 is as follows: 0: 20027, 1: 19892, 2: 20073, 3: 19978, 4: 20030 Show your output here, on this page. See also Java docs for splitmix64 Public domain C code used in many PRNG implementations; by Sebastiano Vigna Related tasks Pseudo-random numbers/Combined recursive generator MRG32k3a‎‎ Pseudo-random numbers/PCG32‎‎ Pseudo-random_numbers/Xorshift_star
#REXX
REXX
/*REXX program generates pseudo─random numbers using the split mix 64 bit method.*/ numeric digits 200 /*ensure enough decimal digs for mult. */ parse arg n reps pick seed1 seed2 . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 5 /*Not specified? Then use the default.*/ if reps=='' | reps=="," then reps= 100000 /* " " " " " " */ if pick=='' | pick=="," then pick= 5 /* " " " " " " */ if seed1=='' | seed1=="," then seed1= 1234567 /* " " " " " " */ if seed2=='' | seed2=="," then seed2= 987654321 /* " " " " " " */ const.1= x2d( 9e3779b97f4a7c15 ) /*initialize 1st constant to be used. */ const.2= x2d('bf58476d1ce4e5b9') /* " 2nd " " " " */ const.3= x2d( 94d049bb133111eb ) /* " 3rd " " " " */ o.30= copies(0, 30) /*construct 30 bits of zeros. */ o.27= copies(0, 27) /* " 27 " " " */ o.31= copies(0, 31) /* " 31 " " " */ w= max(3, length(n) ) /*for aligning the left side of output.*/ state= seed1 /* " the state to seed #1. */ do j=1 for n if j==1 then do; say center('n', w) " pseudo─random number " say copies('═', w) " ════════════════════════════" end say right(j':', w)" " right(commas(next()), 27) /*display a random number*/ end /*j*/ say if reps==0 then exit 0 /*stick a fork in it, we're all done. */ say center('#', w) " count of pseudo─random #" say copies('═', w) " ════════════════════════════" state= seed2 /* " the state to seed #2. */ @.= 0; div= pick / 2**64 /*convert division to inverse multiply.*/ do k=1 for reps parse value next()*div with _ '.' /*get random #, floor of a "division". */ @._= @._ + 1 /*bump the counter for this random num.*/ end /*k*/   do #=0 for pick say right(#':', w)" " right(commas(@.#), 15) /*show count of a random num.*/ end /*#*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do ?=length(_)-3 to 1 by -3; _= insert(',', _, ?); end; return _ b2d: parse arg ?; return x2d( b2x(?) ) /*convert bin──►decimal. */ d2b: parse arg ?; return right( x2b( d2x(?) ), 64, 0) /*convert dec──►64 bit bin.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ next: procedure expose state const. o. state= state + const.1  ; z= d2b(state) /*add const1──►STATE; conv.*/ z= xor(z, left(o.30 || z, 64)); z= d2b(b2d(z)*const.2) /*shiftR 30 bits & XOR; " */ z= xor(z, left(o.27 || z, 64)); z= d2b(b2d(z)*const.3) /* " 27 " " " " */ z= xor(z, left(o.31 || z, 64)); return b2d(z) /* " 31 " " " " */ /*──────────────────────────────────────────────────────────────────────────────────────*/ xor: parse arg a, b; $= /*perform a bit─wise XOR. */ do !=1 for length(a); $= $ || (substr(a,!,1) && substr(b,!,1) ) end /*!*/; return $
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
#Arturo
Arturo
triples: new [] loop 1..50 'x [ loop 1..50 'y [ loop (max @[x y])..100 'z [ if 100 > sum @[x y z] [ if (z^2) = add x^2 y^2 -> 'triples ++ @[sort @[x y z]] ] ] ] ] unique 'triples   print ["Found" size triples "pythagorean triples with a perimeter no larger than 100:"] print triples   primitive: select triples => [1 = gcd]   print "" print [size primitive "of them are primitive:"] print 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.
#PowerShell
PowerShell
$S = '$S = $S.Substring(0,5) + [string][char]39 + $S + [string][char]39 + [string][char]10 + $S.Substring(5)' $S.Substring(0,5) + [string][char]39 + $S + [string][char]39 + [string][char]10 + $S.Substring(5)
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.
#Factor
Factor
USING: arrays kernel math math.order math.statistics math.vectors prettyprint sequences ;   CONSTANT: m1 4294967087 CONSTANT: m2 4294944443   : seed ( n -- seq1 seq2 ) dup 1 m1 between? t assert= 0 0 3array dup ;   : new-state ( seq1 seq2 n -- new-seq ) [ dup ] [ vdot ] [ rem prefix but-last ] tri* ;   : next-state ( a b -- a' b' ) [ { 0 1403580 -810728 } m1 new-state ] [ { 527612 0 -1370589 } m2 new-state ] bi* ;   : next-int ( a b -- a' b' n ) next-state 2dup [ first ] bi@ - m1 rem 1 + ;   : next-float ( a b -- a' b' x ) next-int m1 1 + /f ;   ! Task 1234567 seed 5 [ next-int . ] times 2drop   987654321 seed 100,000 [ next-float 5 * >integer ] replicate 2nip histogram .
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.
#Forth
Forth
6 array (seed) \ holds the seed 6 array (gens) \ holds the generators \ set up constants 0 (gens) 0 th ! \ 1st generator 1403580 (gens) 1 th ! -810728 (gens) 2 th ! 527612 (gens) 3 th ! \ 2nd generator 0 (gens) 4 th ! -1370589 (gens) 5 th !   1 32 lshift 209 - value (m) \ 1st generator constant 1 32 lshift 22853 - value (n) \ 2nd generator constant ( n1 n2 -- n3) : (mod) tuck mod tuck 0< if abs + ;then drop ; : (generate) do (seed) i th @ (gens) i th @ * + loop swap (mod) ; : (reseed) ?do (seed) i th ! loop ; ( n1 n2 n3 limit index --) : randomize 6 0 do dup i 3 mod if >zero then (seed) i th ! loop drop ; ( n --) : random ( -- n) (m) 0 3 0 (generate) (n) 0 6 3 (generate) over over (seed) 4 th @ (seed) 3 th @ rot 6 3 (reseed) (seed) 1 th @ (seed) 0 th @ rot 3 0 (reseed) - (m) (mod) 1+ ;   include lib/fp1.4th \ simple floating point support include lib/zenfloor.4th \ for FLOOR   5 array (count) \ setup an array of 5 elements   : test 1234567 randomize random . cr random . cr random . cr random . cr random . cr cr \ perform the first test   987654321 randomize (m) 1+ s>f \ set up denominator   100000 0 ?do \ do this 100,000 times random s>f fover f/ 5 s>f f* floor f>s cells (count) + 1 swap +! loop fdrop \ show the results 5 0 ?do i . ." : " (count) i th ? cr loop ;   test
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#Raku
Raku
class PCG32 { has $!state; has $!incr; constant mask32 = 2³² - 1; constant mask64 = 2⁶⁴ - 1; constant const = 6364136223846793005;   submethod BUILD ( Int :$seed = 0x853c49e6748fea9b, # default seed Int :$incr = 0xda3e39cb94b95bdb # default increment ) { $!incr = $incr +< 1 +| 1 +& mask64; $!state = (($!incr + $seed) * const + $!incr) +& mask64; }   method next-int { my $shift = ($!state +> 18 +^ $!state) +> 27 +& mask32; my $rotate = $!state +> 59 +& 31; $!state = ($!state * const + $!incr) +& mask64; ($shift +> $rotate) +| ($shift +< (32 - $rotate) +& mask32) }   method next-rat { self.next-int / 2³² } }     # Test next-int with custom seed and increment say 'Seed: 42, Increment: 54; first five Int values:'; my $rng = PCG32.new( :seed(42), :incr(54) ); .say for $rng.next-int xx 5;     # Test next-rat (since these are rational numbers by default) say "\nSeed: 987654321, Increment: 1; first 1e5 Rat values histogram:"; $rng = PCG32.new( :seed(987654321), :incr(1) ); say ( ($rng.next-rat * 5).floor xx 100_000 ).Bag;     # Test next-int with default seed and increment say "\nSeed: default, Increment: default; first five Int values:"; $rng = PCG32.new; .say for $rng.next-int xx 5;
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.
#Kotlin
Kotlin
// version 1.1.3   const val MAX = 2200 const val MAX2 = MAX * MAX - 1   fun main(args: Array<String>) { val found = BooleanArray(MAX + 1) // all false by default val p2 = IntArray(MAX + 1) { it * it } // pre-compute squares   // compute all possible positive values of d * d - c * c and map them back to d val dc = mutableMapOf<Int, MutableList<Int>>() for (d in 1..MAX) { for (c in 1 until d) { val diff = p2[d] - p2[c] val v = dc[diff] if (v == null) dc.put(diff, mutableListOf(d)) else if (d !in v) v.add(d) } }   for (a in 1..MAX) { for (b in 1..a) { if ((a and 1) != 0 && (b and 1) != 0) continue val sum = p2[a] + p2[b] if (sum > MAX2) continue val v = dc[sum] if (v != null) v.forEach { found[it] = true } } } println("The values of d <= $MAX which can't be represented:") for (i in 1..MAX) if (!found[i]) print("$i ") 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
#JavaScript
JavaScript
<!DOCTYPE html> <html lang="en">   <head> <meta charset="UTF-8"> <style> canvas { position: absolute; top: 45%; left: 50%; width: 640px; height: 640px; margin: -320px 0 0 -320px; } </style> </head>   <body> <canvas></canvas> <script> 'use strict'; var canvas = document.querySelector('canvas'); canvas.width = 640; canvas.height = 640;   var g = canvas.getContext('2d');   var depthLimit = 7; var hue = 0.15;   function drawTree(x1, y1, x2, y2, depth) {   if (depth == depthLimit) 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);   g.beginPath(); g.moveTo(x1, y1); g.lineTo(x2, y2); g.lineTo(x3, y3); g.lineTo(x4, y4); g.closePath();   g.fillStyle = HSVtoRGB(hue + depth * 0.02, 1, 1); g.fill(); g.strokeStyle = "lightGray"; g.stroke();   g.beginPath(); g.moveTo(x3, y3); g.lineTo(x4, y4); g.lineTo(x5, y5); g.closePath();   g.fillStyle = HSVtoRGB(hue + depth * 0.035, 1, 1); g.fill(); g.strokeStyle = "lightGray"; g.stroke();   drawTree(x4, y4, x5, y5, depth + 1); drawTree(x5, y5, x3, y3, depth + 1); }   /* copied from stackoverflow */ function HSVtoRGB(h, s, v) { var r, g, b, i, f, p, q, t;   i = Math.floor(h * 6); f = h * 6 - i; p = v * (1 - s); q = v * (1 - f * s); t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return "rgb(" + Math.round(r * 255) + "," + Math.round(g * 255) + "," + Math.round(b * 255) + ")"; }   function draw() { g.clearRect(0, 0, canvas.width, canvas.height); drawTree(275, 500, 375, 500, 0); } draw(); </script>   </body>   </html>
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes several fairly rigorous PRNG "fitness" tests that some more complex algorithms fail. Splitmix64 is not recommended for demanding random number requirements, but is often used to calculate initial states for other more complex pseudo-random number generators. The "standard" splitmix64 maintains one 64 bit state variable and returns 64 bits of random data with each call. Basic pseudocode algorithm: uint64 state /* The state can be seeded with any (upto) 64 bit integer value. */ next_int() { state += 0x9e3779b97f4a7c15 /* increment the state variable */ uint64 z = state /* copy the state to a working variable */ z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9 /* xor the variable with the variable right bit shifted 30 then multiply by a constant */ z = (z ^ (z >> 27)) * 0x94d049bb133111eb /* xor the variable with the variable right bit shifted 27 then multiply by a constant */ return z ^ (z >> 31) /* return the variable xored with itself right bit shifted 31 */ } next_float() { return next_int() / (1 << 64) /* divide by 2^64 to return a value between 0 and 1 */ } The returned value should hold 64 bits of numeric data. If your language does not support unsigned 64 bit integers directly you may need to apply appropriate bitmasks during bitwise operations. In keeping with the general layout of several recent pseudo-random number tasks: Task Write a class or set of functions that generates pseudo-random numbers using splitmix64. Show the first five integers generated using the seed 1234567. 6457827717110365317 3203168211198807973 9817491932198370423 4593380528125082431 16408922859458223821 Show that for an initial seed of 987654321, the counts of 100_000 repetitions of floor next_float() * 5 is as follows: 0: 20027, 1: 19892, 2: 20073, 3: 19978, 4: 20030 Show your output here, on this page. See also Java docs for splitmix64 Public domain C code used in many PRNG implementations; by Sebastiano Vigna Related tasks Pseudo-random numbers/Combined recursive generator MRG32k3a‎‎ Pseudo-random numbers/PCG32‎‎ Pseudo-random_numbers/Xorshift_star
#Ruby
Ruby
class Splitmix64 MASK64 = (1 << 64) - 1 C1, C2, C3 = 0x9e3779b97f4a7c15, 0xbf58476d1ce4e5b9, 0x94d049bb133111eb   def initialize(seed = 0) = @state = seed & MASK64   def rand_i z = @state = (@state + C1) & MASK64 z = ((z ^ (z >> 30)) * C2) & MASK64 z = ((z ^ (z >> 27)) * C3) & MASK64 (z ^ (z >> 31)) & MASK64 end   def rand_f = rand_i.fdiv(1<<64)   end   rand_gen = Splitmix64.new(1234567) 5.times{ puts rand_gen.rand_i }   rand_gen = Splitmix64.new(987654321) p 100_000.times.lazy.map{(rand_gen.rand_f * 5).floor}.tally.sort.to_h  
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes several fairly rigorous PRNG "fitness" tests that some more complex algorithms fail. Splitmix64 is not recommended for demanding random number requirements, but is often used to calculate initial states for other more complex pseudo-random number generators. The "standard" splitmix64 maintains one 64 bit state variable and returns 64 bits of random data with each call. Basic pseudocode algorithm: uint64 state /* The state can be seeded with any (upto) 64 bit integer value. */ next_int() { state += 0x9e3779b97f4a7c15 /* increment the state variable */ uint64 z = state /* copy the state to a working variable */ z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9 /* xor the variable with the variable right bit shifted 30 then multiply by a constant */ z = (z ^ (z >> 27)) * 0x94d049bb133111eb /* xor the variable with the variable right bit shifted 27 then multiply by a constant */ return z ^ (z >> 31) /* return the variable xored with itself right bit shifted 31 */ } next_float() { return next_int() / (1 << 64) /* divide by 2^64 to return a value between 0 and 1 */ } The returned value should hold 64 bits of numeric data. If your language does not support unsigned 64 bit integers directly you may need to apply appropriate bitmasks during bitwise operations. In keeping with the general layout of several recent pseudo-random number tasks: Task Write a class or set of functions that generates pseudo-random numbers using splitmix64. Show the first five integers generated using the seed 1234567. 6457827717110365317 3203168211198807973 9817491932198370423 4593380528125082431 16408922859458223821 Show that for an initial seed of 987654321, the counts of 100_000 repetitions of floor next_float() * 5 is as follows: 0: 20027, 1: 19892, 2: 20073, 3: 19978, 4: 20030 Show your output here, on this page. See also Java docs for splitmix64 Public domain C code used in many PRNG implementations; by Sebastiano Vigna Related tasks Pseudo-random numbers/Combined recursive generator MRG32k3a‎‎ Pseudo-random numbers/PCG32‎‎ Pseudo-random_numbers/Xorshift_star
#Sidef
Sidef
class Splitmix64(state) {   define ( mask64 = (2**64 - 1) )   method next_int { var n = (state = ((state + 0x9e3779b97f4a7c15) & mask64)) n = ((n ^ (n >> 30)) * 0xbf58476d1ce4e5b9 & mask64) n = ((n ^ (n >> 27)) * 0x94d049bb133111eb & mask64) (n ^ (n >> 31)) & mask64 }   method next_float { self.next_int / (mask64+1) } }   say 'Seed: 1234567, first 5 values:' var rng = Splitmix64(1234567) 5.of { rng.next_int.say }   say "\nSeed: 987654321, values histogram:" var rng = Splitmix64(987654321) var histogram = Bag(1e5.of { floor(5*rng.next_float) }...) histogram.pairs.sort.each { .join(": ").say }
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
#APL
APL
  ⍝ Determine whether given list of integers has GCD = 1 primitive←∧/1=2∨/⊢ ⍝ Filter list given as right operand by applying predicate given as left operand filter←{⍵⌿⍨⍺⍺ ⍵}   ⍝ Function pytriples finds all triples given a maximum perimeter ∇res←pytriples maxperimeter;sos;sqrt;cartprod;ascending;ab_max;c_max;a_b_pairs;sos_is_sq;add_c;perimeter_rule ⍝ Input parameter maxperimeter is the maximum perimeter ⍝ Sum of squares of given list of nrs sos←+/(×⍨⊢) ⍝ Square root sqrt←(÷2)*⍨⊢ ⍝ (cartesian product) all possible pairs of integers ⍝ from 1 to ⍵ cartprod←{,{⍺∘.,⍵}⍨⍳⍵} ⍝ Predicate: are values in given list ascending ⍝ Given e.g. pair a, b, c: is a ≤ b ≤ c? ascending←∧/2≤/⊢ ab_max←⌊maxperimeter÷2 c_max←⌈maxperimeter×sqrt 2 ⍝ Selects from all a,b combinations (a<abmax, b<abmax) ⍝ only those pairs where a ≤ b. a_b_pairs←ascending filter¨cartprod(ab_max) ⍝ Predicate: is the sum of squares of a and b ⍝ itself a square? (does it occur in the squares list) sos_is_sq←{{⍵≠1+c_max}(×⍨⍳c_max)⍳sos¨⍵} ⍝ Given a pair a,b add corresponding c to form a triple add_c←{⍵,sqrt sos ⍵} ⍝ Predicate: sum of items less than or equal to max perimeter_rule←{maxperimeter≥+/⍵} res←perimeter_rule¨filter add_c¨sos_is_sq filter a_b_pairs ∇
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.
#Processing
Processing
String p="String p=%c%s%1$c;System.out.printf(p,34,p);";System.out.printf(p,34,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.
#Prolog
Prolog
quine :- listing(quine).
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.
#Go
Go
package main   import ( "fmt" "log" "math" )   var a1 = []int64{0, 1403580, -810728} var a2 = []int64{527612, 0, -1370589}   const m1 = int64((1 << 32) - 209) const m2 = int64((1 << 32) - 22853) const d = m1 + 1   // Python style modulus func mod(x, y int64) int64 { m := x % y if m < 0 { if y < 0 { return m - y } else { return m + y } } return m }   type MRG32k3a struct{ x1, x2 [3]int64 }   func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }   func (mrg *MRG32k3a) seed(seedState int64) { if seedState <= 0 || seedState >= d { log.Fatalf("Argument must be in the range [0, %d].\n", d) } mrg.x1 = [3]int64{seedState, 0, 0} mrg.x2 = [3]int64{seedState, 0, 0} }   func (mrg *MRG32k3a) nextInt() int64 { x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1) x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2) mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} /* keep last three */ mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} /* keep last three */ return mod(x1i-x2i, m1) + 1 }   func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }   func main() { randomGen := MRG32k3aNew() randomGen.seed(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) }   var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf("  %d : %d\n", i, counts[i]) } }
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#REXX
REXX
Numeric Digits 40 N = 6364136223846793005 state = x2d('853c49e6748fea9b',16) inc = x2d('da3e39cb94b95bdb',16) Call seed 42,54 Do zz=1 To 5 res=nextint() Say int2str(res) End Call seed 987654321,1 cnt.=0 Do i=1 To 100000 z=nextfloat() cnt.z=cnt.z+1 End Say '' Say 'The counts for 100,000 repetitions are:' Do z=0 To 4 Say format(z,2) ':' format(cnt.z,5) End Exit   int2str: Procedure int=arg(1) intx=d2x(int,8) res=x2d(copies(0,8)intx,16) Return res   seed: Parse Arg seedState,seedSequence state=0 inc=dshift(seedSequence,-1) inc=x2d(or(d2x(inc,16),d2x(1,16)),16) z=nextint() state=javaadd(state,seedState) z=nextint() Return   nextInt: old = state oldxN = javamult(old,n) statex= javaadd(oldxN,inc) state=statex oldx=d2x(old,16) oldb=x2b(oldx) oldb18=copies(0,18)left(oldb,64-18) oldb18o=bxor(oldb18,oldb) rb=copies(0,27)left(oldb18o,64-27) rx=b2x(rb) shifted=x2d(substr(rx,9),8) oldx=d2x(old,16) oldb=x2b(oldx) oldb2=copies(0,59)left(oldb,length(oldb)-59) oldx2=b2x(oldb2) rotx=x2d(substr(oldx2,9),8) t1=ishift(shifted,rotx,'L') t2=x2d(xneg(d2x(rotx,8)),8) t3=t2+1 t4=x2d(xand(d2x(t3,8),d2x(31,8)),8) t5=dshift(shifted,-t4) t5x=d2x(t5,16) t5y=substr(t5x,9) t5z=x2d(t5y,16) t7=x2d(or(d2x(t1,16),d2x(t5z,16)),16) t8=long2int(t7) Return t8   nextfloat: ni=nextint() nix=d2x(ni,8) niz=copies(0,8)nix u=x2d(niz,16) uu=u/(2**32) z=uu*5%1 Return z   javaadd: Procedure /********************************************************************** * Add two long integers and ignore the possible overflow **********************************************************************/ Numeric Digits 40 Parse Arg a,b r=a+b rx=d2x(r,18) res=right(rx,16) return x2d(res,16)   javamult: Procedure /********************************************************************** * Multiply java style **********************************************************************/ Numeric Digits 40 Parse Arg a,b m=d2x(a*b,16) res=x2d(m,16) Return res   bxor: Procedure /********************************************************************** * Exclusive Or two bit strings **********************************************************************/ Parse arg a,b res='' Do i=1 To length(a) res=res||(substr(a,i,1)<>substr(b,i,1)) End Return res   xxor: Procedure /********************************************************************** * Exclusive Or two hex strings **********************************************************************/ Parse Arg u,v ub=x2b(u) vb=x2b(v) res='' Do i=1 To 64 res=res||(substr(ub,i,1)<>substr(vb,i,1)) End res=b2x(res) Return res   xand: Procedure /********************************************************************** * And two hex strings **********************************************************************/ Parse Arg u,v ub=x2b(u) vb=x2b(v) res='' Do i=1 To length(ub) res=res||(substr(ub,i,1)&substr(vb,i,1)) End res=b2x(res) Return res   or: Procedure /********************************************************************** * Or two hex strings **********************************************************************/ Parse Arg u,v ub=x2b(u) vb=x2b(v) res='' Do i=1 To length(ub) res=res||(substr(ub,i,1)|substr(vb,i,1)) End res=b2x(res) Return res   long2int: Procedure /********************************************************************** * Cast long to int **********************************************************************/ Parse Arg long longx=d2x(long,16) int=x2d(substr(longx,9),8) Return int   xneg: Procedure /********************************************************************** * Negate a hex string **********************************************************************/ Parse Arg s sb=x2b(s) res='' Do i=1 To length(sb) res=res||\substr(sb,i,1) End res=b2x(res) Return res   dshift: Procedure /********************************************************************** * Implement the shift operations for a long variable * r = dshift(long,shift[,mode]) >> Mode='L' logical right shift * >>> Mode='A' arithmetic right shift * << xhift<0 left shift ********************************************`*************************/ Parse Upper Arg n,s,o Numeric Digits 40 If o='' Then o='L' nx=d2x(n,16) nb=x2b(nx) If s<0 Then Do s=abs(s) rb=substr(nb,s+1)||copies('0',s) rx=b2x(rb) r=x2d(rx,16) End Else Do If o='L' Then Do rb=left(copies('0',s)nb,length(nb)) rx=b2x(rb) r=x2d(rx,16) End Else Do rb=left(copies(left(nb,1),s)nb,length(nb)) rx=b2x(rb) r=x2d(rx,16) End End Return r   ishift: Procedure /********************************************************************** * Implement the shift operations for an int variable * r = dshift(int,shift[,mode]) >> Mode='L' logical right shift * >>> Mode='A' arithmetic right shift * << xhift<0 left shift ********************************************`*************************/ Parse Upper Arg n,s,o Numeric Digits 40 If o='' Then o='L' nx=d2x(n,8) nb=x2b(nx) If s<0 Then Do s=abs(s) rb=substr(nb,s+1)||copies('0',s) rx=b2x(rb) r=x2d(rx,8) End Else Do If o='L' Then Do rb=left(copies('0',s)nb,length(nb)) rx=b2x(rb) r=x2d(rx,8) End Else Do rb=left(copies(left(nb,1),s)nb,length(nb)) rx=b2x(rb) r=x2d(rx,8) End End Return r   b2x: Procedure Expose x. /********************************************************************** * Convert a Bit string to a Hex stríng **********************************************************************/ Parse Arg b z='0'; bits.z='0000'; y=bits.z; x.y=z z='1'; bits.z='0001'; y=bits.z; x.y=z z='2'; bits.z='0010'; y=bits.z; x.y=z z='3'; bits.z='0011'; y=bits.z; x.y=z z='4'; bits.z='0100'; y=bits.z; x.y=z z='5'; bits.z='0101'; y=bits.z; x.y=z z='6'; bits.z='0110'; y=bits.z; x.y=z z='7'; bits.z='0111'; y=bits.z; x.y=z z='8'; bits.z='1000'; y=bits.z; x.y=z z='9'; bits.z='1001'; y=bits.z; x.y=z z='A'; bits.z='1010'; y=bits.z; x.y=z z='B'; bits.z='1011'; y=bits.z; x.y=z z='C'; bits.z='1100'; y=bits.z; x.y=z z='D'; bits.z='1101'; y=bits.z; x.y=z z='E'; bits.z='1110'; y=bits.z; x.y=z z='F'; bits.z='1111'; y=bits.z; x.y=z x='' Do While b<>'' Parse Var b b4 +4 b x=x||x.b4 End Return x   x2b: Procedure Expose bits. /*********************************************************************** * Convert a Hex string to a Bit stríng ***********************************************************************/ Parse Arg x z='0'; bits.z='0000'; y=bits.z; x.y=z z='1'; bits.z='0001'; y=bits.z; x.y=z z='2'; bits.z='0010'; y=bits.z; x.y=z z='3'; bits.z='0011'; y=bits.z; x.y=z z='4'; bits.z='0100'; y=bits.z; x.y=z z='5'; bits.z='0101'; y=bits.z; x.y=z z='6'; bits.z='0110'; y=bits.z; x.y=z z='7'; bits.z='0111'; y=bits.z; x.y=z z='8'; bits.z='1000'; y=bits.z; x.y=z z='9'; bits.z='1001'; y=bits.z; x.y=z z='A'; bits.z='1010'; y=bits.z; x.y=z z='B'; bits.z='1011'; y=bits.z; x.y=z z='C'; bits.z='1100'; y=bits.z; x.y=z z='D'; bits.z='1101'; y=bits.z; x.y=z z='E'; bits.z='1110'; y=bits.z; x.y=z z='F'; bits.z='1111'; y=bits.z; x.y=z b='' Do While x<>'' Parse Var x c +1 x b=b||bits.c End Return b
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.
#Lua
Lua
-- initialize local N = 2200 local ar = {} for i=1,N do ar[i] = false end   -- process for a=1,N do for b=a,N do if (a % 2 ~= 1) or (b % 2 ~= 1) then local aabb = a * a + b * b for c=b,N do local aabbcc = aabb + c * c local d = math.floor(math.sqrt(aabbcc)) if (aabbcc == d * d) and (d <= N) then ar[d] = true end end end end -- print('done with a='..a) end   -- print for i=1,N do if not ar[i] then io.write(i.." ") end end 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
#jq
jq
  # viewBox = <min-x> <min-y> <width> <height> # Input: {svg, minx, miny, maxx, maxy} def svg: "<svg viewBox='\(.minx - 4|floor) \(.miny - 4 |floor) \(6 + .maxx - .minx|ceil) \(6 + .maxy - .miny|ceil)'", " preserveAspectRatio='xMinYmin meet'", " xmlns='http://www.w3.org/2000/svg' >", .svg, "</svg>";   def minmax($xy): .minx = ([.minx, $xy[0]]|min) | .miny = ([.miny, $xy[1]]|min) | .maxx = ([.maxx, $xy[0]]|max) | .maxy = ([.maxy, $xy[1]]|max) ;   # default values for $fill and $stroke are provided def Polygon( $ary; $fill; $stroke): def rnd: 1000*.|round/1000; ($fill // "none") as $fill | ($stroke // "black") as $stroke | ($ary | map(rnd) | join(" ")) as $a | .svg += "\n<polygon points='\($a)' fill='\($fill)' stroke='\($stroke)' />" | minmax($ary | [ ([ .[ range(0;length;2)]] |min), ([ .[range(1;length;2)]]|min) ] ) | minmax($ary | [ ([ .[ range(0;length;2)]] |max), ([ .[range(1;length;2)]]|max) ] ) ;     def Square($A; $B; $C; $D; $fill; $stroke): Polygon( $A + $B + $C + $D; $fill; $stroke);   def Triangle($A; $B; $C; $fill; $stroke): Polygon( $A + $B + $C; $fill; $stroke);   def PythagorasTree:   def drawTree($x1; $y1; $x2; $y2; $depth): if $depth <= 0 then . else ($x2 - $x1) as $dx | ($y1 - $y2) as $dy | ($x2 - $dy) as $x3 | ($y2 - $dx) as $y3 | ($x1 - $dy) as $x4 | ($y1 - $dx) as $y4 | ($x4 + 0.5 * ($dx - $dy)) as $x5 | ($y4 - 0.5 * ($dx + $dy)) as $y5   # draw a square | "rgb(\(256 - $depth * 20), 0, 0)" as $col | Square([$x1, $y1]; [$x2, $y2]; [$x3, $y3] ; [$x4, $y4] ; $col; "lightgray")   # draw a triangle | "rgb( 128, \(256 - $depth * 20), 128)" as $col | Triangle([$x3, $y3]; [$x4, $y4]; [$x5, $y5]; $col; "lightgray") | drawTree($x4; $y4; $x5; $y5; $depth - 1) | drawTree($x5; $y5; $x3; $y3; $depth - 1) end ;   {svg: "", minx: infinite, miny: infinite, maxx: -infinite, maxy: -infinite} | drawTree(275; 500; 375; 500; 7);   PythagorasTree | svg  
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
#Julia
Julia
using Gadfly using DataFrames   const xarray = zeros(Float64, 80000) const yarray = zeros(Float64, 80000) const arraypos = ones(Int32,1) const maxdepth = zeros(Int32, 1)     function addpoints(x1, y1, x2, y2) xarray[arraypos[1]] = x1 xarray[arraypos[1]+1] = x2 yarray[arraypos[1]] = y1 yarray[arraypos[1]+1] = y2 arraypos[1] += 2 end     function pythtree(ax, ay, bx, by, depth) if(depth > maxdepth[1]) return end 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; addpoints(ax, ay, bx, by) addpoints(bx, by, x3, y3) addpoints(x3, y3, x4, y4) addpoints(x4, y4, ax, ay) pythtree(x4, y4, x5, y5, depth + 1) pythtree(x5, y5, x3, y3, depth + 1) end     function pythagorastree(x1, y1, x2, y2, size, maxdep) maxdepth[1] = maxdep println("Pythagoras Tree, depth $(maxdepth[1]), size $size, starts at ($x1, $y1, $x2, $y2)"); pythtree(x1, y1, x2, y2, 0); df = DataFrame(x=xarray[1:arraypos[1]-1], y=-yarray[1:arraypos[1]-1]) plot(df, x=:x, y=:y, Geom.path(), Theme(default_color="green", point_size=0.4mm)) end   pythagorastree(275.,500.,375.,500.,640., 9)
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes several fairly rigorous PRNG "fitness" tests that some more complex algorithms fail. Splitmix64 is not recommended for demanding random number requirements, but is often used to calculate initial states for other more complex pseudo-random number generators. The "standard" splitmix64 maintains one 64 bit state variable and returns 64 bits of random data with each call. Basic pseudocode algorithm: uint64 state /* The state can be seeded with any (upto) 64 bit integer value. */ next_int() { state += 0x9e3779b97f4a7c15 /* increment the state variable */ uint64 z = state /* copy the state to a working variable */ z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9 /* xor the variable with the variable right bit shifted 30 then multiply by a constant */ z = (z ^ (z >> 27)) * 0x94d049bb133111eb /* xor the variable with the variable right bit shifted 27 then multiply by a constant */ return z ^ (z >> 31) /* return the variable xored with itself right bit shifted 31 */ } next_float() { return next_int() / (1 << 64) /* divide by 2^64 to return a value between 0 and 1 */ } The returned value should hold 64 bits of numeric data. If your language does not support unsigned 64 bit integers directly you may need to apply appropriate bitmasks during bitwise operations. In keeping with the general layout of several recent pseudo-random number tasks: Task Write a class or set of functions that generates pseudo-random numbers using splitmix64. Show the first five integers generated using the seed 1234567. 6457827717110365317 3203168211198807973 9817491932198370423 4593380528125082431 16408922859458223821 Show that for an initial seed of 987654321, the counts of 100_000 repetitions of floor next_float() * 5 is as follows: 0: 20027, 1: 19892, 2: 20073, 3: 19978, 4: 20030 Show your output here, on this page. See also Java docs for splitmix64 Public domain C code used in many PRNG implementations; by Sebastiano Vigna Related tasks Pseudo-random numbers/Combined recursive generator MRG32k3a‎‎ Pseudo-random numbers/PCG32‎‎ Pseudo-random_numbers/Xorshift_star
#Wren
Wren
import "/big" for BigInt   var Const1 = BigInt.fromBaseString("9e3779b97f4a7c15", 16) var Const2 = BigInt.fromBaseString("bf58476d1ce4e5b9", 16) var Const3 = BigInt.fromBaseString("94d049bb133111eb", 16) var Mask64 = (BigInt.one << 64) - BigInt.one   class Splitmix64 { construct new(state) { _state = state }   nextInt { _state = (_state + Const1) & Mask64 var z = _state z = ((z ^ (z >> 30)) * Const2) & Mask64 z = ((z ^ (z >> 27)) * Const3) & Mask64 return (z ^ (z >> 31)) & Mask64 }   nextFloat { nextInt.toNum / 2.pow(64) } }   var randomGen = Splitmix64.new(BigInt.new(1234567)) for (i in 0..4) System.print(randomGen.nextInt)   var counts = List.filled(5, 0) randomGen = Splitmix64.new(BigInt.new(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_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
#AutoHotkey
AutoHotkey
#NoEnv SetBatchLines, -1 #SingleInstance, Force   ; Greatest common divisor, from http://rosettacode.org/wiki/Greatest_common_divisor#AutoHotkey gcd(a,b) { Return b=0 ? Abs(a) : Gcd(b,mod(a,b)) }   count_triples(max) { primitives := 0, triples := 0, m := 2 while m <= (max / 2)**0.5 { n := mod(m, 2) + 1 ,p := 2*m*(m + n) , delta := 4*m while n < m and p <= max gcd(m, n) = 1 ? (primitives++ , triples += max // p) : "" , n += 2 , p += delta m++ } Return primitives " primitives out of " triples " triples" }   Loop, 8 Msgbox % 10**A_Index ": " count_triples(10**A_Index)
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.
#PureBasic
PureBasic
s$="s$= : Debug Mid(s$,1,3)+Chr(34)+s$+Chr(34)+Mid(s$,4,100)" : Debug Mid(s$,1,3)+Chr(34)+s$+Chr(34)+Mid(s$,4,100)
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.
#Haskell
Haskell
import Data.List   randoms :: Int -> [Int] randoms seed = unfoldr go ([seed,0,0],[seed,0,0]) where go (x1,x2) = let x1i = sum (zipWith (*) x1 a1) `mod` m1 x2i = sum (zipWith (*) x2 a2) `mod` m2 in Just $ ((x1i - x2i) `mod` m1, (x1i:init x1, x2i:init x2))   a1 = [0, 1403580, -810728] m1 = 2^32 - 209 a2 = [527612, 0, -1370589] m2 = 2^32 - 22853   randomsFloat = map ((/ (2^32 - 208)) . fromIntegral) . randoms
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#Ruby
Ruby
class PCG32 MASK64 = (1 << 64) - 1 MASK32 = (1 << 32) - 1 CONST = 6364136223846793005   def seed(seed_state, seed_sequence) @state = 0 @inc = ((seed_sequence << 1) | 1) & MASK64 next_int @state = @state + seed_state next_int end   def next_int old = @state @state = ((old * CONST) + @inc) & MASK64 xorshifted = (((old >> 18) ^ old) >> 27) & MASK32 rot = (old >> 59) & MASK32 answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)) answer & MASK32 end   def next_float next_int.fdiv(1 << 32) end   end   random_gen = PCG32.new random_gen.seed(42, 54) 5.times{puts random_gen.next_int}   random_gen.seed(987654321, 1) p 100_000.times.each{(random_gen.next_float * 5).floor}.tally.sort.to_h  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
max = 2200; maxsq = max^2; d = Range[max]^2; Dynamic[{a, b, Length[d]}] Do[ Do[ c = Range[1, Floor[(maxsq - a^2 - b^2)^(1/2)]]; dposs = a^2 + b^2 + c^2; d = Complement[d, dposs] , {b, Floor[(maxsq - a^2)^(1/2)]} ] , {a, Floor[maxsq^(1/2)]} ] Sqrt[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.
#Modula-2
Modula-2
MODULE PythagoreanQuadruples; FROM FormatString IMPORT FormatString; FROM RealMath IMPORT sqrt; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteInteger(i : INTEGER); VAR buffer : ARRAY[0..16] OF CHAR; BEGIN FormatString("%i", buffer, i); WriteString(buffer) END WriteInteger;   (* Main *) CONST N = 2200; VAR r : ARRAY[0..N] OF BOOLEAN; a,b,c,d : INTEGER; aabb,aabbcc : INTEGER; BEGIN (* Initialize *) FOR a:=0 TO HIGH(r) DO r[a] := FALSE END;   (* Process *) FOR a:=1 TO N DO FOR b:=a TO N DO IF (a MOD 2 = 1) AND (b MOD 2 = 1) THEN (* For positive odd a and b, no solution *) CONTINUE END; aabb := a*a + b*b; FOR c:=b TO N DO aabbcc := aabb + c*c; d := INT(sqrt(FLOAT(aabbcc))); IF (aabbcc = d*d) AND (d <= N) THEN (* solution *) r[d] := TRUE END END END END;   FOR a:=1 TO N DO IF NOT r[a] THEN (* pritn non-solution *) WriteInteger(a); WriteString(" ") END END; WriteLn;   ReadChar END PythagoreanQuadruples.
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
#Kotlin
Kotlin
// version 1.1.2   import java.awt.* import java.awt.geom.Path2D import javax.swing.*   class PythagorasTree : JPanel() { val depthLimit = 7 val hue = 0.15f   init { preferredSize = Dimension(640, 640) background = Color.white }   private fun drawTree(g: Graphics2D, x1: Float, y1: Float, x2: Float, y2: Float, depth: Int) { if (depth == depthLimit) return   val dx = x2 - x1 val dy = y1 - y2   val x3 = x2 - dy val y3 = y2 - dx val x4 = x1 - dy val y4 = y1 - dx val x5 = x4 + 0.5f * (dx - dy) val y5 = y4 - 0.5f * (dx + dy)   val square = Path2D.Float() with (square) { moveTo(x1, y1) lineTo(x2, y2) lineTo(x3, y3) lineTo(x4, y4) closePath() }   g.color = Color.getHSBColor(hue + depth * 0.02f, 1.0f, 1.0f) g.fill(square) g.color = Color.lightGray g.draw(square)   val triangle = Path2D.Float() with (triangle) { moveTo(x3, y3) lineTo(x4, y4) lineTo(x5, y5) closePath() }   g.color = Color.getHSBColor(hue + depth * 0.035f, 1.0f, 1.0f) g.fill(triangle) g.color = Color.lightGray g.draw(triangle)   drawTree(g, x4, y4, x5, y5, depth + 1) drawTree(g, x5, y5, x3, y3, depth + 1) }   override fun paintComponent(g: Graphics) { super.paintComponent(g) drawTree(g as Graphics2D, 275.0f, 500.0f, 375.0f, 500.0f, 0) } }   fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() with (f) { defaultCloseOperation = JFrame.EXIT_ON_CLOSE title = "Pythagoras Tree" isResizable = false add(PythagorasTree(), BorderLayout.CENTER) pack() setLocationRelativeTo(null); setVisible(true) } } }
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
#AWK
AWK
  # syntax: GAWK -f PYTHAGOREAN_TRIPLES.AWK # converted from Go BEGIN { printf("%5s %11s %11s %11s %s\n","limit","limit","triples","primitives","seconds") for (max_peri=10; max_peri<=1E9; max_peri*=10) { t = systime() prim = 0 total = 0 new_tri(3,4,5) printf("10^%-2d %11d %11d %11d %d\n",++n,max_peri,total,prim,systime()-t) } exit(0) } function new_tri(s0,s1,s2, p) { p = s0 + s1 + s2 if (p <= max_peri) { prim++ total += int(max_peri / p) new_tri(+1*s0-2*s1+2*s2,+2*s0-1*s1+2*s2,+2*s0-2*s1+3*s2) new_tri(+1*s0+2*s1+2*s2,+2*s0+1*s1+2*s2,+2*s0+2*s1+3*s2) new_tri(-1*s0+2*s1+2*s2,-2*s0+1*s1+2*s2,-2*s0+2*s1+3*s2) } }  
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.
#Python
Python
w = "print('w = ' + chr(34) + w + chr(34) + chr(10) + w)" print('w = ' + chr(34) + w + chr(34) + chr(10) + w)
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.
#Java
Java
public class App { private static long mod(long x, long y) { long m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; }   public static class RNG { // first generator private final long[] a1 = {0, 1403580, -810728}; private static final long m1 = (1L << 32) - 209; private long[] x1; // second generator private final long[] a2 = {527612, 0, -1370589}; private static final long m2 = (1L << 32) - 22853; private long[] x2; // other private static final long d = m1 + 1;   public void seed(long state) { x1 = new long[]{state, 0, 0}; x2 = new long[]{state, 0, 0}; }   public long nextInt() { long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1); long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2); long z = mod(x1i - x2i, m1);   // keep the last three values of the first generator x1 = new long[]{x1i, x1[0], x1[1]}; // keep the last three values of the second generator x2 = new long[]{x2i, x2[0], x2[1]};   return z + 1; }   public double nextFloat() { return 1.0 * nextInt() / d; } }   public static void main(String[] args) { RNG rng = new RNG();   rng.seed(1234567); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println();   int[] counts = {0, 0, 0, 0, 0}; rng.seed(987654321); for (int i = 0; i < 100_000; i++) { int value = (int) Math.floor(rng.nextFloat() * 5.0); counts[value]++; } for (int i = 0; i < counts.length; i++) { System.out.printf("%d: %d%n", i, counts[i]); } } }
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#Scheme
Scheme
(import (scheme small) (srfi 33))   (define PCG-DEFAULT-MULTIPLIER 6364136223846793005) (define MASK64 (- (arithmetic-shift 1 64) 1)) (define MASK32 (- (arithmetic-shift 1 32) 1))   (define-record-type <pcg32-random> (make-pcg32-random-record) pcg32? (state pcg32-state pcg32-state!) (inc pcg32-inc pcg32-inc!))   (define (make-pcg32) (define rng (make-pcg32-random-record)) (pcg32-seed rng 31415926 535897932) rng)   (define (pcg32-seed rng init-state init-seq) (pcg32-state! rng 0) (pcg32-inc! rng (bitwise-and (bitwise-ior (arithmetic-shift init-seq 1) 1) MASK64)) (pcg32-next-int rng) (pcg32-state! rng (bitwise-and (+ (pcg32-state rng) init-state) MASK64)) (pcg32-next-int rng))   (define (pcg32-next-int rng) (define xorshifted 0) (define rot 0) (define answer 0) (define oldstate (pcg32-state rng)) (pcg32-state! rng (bitwise-and (+ (* oldstate PCG-DEFAULT-MULTIPLIER) (pcg32-inc rng)) MASK64)) (set! xorshifted (bitwise-xor (arithmetic-shift oldstate -18) oldstate)) (set! xorshifted (arithmetic-shift xorshifted -27)) (set! xorshifted (bitwise-and xorshifted MASK32)) (set! rot (bitwise-and (arithmetic-shift oldstate -59) MASK32)) (set! answer (bitwise-ior (arithmetic-shift xorshifted (- rot)) (arithmetic-shift xorshifted (bitwise-and (- rot) 31)))) (set! answer (bitwise-and answer MASK32)) answer)   (define (pcg32-next-float rng) (inexact (/ (pcg32-next-int rng) (arithmetic-shift 1 32))))   ;; task   (define rng (make-pcg32)) (pcg32-seed rng 42 54) (let lp ((i 0)) (when (< i 5) (display (pcg32-next-int rng))(newline) (lp (+ i 1)))) (newline)   (pcg32-seed rng 987654321 1) (define vec (make-vector 5 0)) (let lp ((i 0)) (when (< i 100000) (let ((j (exact (floor (* (pcg32-next-float rng) 5))))) (vector-set! vec j (+ (vector-ref vec j) 1))) (lp (+ i 1)))) (let lp ((i 0)) (when (< i 5) (display i) (display " : ") (display (vector-ref vec i)) (newline) (lp (+ i 1))))  
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.
#Nim
Nim
import math   const N = 2_200   template isOdd(n: int): bool = (n and 1) != 0   var r = newSeq[bool](N + 1)   for a in 1..N: for b in a..N: if a.isOdd and b.isOdd: continue let aabb = a * a + b * b for c in b..N: let aabbcc = aabb + c * c d = sqrt(aabbcc.float).int if aabbcc == d * d and d <= N: r[d] = true   for i in 1..N: if not r[I]: stdout.write i, " " echo()
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.
#Pascal
Pascal
program pythQuad; //find phythagorean Quadrupel up to a,b,c,d <= 2200 //a^2 + b^2 +c^2 = d^2 //find all values of d which are not possible //brute force //split in two procedure to reduce register pressure for CPU32   const MaxFactor =2200; limit = MaxFactor*MaxFactor; type tIdx = NativeUint; tSum = NativeUint;   var check : array[0..MaxFactor] of boolean; checkCnt : LongWord;   procedure Find2(s:tSum;idx:tSum); //second sum (a*a+b*b) +c*c =?= d*d var s1 : tSum; d : tSum; begin d := trunc(sqrt(s+idx*idx));// calculate first sqrt For idx := idx to MaxFactor do Begin s1 := s+idx*idx; If s1 <= limit then Begin while s1 > d*d do //adjust sqrt inc(d); inc(checkCnt); IF s1=d*d then check[d] := true; end else Break; end; end;   procedure Find1; //first sum a*a+b*b var a,b : tIdx; s : tSum; begin For a := 1 to MaxFactor do For b := a to MaxFactor do Begin s := a*a+b*b; if s < limit then Find1(s,b) else break; end; end;   var i : NativeUint; begin Find1;   For i := 1 to MaxFactor do If Not(Check[i]) then write(i,' '); writeln; writeln(CheckCnt,' checks were done'); 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
#M2000_Interpreter
M2000 Interpreter
  MODULE Pythagoras_tree { CLS 5, 0 ' MAGENTA, NO SPLIT SCREEN PEN 14 ' YELLOW \\ code from zkl/Free Basic LET w = scale.x, h = w * 11 div 16 LET w2 = w div 2, diff = w div 12 LET TreeOrder = 6 pythagoras_tree(w2 - diff, h -10, w2 + diff, h -10, 0)   SUB pythagoras_tree(x1, y1, x2, y2, depth)   IF depth > TreeOrder THEN EXIT SUB   LOCAL dx = x2 - x1, dy = y1 - y2 LOCAL x3 = x2 - dy, y3 = y2 - dx LOCAL x4 = x1 - dy, y4 = y1 - dx LOCAL x5 = x4 + (dx - dy) / 2 LOCAL y5 = y4 - (dx + dy) / 2 MOVE x1, y1 DRAW TO x2, y2 DRAW TO x3, y3 DRAW TO x4, y4 DRAW TO x1, y1 pythagoras_tree(x4, y4, x5, y5, depth +1) pythagoras_tree(x5, y5, x3, y3, depth +1)   END SUB } Pythagoras_tree  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
n = 7; colors = Blend[{Orange, Yellow, Green}, #] & /@ Subdivide[n - 1]; ClearAll[NextConfigs, NewConfig] NewConfig[b1_List, b2_List] := Module[{diff, perp}, diff = b2 - b1; perp = Cross[b2 - b1]; <|"quad" -> Polygon[{b1, b2, b2 + perp, b1 + perp}], "triang" -> Polygon[{b1 + 1.5 perp + diff/2, b1 + perp, b2 + perp}]|> ] NextConfigs[config_Association] := Module[{tr}, tr = config["triangs"][[All, 1]]; tr = Join[NewConfig @@@ tr[[All, {2, 1}]], NewConfig @@@ tr[[All, {1, 3}]]]; <|"quads" -> tr[[All, "quad"]], "triangs" -> tr[[All, "triang"]]|> ] nc = NewConfig[{-0.5, 0.0}, {0.5, 0.0}]; config = <|"quads" -> {nc["quad"]}, "triangs" -> {nc["triang"]}|>; config = NestList[NextConfigs, config, n - 1]; Graphics[MapThread[{EdgeForm[Black], FaceForm[#2], #1["quads"], #1["triangs"]} &, {config, colors}]]
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
#BBC_BASIC
BBC BASIC
DIM U0%(2,2), U1%(2,2), U2%(2,2), seed%(2) U0%() = 1, -2, 2, 2, -1, 2, 2, -2, 3 U1%() = 1, 2, 2, 2, 1, 2, 2, 2, 3 U2%() = -1, 2, 2, -2, 1, 2, -2, 2, 3   seed%() = 3, 4, 5 FOR power% = 1 TO 7 all% = 0 : prim% = 0 PROCtri(seed%(), 10^power%, all%, prim%) PRINT "Up to 10^"; power%, ": " all% " triples" prim% " primitives" NEXT END   DEF PROCtri(i%(), mp%, RETURN all%, RETURN prim%) LOCAL t%() : DIM t%(2)   IF SUM(i%()) > mp% ENDPROC prim% += 1 all% += mp% DIV SUM(i%())   t%() = U0%() . i%() PROCtri(t%(), mp%, all%, prim%) t%() = U1%() . i%() PROCtri(t%(), mp%, all%, prim%) t%() = U2%() . i%() PROCtri(t%(), mp%, all%, prim%) ENDPROC
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.
#Quackery
Quackery
[ ' [ ' unbuild dup 4 split rot space rot 3 times join echo$ ] unbuild dup 4 split rot space rot 3 times join echo$ ]
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.
#R
R
(function(){x<-intToUtf8(34);s<-"(function(){x<-intToUtf8(34);s<-%s%s%s;cat(sprintf(s,x,s,x))})()";cat(sprintf(s,x,s,x))})()
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.
#Julia
Julia
const a1 = [0, 1403580, -810728] const m1 = 2^32 - 209 const a2 = [527612, 0, -1370589] const m2 = 2^32 - 22853 const d = m1 + 1   mutable struct MRG32k3a x1::Tuple{Int64, Int64, Int64} x2::Tuple{Int64, Int64, Int64} MRG32k3a() = new((0, 0, 0), (0, 0, 0)) MRG32k3a(seed_state) = new((seed_state, 0, 0), (seed_state, 0, 0)) end seed(sd) = begin @assert(0 < sd < d); MRG32k3a(sd) end   function next_int(x::MRG32k3a) x1i = mod1(a1[1] * x.x1[1] + a1[2] * x.x1[2] + a1[3] * x.x1[3], m1) x2i = mod1(a2[1] * x.x2[1] + a2[2] * x.x2[2] + a2[3] * x.x2[3], m2) x.x1 = (x1i, x.x1[1], x.x1[2]) x.x2 = (x2i, x.x2[1], x.x2[2]) return mod1(x1i - x2i, m1) + 1 end   next_float(x::MRG32k3a) = next_int(x) / d   const g1 = seed(1234567) for _ in 1:5 println(next_int(g1)) end const g2 = seed(987654321) hist = fill(0, 5) for _ in 1:100_000 hist[Int(floor(next_float(g2) * 5)) + 1] += 1 end foreach(p -> print(p[1], ": ", p[2], " "), enumerate(hist))  
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.
#Kotlin
Kotlin
import kotlin.math.floor   fun mod(x: Long, y: Long): Long { val m = x % y return if (m < 0) { if (y < 0) { m - y } else { m + y } } else m }   class RNG { // first generator private val a1 = arrayOf(0L, 1403580L, -810728L) private val m1 = (1L shl 32) - 209 private var x1 = arrayOf(0L, 0L, 0L)   // second generator private val a2 = arrayOf(527612L, 0L, -1370589L) private val m2 = (1L shl 32) - 22853 private var x2 = arrayOf(0L, 0L, 0L)   private val d = m1 + 1   fun seed(state: Long) { x1 = arrayOf(state, 0, 0) x2 = arrayOf(state, 0, 0) }   fun nextInt(): Long { val x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1) val x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2) val z = mod(x1i - x2i, m1)   // keep last three values of the first generator x1 = arrayOf(x1i, x1[0], x1[1]) // keep last three values of the second generator x2 = arrayOf(x2i, x2[0], x2[1])   return z + 1 }   fun nextFloat(): Double { return nextInt().toDouble() / d } }   fun main() { val rng = RNG()   rng.seed(1234567) println(rng.nextInt()) println(rng.nextInt()) println(rng.nextInt()) println(rng.nextInt()) println(rng.nextInt()) println()   val counts = IntArray(5) rng.seed(987654321) for (i in 0 until 100_000) { val v = floor((rng.nextFloat() * 5.0)).toInt() counts[v]++ } for (iv in counts.withIndex()) { println("${iv.index}: ${iv.value}") } }
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#Sidef
Sidef
class PCG32(seed, incr) {   has state   define ( mask32 = (2**32 - 1), mask64 = (2**64 - 1), N = 6364136223846793005, )   method init { seed := 1 incr := 2 incr = (((incr << 1) | 1) & mask64) state = (((incr + seed)*N + incr) & mask64) }   method next_int { var shift = ((((state >> 18) ^ state) >> 27) & mask32) var rotate = ((state >> 59) & mask32) state = ((state*N + incr) & mask64) ((shift >> rotate) | (shift << (32-rotate))) & mask32 }   method next_float { self.next_int / (mask32+1) } }   say "Seed: 42, Increment: 54, first 5 values:"; var rng = PCG32(seed: 42, incr: 54) say 5.of { rng.next_int }   say "\nSeed: 987654321, Increment: 1, values histogram:"; var rng = PCG32(seed: 987654321, incr: 1) var histogram = Bag(1e5.of { floor(5*rng.next_float) }...) histogram.pairs.sort.each { .join(": ").say }
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.
#Perl
Perl
my $N = 2200; push @sq, $_**2 for 0 .. $N; my @not = (0) x $N; @not[0] = 1;     for my $d (1 .. $N) { my $last = 0; for my $a (reverse ceiling($d/3) .. $d) { for my $b (1 .. ceiling($a/2)) { my $ab = $sq[$a] + $sq[$b]; last if $ab > $sq[$d]; my $x = sqrt($sq[$d] - $ab); if ($x == int $x) { $not[$d] = 1; $last = 1; last } } last if $last; } }   sub ceiling { int $_[0] + 1 - 1e-15 }   for (0 .. $#not) { $result .= "$_ " unless $not[$_] } print "$result\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
#Nim
Nim
import imageman   const Width = 1920 Height = 1080 MaxDepth = 10 Color = ColorRGBU([byte 0, 255, 0])     proc drawTree(img: var Image; x1, y1, x2, y2: int; depth: Natural) =   if depth == 0: return   let dx = x2 - x1 dy = y1 - y2 x3 = x2 - dy y3 = y2 - dx x4 = x1 - dy y4 = y1 - dx x5 = x4 + (dx - dy) div 2 y5 = y4 - (dx + dy) div 2   # Draw square. img.drawPolyline(true, Color, (x1, y1), (x2, y2), (x3, y3), (x4, y4))   # Draw triangle. img.drawPolyline(true, Color, (x3, y3), (x4, y4), (x5, y5))   # Next level. img.drawTree(x4, y4, x5, y5, depth - 1) img.drawTree(x5, y5, x3, y3, depth - 1)     var image = initImage[ColorRGBU](Width, Height) image.drawTree(int(Width / 2.3), Height - 1, int(Width / 1.8), Height - 1, MaxDepth) image.savePNG("pythagoras_tree.png", compression = 9)
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
#Bracmat
Bracmat
(pythagoreanTriples= total prim max-peri U . (.(1,-2,2) (2,-1,2) (2,-2,3)) (.(1,2,2) (2,1,2) (2,2,3)) (.(-1,2,2) (-2,1,2) (-2,2,3))  : ?U & ( new-tri = i t p Urows Urow Ucols , a b c loop A B C .  !arg:(,?a,?b,?c) & !a+!b+!c:~>!max-peri:?p & 1+!prim:?prim & div$(!max-peri.!p)+!total:?total & !U:?Urows & ( loop =  !Urows:(.?Urow) ?Urows & !Urow:?Ucols & :?t & whl ' ( !Ucols:(?A,?B,?C) ?Ucols & (!t,!a*!A+!b*!B+!c*!C):?t ) & new-tri$!t & !loop ) & !loop | ) & ( Main = seed . (,3,4,5):?seed & 10:?max-peri & whl ' ( 0:?total:?prim & new-tri$!seed & out $ ( str $ ( "Up to "  !max-peri ": "  !total " triples, "  !prim " primitives." ) ) & !max-peri*10:~>10000000:?max-peri ) ) & Main$ );   pythagoreanTriples$;  
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.
#Racket
Racket
((λ (x) `(,x ',x)) '(λ (x) `(,x ',x)))
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.
#Nim
Nim
import algorithm, math, sequtils, strutils, tables   const # First generator. a1 = [int64 0, 1403580, -810728] m1: int64 = 2^32 - 209 # Second generator. a2 = [int64 527612, 0, -1370589] m2: int64 = 2^32 - 22853   d = m1 + 1   type MRG32k3a = object x1: array[3, int64] # List of three last values of gen #1. x2: array[3, int64] # List of three last values of gen #2.     func seed(gen: var MRG32k3a; seedState: int64) = assert seedState in 1..<d gen.x1 = [seedState, 0, 0] gen.x2 = [seedState, 0, 0]   func nextInt(gen: var MRG32k3a): int64 = let x1i = floormod(a1[0] * gen.x1[0] + a1[1] * gen.x1[1] + a1[2] * gen.x1[2], m1) let x2i = floormod(a2[0] * gen.x2[0] + a2[1] * gen.x2[1] + a2[2] * gen.x2[2], m2) # In version 1.4, the following two lines doesn't work. # gen.x1 = [x1i, gen.x1[0], gen.x1[1]] # Keep last three. # gen.x2 = [x2i, gen.x2[0], gen.x2[1]] # Keep last three. gen.x1[2] = gen.x1[1]; gen.x1[1] = gen.x1[0]; gen.x1[0] = x1i gen.x2[2] = gen.x2[1]; gen.x2[1] = gen.x2[0]; gen.x2[0] = x2i result = floormod(x1i - x2i, m1) + 1   func nextFloat(gen: var MRG32k3a): float = gen.nextInt().float / d.float   when isMainModule: var gen: MRG32k3a   gen.seed(1234567) for _ in 1..5: echo gen.nextInt()   echo "" gen.seed(987654321) var counts: CountTable[int] for _ in 1..100_000: counts.inc int(gen.nextFloat() * 5) echo sorted(toSeq(counts.pairs)).mapIt($it[0] & ": " & $it[1]).join(", ")
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.
#Pari.2FGP
Pari/GP
a1 = [0, 1403580, -810728]; m1 = 2^32-209; a2 = [527612, 0, -1370589]; m2 = 2^32-22853; d = m1+1; seed(s)=x1=x2=[s,0,0]; next_int()= { my(x1i=a1*x1~%m1, x2i=a2*x2~%m2); x1 = [x1i, x1[1], x1[2]]; x2 = [x2i, x2[1], x2[2]]; (x1i-x2i)%m1 + 1; } next_float()=next_int()/d;   seed(1234567); vector(5,i,next_int()) seed(987654321); v=vector(5); for(i=1,1e5, v[next_float()*5\1+1]++); v
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#Standard_ML
Standard ML
type pcg32 = LargeWord.word * LargeWord.word   local infix 5 >> val op >> = LargeWord.>> and m = 0w6364136223846793005 : LargeWord.word and rotate32 = fn a as (x, n) => Word32.orb (Word32.>> a, Word32.<< (x, Word.andb (~ n, 0w31))) in fun pcg32Init (seed, seq) : pcg32 = let val inc = LargeWord.<< (LargeWord.fromInt seq, 0w1) + 0w1 in ((LargeWord.fromInt seed + inc) * m + inc, inc) end fun pcg32Random ((state, inc) : pcg32) : Word32.word * pcg32 = ( rotate32 ( Word32.xorb ( Word32.fromLarge (state >> 0w27), Word32.fromLarge (state >> 0w45)), Word.fromLarge (state >> 0w59)), (state * m + inc, inc)) end
http://rosettacode.org/wiki/Pseudo-random_numbers/PCG32
Pseudo-random numbers/PCG32
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or right, with zero bits shifted in where appropriate. Examples are shown for 8 bit binary numbers; most significant bit to the left. << Logical shift left by given number of bits. E.g Binary 00110101 << 2 == Binary 11010100 >> Logical shift right by given number of bits. E.g Binary 00110101 >> 2 == Binary 00001101 ^ Bitwise exclusive-or operator https://en.wikipedia.org/wiki/Exclusive_or Bitwise comparison for if bits differ E.g Binary 00110101 ^ Binary 00110011 == Binary 00000110 | Bitwise or operator https://en.wikipedia.org/wiki/Bitwise_operation#OR Bitwise comparison gives 1 if any of corresponding bits are 1 E.g Binary 00110101 | Binary 00110011 == Binary 00110111 PCG32 Generator (pseudo-code) PCG32 has two unsigned 64-bit integers of internal state: state: All 2**64 values may be attained. sequence: Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 different sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. Task Generate a class/set of functions that generates pseudo-random numbers using the above. Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 Show your output here, on this page.
#Wren
Wren
import "/big" for BigInt   var Const = BigInt.new("6364136223846793005") var Mask64 = (BigInt.one << 64) - BigInt.one var Mask32 = (BigInt.one << 32) - BigInt.one   class Pcg32 { construct new() { _state = BigInt.fromBaseString("853c49e6748fea9b", 16) _inc = BigInt.fromBaseString("da3e39cb94b95bdb", 16) }   seed(seedState, seedSequence) { _state = BigInt.zero _inc = ((seedSequence << BigInt.one) | BigInt.one) & Mask64 nextInt _state = _state + seedState nextInt }   nextInt { var old = _state _state = (old*Const + _inc) & Mask64 var xorshifted = (((old >> 18) ^ old) >> 27) & Mask32 var rot = (old >> 59) & Mask32 return ((xorshifted >> rot) | (xorshifted << ((-rot) & 31))) & Mask32 }   nextFloat { nextInt.toNum / 2.pow(32) } }   var randomGen = Pcg32.new() randomGen.seed(BigInt.new(42), BigInt.new(54)) for (i in 0..4) System.print(randomGen.nextInt)   var counts = List.filled(5, 0) randomGen.seed(BigInt.new(987654321), BigInt.one) 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.
#Phix
Phix
with javascript_semantics constant N = 2200, N2 = N*N*2 sequence found = repeat(false,N), squares = repeat(false,N2) -- first mark all numbers that can be the sum of two squares for a=1 to N do integer a2 = a*a for b=a to N do squares[a2+b*b] = true end for end for -- now find all d such that d^2 - c^2 is in squares for d=1 to N do integer d2 = d*d for c=1 to d-1 do if squares[d2-c*c] then found[d] = true exit end if end for end for sequence res = {} for i=1 to N do if not found[i] then res &= i end if end for pp(res)
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
#Ol
Ol
  (import (lib gl)) (import (OpenGL version-1-0)) (gl:set-window-size 700 600) (gl:set-window-title "http://rosettacode.org/wiki/Pythagoras_tree")   (glLineWidth 2) (gl:set-renderer (lambda (mouse) (glClear GL_COLOR_BUFFER_BIT) (glLoadIdentity) (glOrtho -3 4 -1 5 0 1)   (let loop ((a '(0 . 0)) (b '(1 . 0)) (n 7)) (unless (zero? n) (define dx (- (car b) (car a))) (define dy (- (cdr b) (cdr a))) (define c (cons (- (car b) dy) (+ (cdr b) dx))) (define d (cons (- (car a) dy) (+ (cdr a) dx))) (define e (cons (- (/ (+ (car c) (car d)) 2) (/ dy 2)) (+ (/ (+ (cdr c) (cdr d)) 2) (/ dx 2))))   (glColor3f 0 (+ 1/3 (/ 2/3 n)) 0) (glBegin GL_QUADS) (glVertex2f (car a) (cdr a)) (glVertex2f (car b) (cdr b)) (glVertex2f (car c) (cdr c)) (glVertex2f (car d) (cdr d)) (glEnd) (glColor3f 1 0 0) (glBegin GL_TRIANGLES) (glVertex2f (car c) (cdr c)) (glVertex2f (car e) (cdr e)) (glVertex2f (car d) (cdr d)) (glEnd) (loop d e (- n 1)) (loop e c (- n 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
#C
C
#include <stdio.h> #include <stdlib.h>   typedef unsigned long long xint; typedef unsigned long ulong;   inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; }   int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc;   for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); /* show that we are working */ fflush(stdout);   /* max_p/2: valid limit, because one side of triangle * must be less than the sum of the other two */ for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break;   if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } }   printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim);   return 0; }
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.
#Raku
Raku
my &f = {say $^s, $^s.raku;}; f "my \&f = \{say \$^s, \$^s.raku;}; f "  
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.
#Perl
Perl
use strict; use warnings; use feature 'say';   package MRG32k3a {   use constant { m1 => 2**32 - 209, m2 => 2**32 - 22853 };   use Const::Fast; const my @a1 => < 0 1403580 -810728>; const my @a2 => <527612 0 -1370589>;   sub new { my ($class,undef,$seed) = @_; my @x1 = my @x2 = ($seed, 0, 0); bless {x1 => \@x1, x2 => \@x2}, $class; }   sub next_int { my ($self) = @_; unshift @{$$self{x1}}, ($a1[0] * $$self{x1}[0] + $a1[1] * $$self{x1}[1] + $a1[2] * $$self{x1}[2]) % m1; pop @{$$self{x1}}; unshift @{$$self{x2}}, ($a2[0] * $$self{x2}[0] + $a2[1] * $$self{x2}[1] + $a2[2] * $$self{x2}[2]) % m2; pop @{$$self{x2}}; ($$self{x1}[0] - $$self{x2}[0]) % (m1 + 1) }   sub next_float { $_[0]->next_int / (m1 + 1) } }   say 'Seed: 1234567, first 5 values:'; my $rng = MRG32k3a->new( seed => 1234567 ); say $rng->next_int for 1..5;   my %h; say "\nSeed: 987654321, values histogram:"; $rng = MRG32k3a->new( seed => 987654321 ); $h{int 5 * $rng->next_float}++ for 1..100_000; say "$_ $h{$_}" for sort keys %h;
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.
#PicoLisp
PicoLisp
(de quadruples (N) (let (AB NIL S 3 R) (for A N (for (B A (>= N B) (inc B)) (idx 'AB (+ (* A A) (* B B)) T ) ) ) (for C N (let (S1 S S2) (inc 'S 2) (setq S2 S) (for (D (+ C 1) (>= N D) (inc D)) (and (idx 'AB S1) (idx 'R D T)) (inc 'S1 S2) (inc 'S2 2) ) ) ) (make (for A N (or (idx 'R A) (link A)) ) ) ) )   (println (quadruples 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.
#PureBasic
PureBasic
OpenConsole() limite.i = 2200 s.i = 3 Dim l.i(limite) Dim ladd.i(limite * limite * 2)   For x.i = 1 To limite x2.i = x * x For y = x To limite ladd(x2 + y * y) = 1 Next y Next x   For x.i = 1 To limite s1.i = s s.i + 2 s2.i = s For y = x +1 To limite If ladd(s1) = 1 l(y) = 1 EndIf s1 + s2 s2 + 2 Next y Next x   For x.i = 1 To limite If l(x) = 0 Print(Str(x) + " ") EndIf Next x Input() CloseConsole()
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
#PARI.2FGP
PARI/GP
\\ Pythagoras Tree (w/recursion) \\ 4/11/16 aev plotline(x1,y1,x2,y2)={plotmove(0, x1,y1);plotrline(0,x2-x1,y2-y1);}   pythtree(ax,ay,bx,by,d=0)={ my(dx,dy,x3,y3,x4,y4,x5,y5); if(d>10, return()); 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; plotline(ax,ay,bx,by); plotline(bx,by,x3,y3); plotline(x3,y3,x4,y4); plotline(x4,y4,ax,ay); pythtree(x4,y4,x5,y5,d+1); pythtree(x5,y5,x3,y3,d+1); }   PythagorTree(x1,y1,x2,y2,depth=9,size)={ my(dx=1,dy=0,ttlb="Pythagoras Tree, depth ",ttl=Str(ttlb,depth)); print1(" *** ",ttl); print(", size ",size); print(" *** Start: ",x1,",",y1,",",x2,",",y2); plotinit(0); plotcolor(0,6); \\green plotscale(0, -size,size, size,0 ); plotmove(0, 0,0); pythtree(x1,y1, x2,y2); plotdraw([0,size,size]); }   {\\ Executing: PythagorTree(275,500,375,500,9,640); \\PythTree1.png }
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}}
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays; with Ada.Numerics.Generic_Elementary_Functions; procedure QR is   procedure Show (mat : Real_Matrix) is package FIO is new Ada.Text_IO.Float_IO (Float); begin for row in mat'Range (1) loop for col in mat'Range (2) loop FIO.Put (mat (row, col), Exp => 0, Aft => 4, Fore => 5); end loop; New_Line; end loop; end Show;   function GetCol (mat : Real_Matrix; n : Integer) return Real_Matrix is column : Real_Matrix (mat'Range (1), 1 .. 1); begin for row in mat'Range (1) loop column (row, 1) := mat (row, n); end loop; return column; end GetCol;   function Mag (mat : Real_Matrix) return Float is sum : Real_Matrix := Transpose (mat) * mat; package Math is new Ada.Numerics.Generic_Elementary_Functions (Float); begin return Math.Sqrt (sum (1, 1)); end Mag;   function eVect (col : Real_Matrix; n : Integer) return Real_Matrix is vect : Real_Matrix (col'Range (1), 1 .. 1); begin for row in col'Range (1) loop if row /= n then vect (row, 1) := 0.0; else vect (row, 1) := 1.0; end if; end loop; return vect; end eVect;   function Identity (n : Integer) return Real_Matrix is mat : Real_Matrix (1 .. n, 1 .. n) := (1 .. n => (others => 0.0)); begin for i in Integer range 1 .. n loop mat (i, i) := 1.0; end loop; return mat; end Identity;   function Chop (mat : Real_Matrix; n : Integer) return Real_Matrix is small : Real_Matrix (n .. mat'Length (1), n .. mat'Length (2)); begin for row in small'Range (1) loop for col in small'Range (2) loop small (row, col) := mat (row, col); end loop; end loop; return small; end Chop;   function H_n (inmat : Real_Matrix; n : Integer) return Real_Matrix is mat : Real_Matrix := Chop (inmat, n); col : Real_Matrix := GetCol (mat, n); colT : Real_Matrix (1 .. 1, mat'Range (1)); H : Real_Matrix := Identity (mat'Length (1)); Hall : Real_Matrix := Identity (inmat'Length (1)); begin col := col - Mag (col) * eVect (col, n); col := col / Mag (col); colT := Transpose (col); H := H - 2.0 * (col * colT); for row in H'Range (1) loop for col in H'Range (2) loop Hall (n - 1 + row, n - 1 + col) := H (row, col); end loop; end loop; return Hall; end H_n;   A : constant Real_Matrix (1 .. 3, 1 .. 3) := ( (12.0, -51.0, 4.0), (6.0, 167.0, -68.0), (-4.0, 24.0, -41.0)); Q1, Q2, Q3, Q, R: Real_Matrix (1 .. 3, 1 .. 3); begin Q1 := H_n (A, 1); Q2 := H_n (Q1 * A, 2); Q3 := H_n (Q2 * Q1* A, 3); Q := Transpose (Q1) * Transpose (Q2) * TransPose(Q3); R := Q3 * Q2 * Q1 * A; Put_Line ("Q:"); Show (Q); Put_Line ("R:"); Show (R); end QR;
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
#C.2B.2B
C++
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector>   using namespace std;   auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; }   // The formulas below will generate primitive triples if: // 0 < n < m // m and n are relatively prime (gcd == 1) // m + n is odd   auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } }   return tuple(totalCount, primitveCount); }     int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; // This last one takes almost a minute for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << 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.
#REBOL
REBOL
rebol [] q: [print ["rebol [] q:" mold q "do q"]] do q
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.
#Phix
Phix
with javascript_semantics constant -- First generator a1 = {0, 1403580, -810728}, m1 = power(2,32) - 209, -- Second Generator a2 = {527612, 0, -1370589}, m2 = power(2,32) - 22853, d = m1 + 1 sequence x1 = {0, 0, 0}, /* list of three last values of gen #1 */ x2 = {0, 0, 0} /* list of three last values of gen #2 */ procedure seed(integer seed_state) assert(seed_state>0 and seed_state<d) x1 = {seed_state, 0, 0} x2 = {seed_state, 0, 0} end procedure function next_int() atom x1i = mod(a1[1]*x1[1] + a1[2]*x1[2] + a1[3]*x1[3],m1), x2i = mod(a2[1]*x2[1] + a2[2]*x2[2] + a2[3]*x2[3],m2) x1 = {x1i, x1[1], x1[2]} /* Keep last three */ x2 = {x2i, x2[1], x2[2]} /* Keep last three */ atom z = mod(x1i-x2i,m1), answer = (z + 1) return answer end function function next_float() return next_int() / d end function seed(1234567) for i=1 to 5 do printf(1,"%d\n",next_int()) end for seed(987654321) sequence r = repeat(0,5) for i=1 to 100_000 do integer rdx = floor(next_float()*5)+1 r[rdx] += 1 end for ?r
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.
#Python
Python
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: r[d] = True s1 += s2 s2 += 2 return [i for i, val in enumerate(r) if not val and i]   if __name__ == '__main__': n = 2200 print(f"Those values of d in 1..{n} that can't be represented: {quad(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
#Perl
Perl
use Imager;   sub tree { my ($img, $x1, $y1, $x2, $y2, $depth) = @_;   return () if $depth <= 0;   my $dx = ($x2 - $x1); my $dy = ($y1 - $y2);   my $x3 = ($x2 - $dy); my $y3 = ($y2 - $dx); my $x4 = ($x1 - $dy); my $y4 = ($y1 - $dx); my $x5 = ($x4 + 0.5 * ($dx - $dy)); my $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); }   my ($width, $height) = (1920, 1080); my $img = 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/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}}
#Axiom
Axiom
)abbrev package TESTP TestPackage TestPackage(R:Join(Field,RadicalCategory)): with unitVector: NonNegativeInteger -> Vector(R) "/": (Vector(R),R) -> Vector(R) "^": (Vector(R),NonNegativeInteger) -> Vector(R) solveUpperTriangular: (Matrix(R),Vector(R)) -> Vector(R) signValue: R -> R householder: Vector(R) -> Matrix(R) qr: Matrix(R) -> Record(q:Matrix(R),r:Matrix(R)) lsqr: (Matrix(R),Vector(R)) -> Vector(R) polyfit: (Vector(R),Vector(R),NonNegativeInteger) -> Vector(R) == add unitVector(dim) == out := new(dim,0@R)$Vector(R) out(1) := 1@R out v:Vector(R) / a:R == map((vi:R):R +-> vi/a, v)$Vector(R) v:Vector(R) ^ n:NonNegativeInteger == map((vi:R):R +-> vi^n, v)$Vector(R) solveUpperTriangular(r,b) == n := ncols r x := new(n,0@R)$Vector(R) for k in n..1 by -1 repeat index := min(n,k+1) x(k) := (b(k)-reduce("+",subMatrix(r,k,k,index,n)*x.(index..n)))/r(k,k) x signValue(r) == R has (sign: R -> Integer) => coerce(sign(r)$R)$R zero? r => r if sqrt(r*r) = r then 1 else -1 householder(a) == m := #a u := a + length(a)*signValue(a(1))*unitVector(m) v := u/u(1) beta := (1+1)/dot(v,v) scalarMatrix(m,1) - beta*transpose(outerProduct(v,v)) qr(a) == (m,n) := (nrows a, ncols a) qm := scalarMatrix(m,1) rm := copy a for i in 1..(if m=n then n-1 else n) repeat x := column(subMatrix(rm,i,m,i,i),1) h := scalarMatrix(m,1) setsubMatrix!(h,i,i,householder x) qm := qm*h rm := h*rm [qm,rm] lsqr(a,b) == dc := qr a n := ncols(dc.r) solveUpperTriangular(subMatrix(dc.r,1,n,1,n),transpose(dc.q)*b) polyfit(x,y,n) == a := new(#x,n+1,0@R)$Matrix(R) for j in 0..n repeat setColumn!(a,j+1,x^j) lsqr(a,y)
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
#C.23
C#
using System;   namespace RosettaCode.CSharp { class Program { static void Count_New_Triangle(ulong A, ulong B, ulong C, ulong Max_Perimeter, ref ulong Total_Cnt, ref ulong Primitive_Cnt) { ulong Perimeter = A + B + C;   if (Perimeter <= Max_Perimeter) { Primitive_Cnt = Primitive_Cnt + 1; Total_Cnt = Total_Cnt + Max_Perimeter / Perimeter; Count_New_Triangle(A + 2 * C - 2 * B, 2 * A + 2 * C - B, 2 * A + 3 * C - 2 * B, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt); Count_New_Triangle(A + 2 * B + 2 * C, 2 * A + B + 2 * C, 2 * A + 2 * B + 3 * C, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt); Count_New_Triangle(2 * B + 2 * C - A, B + 2 * C - 2 * A, 2 * B + 3 * C - 2 * A, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt); } }   static void Count_Pythagorean_Triples() { ulong T_Cnt, P_Cnt;   for (int I = 1; I <= 8; I++) { T_Cnt = 0; P_Cnt = 0; ulong ExponentNumberValue = (ulong)Math.Pow(10, I); Count_New_Triangle(3, 4, 5, ExponentNumberValue, ref T_Cnt, ref P_Cnt); Console.WriteLine("Perimeter up to 10E" + I + " : " + T_Cnt + " Triples, " + P_Cnt + " Primitives"); } }   static void Main(string[] args) { Count_Pythagorean_Triples(); } } }
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.
#REXX
REXX
/*REXX program outputs its own 1─line source.*/ say sourceline(1)
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.
#Ring
Ring
v = "see substr(`v = ` + char(34) + `@` + char(34) + nl + `@` ,`@`,v)" see substr(`v = ` + char(34) + `@` + char(34) + nl + `@` ,`@`,v)
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.
#Python
Python
# Constants a1 = [0, 1403580, -810728] m1 = 2**32 - 209 # a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 # d = m1 + 1   class MRG32k3a():   def __init__(self, seed_state=123): self.seed(seed_state)   def seed(self, seed_state): assert 0 <seed_state < d, f"Out of Range 0 x < {d}" self.x1 = [seed_state, 0, 0] self.x2 = [seed_state, 0, 0]   def next_int(self): "return random int in range 0..d" x1i = sum(aa * xx for aa, xx in zip(a1, self.x1)) % m1 x2i = sum(aa * xx for aa, xx in zip(a2, self.x2)) % m2 self.x1 = [x1i] + self.x1[:2] self.x2 = [x2i] + self.x2[:2]   z = (x1i - x2i) % m1 answer = (z + 1)   return answer   def next_float(self): "return random float between 0 and 1" return self.next_int() / d     if __name__ == '__main__': random_gen = MRG32k3a() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int())   random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
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.
#R
R
squares <- d <- seq_len(2200)^2 aAndb <- outer(squares, squares, '+') aAndb <- aAndb[upper.tri(aAndb, diag = TRUE)] sapply(squares, function(c) d <<- setdiff(d, aAndb + c)) print(sqrt(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.
#Racket
Racket
#lang racket   (require data/bit-vector)   (define (quadruples top) (define top+1 (add1 top)) (define 1..top (in-range 1 top+1)) (define r (make-bit-vector top+1)) (define ab (make-bit-vector (add1 (sqr (* top 2))))) (for* ((a 1..top) (b (in-range a top+1))) (bit-vector-set! ab (+ (sqr a) (sqr b)) #t))   (for/fold ((s 3)) ((c 1..top)) (for/fold ((s1 s) (s2 (+ s 2))) ((d (in-range (add1 c) top+1))) (when (bit-vector-ref ab s1) (bit-vector-set! r d #t)) (values (+ s1 s2) (+ s2 2))) (+ 2 s))   (for/list ((i (in-naturals 1)) (v (in-bit-vector r 1)) #:unless v) i))   (define (report n) (printf "Those values of d in 1..~a that can't be represented: ~a~%" n (quadruples n)))   (report 2200)
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
#Phix
Phix
-- demo\rosetta\PythagorasTree.exw with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas enum FILL, BORDER procedure drawTree(atom x1, y1, x2, y2, integer depth, dd) atom 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) if depth=dd then integer r = 250-depth*20 for draw=FILL to BORDER do -- one square... cdCanvasSetForeground(cddbuffer, iff(draw=FILL?rgb(r,#FF,0):CD_GRAY)) integer mode = iff(draw=FILL?CD_FILL:CD_CLOSED_LINES) cdCanvasBegin(cddbuffer,mode) cdCanvasVertex(cddbuffer, x1, 640-y1) cdCanvasVertex(cddbuffer, x2, 640-y2) cdCanvasVertex(cddbuffer, x3, 640-y3) cdCanvasVertex(cddbuffer, x4, 640-y4) cdCanvasEnd(cddbuffer) -- ...and the attached triangle if draw=FILL then cdCanvasSetForeground(cddbuffer, rgb(r-depth*10,#FF,0)) end if cdCanvasBegin(cddbuffer,mode) cdCanvasVertex(cddbuffer, x3, 640-y3) cdCanvasVertex(cddbuffer, x4, 640-y4) cdCanvasVertex(cddbuffer, x5, 640-y5) cdCanvasEnd(cddbuffer) end for elsif depth<dd then drawTree(x4, y4, x5, y5, depth + 1, dd) drawTree(x5, y5, x3, y3, depth + 1, dd) end if end procedure function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) cdCanvasActivate(cddbuffer) for i=0 to 7 do -- (draw leaves last) drawTree(275, 500, 375, 500, 0, i) end for cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_RED) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupCanvas(NULL) IupSetAttribute(canvas, "RASTERSIZE", "640x640") IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) dlg = IupDialog(canvas,"RESIZE=NO") IupSetAttribute(dlg, "TITLE", "Pythagoras Tree") IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure 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}}
#BBC_BASIC
BBC BASIC
*FLOAT 64 @% = &2040A INSTALL @lib$+"ARRAYLIB"   REM Test matrix for QR decomposition: DIM A(2,2) A() = 12, -51, 4, \ \ 6, 167, -68, \ \ -4, 24, -41   REM Do the QR decomposition: DIM Q(2,2), R(2,2) PROCqrdecompose(A(), Q(), R()) PRINT "Q:" PRINT Q(0,0), Q(0,1), Q(0,2) PRINT Q(1,0), Q(1,1), Q(1,2) PRINT Q(2,0), Q(2,1), Q(2,2) PRINT "R:" PRINT R(0,0), R(0,1), R(0,2) PRINT R(1,0), R(1,1), R(1,2) PRINT R(2,0), R(2,1), R(2,2)   REM Test data for least-squares solution: DIM x(10) : x() = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 DIM y(10) : y() = 1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321   REM Do the least-squares solution: DIM a(10,2), q(10,10), r(10,2), t(10,10), b(10), z(2) FOR i% = 0 TO 10 FOR j% = 0 TO 2 a(i%,j%) = x(i%) ^ j% NEXT NEXT PROCqrdecompose(a(), q(), r()) PROC_transpose(q(),t()) b() = t() . y() FOR k% = 2 TO 0 STEP -1 s = 0 IF k% < 2 THEN FOR j% = k%+1 TO 2 s += r(k%,j%) * z(j%) NEXT ENDIF z(k%) = (b(k%) - s) / r(k%,k%) NEXT k% PRINT '"Least-squares solution:" PRINT z(0), z(1), z(2) END   DEF PROCqrdecompose(A(), Q(), R()) LOCAL i%, k%, m%, n%, H() m% = DIM(A(),1) : n% = DIM(A(),2) DIM H(m%,m%) FOR i% = 0 TO m% : Q(i%,i%) = 1 : NEXT WHILE n% PROCqrstep(n%, k%, A(), H()) A() = H() . A() Q() = Q() . H() k% += 1 m% -= 1 n% -= 1 ENDWHILE R() = A() ENDPROC   DEF PROCqrstep(n%, k%, A(), H()) LOCAL a(), h(), i%, j% DIM a(n%,0), h(n%,n%) FOR i% = 0 TO n% : a(i%,0) = A(i%+k%,k%) : NEXT PROChouseholder(h(), a()) H() = 0  : H(0,0) = 1 FOR i% = 0 TO n% FOR j% = 0 TO n% H(i%+k%,j%+k%) = h(i%,j%) NEXT NEXT ENDPROC   REM Create the Householder matrix for the supplied column vector: DEF PROChouseholder(H(), a()) LOCAL e(), u(), v(), vt(), vvt(), I(), d() LOCAL i%, n% : n% = DIM(a(),1) REM Create the scaled standard basis vector e(): DIM e(n%,0) : e(0,0) = SGN(a(0,0)) * MOD(a()) REM Create the normal vector u(): DIM u(n%,0) : u() = a() + e() REM Normalise with respect to the first element: DIM v(n%,0) : v() = u() / u(0,0) REM Get the transpose of v() and its dot product with v(): DIM vt(0,n%), d(0) : PROC_transpose(v(), vt()) : d() = vt() . v() REM Get the product of v() and vt(): DIM vvt(n%,n%) : vvt() = v() . vt() REM Create an identity matrix I(): DIM I(n%,n%) : FOR i% = 0 TO n% : I(i%,i%) = 1 : NEXT REM Create the Householder matrix H() = I - 2/vt()v() v()vt(): vvt() *= 2 / d(0) : H() = I() - vvt() ENDPROC
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
#Clojure
Clojure
(defn gcd [a b] (if (zero? b) a (recur b (mod a b))))   (defn pyth [peri] (for [m (range 2 (Math/sqrt (/ peri 2))) n (range (inc (mod m 2)) m 2) ; n<m, opposite polarity  :let [p (* 2 m (+ m n))] ; = a+b+c for this (m,n)  :while (<= p peri)  :when (= 1 (gcd m n))  :let [m2 (* m m), n2 (* n n), [a b] (sort [(- m2 n2) (* 2 m n)]), c (+ m2 n2)] k (range 1 (inc (quot peri p)))] [(= k 1) (* k a) (* k b) (* k c)]))   (defn rcount [ts] ; (->> peri pyth rcount) produces [total, primitive] counts (reduce (fn [[total prims] t] [(inc total), (if (first t) (inc prims) prims)]) [0 0] ts))
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.
#Ruby
Ruby
_="_=%p;puts _%%_";puts _%_
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.
#Rust
Rust
fn main() { let x = "fn main() {\n let x = "; let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}\n"; print!("{}{:?}; let y = {:?}; {}", x, x, y, y) }
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.
#Raku
Raku
class MRG32k3a { has @!x1; has @!x2;   constant a1 = 0, 1403580, -810728; constant a2 = 527612, 0, -1370589; constant m1 = 2**32 - 209; constant m2 = 2**32 - 22853;   submethod BUILD ( Int :$seed where 0 < * <= m1 = 1 ) { @!x1 = @!x2 = $seed, 0, 0 }   method next-int { @!x1.unshift: (a1[0] * @!x1[0] + a1[1] * @!x1[1] + a1[2] * @!x1[2]) % m1; @!x1.pop; @!x2.unshift: (a2[0] * @!x2[0] + a2[1] * @!x2[1] + a2[2] * @!x2[2]) % m2; @!x2.pop; (@!x1[0] - @!x2[0]) % (m1 + 1) }   method next-rat { self.next-int / (m1 + 1) } }     # Test next-int with custom seed say 'Seed: 1234567; first five Int values:'; my $rng = MRG32k3a.new :seed(1234567); .say for $rng.next-int xx 5;     # Test next-rat (since these are rational numbers by default) say "\nSeed: 987654321; first 1e5 Rat values histogram:"; $rng = MRG32k3a.new :seed(987654321); say ( ($rng.next-rat * 5).floor xx 100_000 ).Bag;     # Test next-int with default seed say "\nSeed: default; first five Int values:"; $rng = MRG32k3a.new; .say for $rng.next-int xx 5;
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.
#Raku
Raku
my \N = 2200; my @sq = (0 .. N)»²; my @not = False xx N; @not[0] = True;   (1 .. N).race.map: -> $d { my $last = 0; for $d ... ($d/3).ceiling -> $a { for 1 .. ($a/2).ceiling -> $b { last if (my $ab = @sq[$a] + @sq[$b]) > @sq[$d]; if (@sq[$d] - $ab).sqrt.narrow ~~ Int { @not[$d] = True; $last = 1; last } } last if $last; } }   say @not.grep( *.not, :k );
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
#Processing
Processing
void tree(float x1, float y1, float x2, float y2, int depth) {   if (depth <= 0) { return; }   float dx = (x2 - x1); float dy = (y1 - y2);   float x3 = (x2 - dy); float y3 = (y2 - dx); float x4 = (x1 - dy); float y4 = (y1 - dx); float x5 = (x4 + 0.5*(dx - dy)); float y5 = (y4 - 0.5*(dx + dy));   // square beginShape(); fill(0.0, 255.0/depth, 0.0); vertex(x1, y1); vertex(x2, y2); vertex(x3, y3); vertex(x4, y4); vertex(x1, y1); endShape();   // triangle beginShape(); fill(0.0, 255.0/depth, 0.0); vertex(x3, y3); vertex(x4, y4); vertex(x5, y5); vertex(x3, y3); endShape();   tree(x4, y4, x5, y5, depth-1); tree(x5, y5, x3, y3, depth-1); }   void setup() { size(1920, 1080); background(255); stroke(0, 255, 0); tree(width/2.3, height, width/1.8, height, 10); }
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
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   typedef struct { int m, n; double ** v; } mat_t, *mat;   mat matrix_new(int m, int n) { mat x = malloc(sizeof(mat_t)); x->v = malloc(sizeof(double*) * m); x->v[0] = calloc(sizeof(double), m * n); for (int i = 0; i < m; i++) x->v[i] = x->v[0] + n * i; x->m = m; x->n = n; return x; }   void matrix_delete(mat m) { free(m->v[0]); free(m->v); free(m); }   void matrix_transpose(mat m) { for (int i = 0; i < m->m; i++) { for (int j = 0; j < i; j++) { double t = m->v[i][j]; m->v[i][j] = m->v[j][i]; m->v[j][i] = t; } } }   mat matrix_copy(int n, double a[][n], int m) { mat x = matrix_new(m, n); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) x->v[i][j] = a[i][j]; return x; }   mat matrix_mul(mat x, mat y) { if (x->n != y->m) return 0; mat r = matrix_new(x->m, y->n); for (int i = 0; i < x->m; i++) for (int j = 0; j < y->n; j++) for (int k = 0; k < x->n; k++) r->v[i][j] += x->v[i][k] * y->v[k][j]; return r; }   mat matrix_minor(mat x, int d) { mat m = matrix_new(x->m, x->n); for (int i = 0; i < d; i++) m->v[i][i] = 1; for (int i = d; i < x->m; i++) for (int j = d; j < x->n; j++) m->v[i][j] = x->v[i][j]; return m; }   /* c = a + b * s */ double *vmadd(double a[], double b[], double s, double c[], int n) { for (int i = 0; i < n; i++) c[i] = a[i] + s * b[i]; return c; }   /* m = I - v v^T */ mat vmul(double v[], int n) { mat x = matrix_new(n, n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) x->v[i][j] = -2 * v[i] * v[j]; for (int i = 0; i < n; i++) x->v[i][i] += 1;   return x; }   /* ||x|| */ double vnorm(double x[], int n) { double sum = 0; for (int i = 0; i < n; i++) sum += x[i] * x[i]; return sqrt(sum); }   /* y = x / d */ double* vdiv(double x[], double d, double y[], int n) { for (int i = 0; i < n; i++) y[i] = x[i] / d; return y; }   /* take c-th column of m, put in v */ double* mcol(mat m, double *v, int c) { for (int i = 0; i < m->m; i++) v[i] = m->v[i][c]; return v; }   void matrix_show(mat m) { for(int i = 0; i < m->m; i++) { for (int j = 0; j < m->n; j++) { printf(" %8.3f", m->v[i][j]); } printf("\n"); } printf("\n"); }   void householder(mat m, mat *R, mat *Q) { mat q[m->m]; mat z = m, z1; for (int k = 0; k < m->n && k < m->m - 1; k++) { double e[m->m], x[m->m], a; z1 = matrix_minor(z, k); if (z != m) matrix_delete(z); z = z1;   mcol(z, x, k); a = vnorm(x, m->m); if (m->v[k][k] > 0) a = -a;   for (int i = 0; i < m->m; i++) e[i] = (i == k) ? 1 : 0;   vmadd(x, e, a, e, m->m); vdiv(e, vnorm(e, m->m), e, m->m); q[k] = vmul(e, m->m); z1 = matrix_mul(q[k], z); if (z != m) matrix_delete(z); z = z1; } matrix_delete(z); *Q = q[0]; *R = matrix_mul(q[0], m); for (int i = 1; i < m->n && i < m->m - 1; i++) { z1 = matrix_mul(q[i], *Q); if (i > 1) matrix_delete(*Q); *Q = z1; matrix_delete(q[i]); } matrix_delete(q[0]); z = matrix_mul(*Q, m); matrix_delete(*R); *R = z; matrix_transpose(*Q); }   double in[][3] = { { 12, -51, 4}, { 6, 167, -68}, { -4, 24, -41}, { -1, 1, 0}, { 2, 0, 3}, };   int main() { mat R, Q; mat x = matrix_copy(3, in, 5); householder(x, &R, &Q);   puts("Q"); matrix_show(Q); puts("R"); matrix_show(R);   // to show their product is the input matrix mat m = matrix_mul(Q, R); puts("Q * R"); matrix_show(m);   matrix_delete(x); matrix_delete(R); matrix_delete(Q); matrix_delete(m); return 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.
#11l
11l
:start: print(‘Program: ’:argv[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
#CoffeeScript
CoffeeScript
  gcd = (x, y) -> return x if y == 0 gcd(y, x % y)   # m,n generate primitive Pythag triples # # preconditions: # m, n are integers of different parity # m > n # gcd(m,n) == 1 (coprime) # # m, n generate: [m*m - n*n, 2*m*n, m*m + n*n] # perimeter is 2*m*m + 2*m*n = 2 * m * (m+n) count_triples = (max_perim) -> num_primitives = 0 num_triples = 0 m = 2 upper_limit = Math.sqrt max_perim / 2 while m <= upper_limit n = m % 2 + 1 p = 2*m*m + 2*m*n delta = 4*m while n < m and p <= max_perim if gcd(m, n) == 1 num_primitives += 1 num_triples += Math.floor max_perim / p n += 2 p += delta m += 1 console.log num_primitives, num_triples   max_perim = Math.pow 10, 9 # takes under a minute count_triples(max_perim)  
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.
#Scala
Scala
val q = "\"" * 3 val c = """val q = "\"" * 3 val c = %s%s%s println(c format (q, c, q)) """ println(c format (q, c, q))
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.
#Ruby
Ruby
def mod(x, y) m = x % y if m < 0 then if y < 0 then return m - y else return m + y end end return m end   # Constants # First generator A1 = [0, 1403580, -810728] A1.freeze M1 = (1 << 32) - 209 # Second generator A2 = [527612, 0, -1370589] A2.freeze M2 = (1 << 32) - 22853   D = M1 + 1   # the last three values of the first generator $x1 = [0, 0, 0] # the last three values of the second generator $x2 = [0, 0, 0]   def seed(seed_state) $x1 = [seed_state, 0, 0] $x2 = [seed_state, 0, 0] end   def next_int() x1i = mod((A1[0] * $x1[0] + A1[1] * $x1[1] + A1[2] * $x1[2]), M1) x2i = mod((A2[0] * $x2[0] + A2[1] * $x2[1] + A2[2] * $x2[2]), M2) z = mod(x1i - x2i, M1)   $x1 = [x1i, $x1[0], $x1[1]] $x2 = [x2i, $x2[0], $x2[1]]   return z + 1 end   def next_float() return 1.0 * next_int() / D end   ########################################   seed(1234567) print next_int(), "\n" print next_int(), "\n" print next_int(), "\n" print next_int(), "\n" print next_int(), "\n" print "\n"   counts = [0, 0, 0, 0, 0] seed(987654321) for i in 1 .. 100000 value = (next_float() * 5.0).floor counts[value] = counts[value] + 1 end counts.each_with_index { |v,i| print i, ": ", v, "\n" }
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.
#REXX
REXX
/*REXX pgm computes/shows (integers), D that aren't possible for: a² + b² + c² = d² */ parse arg hi . /*obtain optional argument from the CL.*/ if hi=='' | hi=="," then hi=2200; high= 3 * hi /*Not specified? Then use the default.*/ @.=. /*array of integers to be squared. */ !.=. /* " " " squared. */ do j=1 for high /*precompute possible squares (to max).*/ _= j*j;  !._= j; if j<=hi then @.j= _ /*define a square; D value; squared # */ end /*j*/ d.=. /*array of possible solutions (D) */ do a=1 for hi-2; aodd= a//2 /*go hunting for solutions to equation.*/ do b=a to hi-1; if aodd then if b//2 then iterate /*Are A and B both odd? Then skip.*/ ab = @.a + @.b /*calculate sum of 2 (A,B) squares.*/ do c=b to hi; abc= ab + @.c /* " " " 3 (A,B,C) " */ if !.abc==. then iterate /*Not a square? Then skip it*/ s=!.abc; d.s= /*define this D solution as being found*/ end /*c*/ end /*b*/ end /*a*/ say say 'Not possible positive integers for d ≤' hi " using equation: a² + b² + c² = d²" say $= /* [↓] find all the "not possibles". */ do p=1 for hi; if d.p==. then $=$ p /*Not possible? Then add it to the list*/ end /*p*/ /* [↓] display list of not-possibles. */ say substr($, 2) /*stick a fork in it, we're all done. */