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/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
#11l
11l
T Splitmix64 UInt64 state   F seed(seed_state) .state = seed_state   F next_int() .state += 9E37'79B9'7F4A'7C15 V z = .state z = (z (+) (z >> 30)) * BF58'476D'1CE4'E5B9 z = (z (+) (z >> 27)) * 94D0'49BB'1331'11EB R z (+) (z >> 31)   F next_float() R Float(.next_int()) / 2.0^64   V random_gen = Splitmix64() random_gen.seed(1234567) L 5 print(random_gen.next_int())   random_gen.seed(987654321) V hist = Dict(0.<5, i -> (i, 0)) L 100'000 hist[Int(random_gen.next_float() * 5)]++ print(hist)
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.
#C.2B.2B
C++
#include <exception> #include <iostream>   using ulong = unsigned long;   class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; }   ulong next() { return state = state * state / div % mod; } };   int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
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.
#CLU
CLU
middle_square = cluster is seed, next rep = null own state: int   seed = proc (s: int) state := s end seed   next = proc () returns (int) state := (state ** 2) / 1000 // 1000000 return(state) end next end middle_square   start_up = proc () po: stream := stream$primary_output() middle_square$seed(675248) for i: int in int$from_to(1, 5) do stream$putl(po, int$unparse(middle_square$next())) end end start_up
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Lua
Lua
function create() local g = { magic = 0x2545F4914F6CDD1D, state = 0, seed = function(self, num) self.state = num end, next_int = function(self) local x = self.state x = x ~ (x >> 12) x = x ~ (x << 25) x = x ~ (x >> 27) self.state = x local answer = (x * self.magic) >> 32 return answer end, next_float = function(self) return self:next_int() / (1 << 32) end } return g end   local g = create() g:seed(1234567) print(g:next_int()) print(g:next_int()) print(g:next_int()) print(g:next_int()) print(g:next_int()) print()   local counts = {[0]=0, [1]=0, [2]=0, [3]=0, [4]=0} g:seed(987654321) for i=1,100000 do local j = math.floor(g:next_float() * 5.0) counts[j] = counts[j] + 1 end for i,v in pairs(counts) do print(i..': '..v) end
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#OxygenBasic
OxygenBasic
'RUNTIME COMPILING   source="print source"   a=compile source : call a : freememory a
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.
#D
D
import std.math; import std.stdio;   struct PCG32 { private: immutable ulong N = 6364136223846793005; ulong state = 0x853c49e6748fea9b; ulong inc = 0xda3e39cb94b95bdb;   public: void seed(ulong seed_state, ulong seed_sequence) { state = 0; inc = (seed_sequence << 1) | 1; nextInt(); state = state + seed_state; nextInt(); }   uint nextInt() { ulong old = state; state = old * N + inc; uint shifted = cast(uint)(((old >> 18) ^ old) >> 27); uint rot = old >> 59; return (shifted >> rot) | (shifted << ((~rot + 1) & 31)); }   double nextFloat() { return (cast(double) nextInt()) / (1L << 32); } }   void main() { auto r = PCG32();   r.seed(42, 54); writeln(r.nextInt()); writeln(r.nextInt()); writeln(r.nextInt()); writeln(r.nextInt()); writeln(r.nextInt()); writeln;   auto counts = [0, 0, 0, 0, 0]; r.seed(987654321, 1); foreach (_; 0..100_000) { int j = cast(int)floor(r.nextFloat() * 5.0); counts[j]++; }   writeln("The counts for 100,000 repetitions are:"); foreach (i,v; counts) { writeln(" ", i, " : ", v); } }
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#C
C
#include <stdio.h> #include <math.h> #include <string.h>   #define N 2200   int main(int argc, char **argv){ int a,b,c,d; int r[N+1]; memset(r,0,sizeof(r)); // zero solution array for(a=1; a<=N; a++){ for(b=a; b<=N; b++){ int aabb; if(a&1 && b&1) continue; // for positive odd a and b, no solution. aabb=a*a + b*b; for(c=b; c<=N; c++){ int aabbcc=aabb + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; // solution } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); // print non solution printf("\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
#AutoHotkey
AutoHotkey
pToken := Gdip_Startup() gdip1() Pythagoras_tree(600, 600, 712, 600, 1) UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height) OnExit, Exit return   Pythagoras_tree(x1, y1, x2, y2, depth){ global G, hwnd1, hdc, Width, Height if (depth > 7) Return   Pen := Gdip_CreatePen(0xFF808080, 1) Brush1 := Gdip_BrushCreateSolid(0xFFFFE600) Brush2 := Gdip_BrushCreateSolid(0xFFFAFF00) Brush3 := Gdip_BrushCreateSolid(0xFFDBFF00) Brush4 := Gdip_BrushCreateSolid(0xFFDBFF00) Brush5 := Gdip_BrushCreateSolid(0xFF9EFF00) Brush6 := Gdip_BrushCreateSolid(0xFF80FF00) Brush7 := Gdip_BrushCreateSolid(0xFF60FF00)   dx := x2 - x1 , dy := y1 - y2 x3 := x2 - dy , y3 := y2 - dx x4 := x1 - dy , y4 := y1 - dx x5 := x4 + (dx - dy) / 2 y5 := y4 - (dx + dy) / 2   ; draw box/triangle Gdip_FillPolygon(G, Brush%depth%, x1 "," y1 "|" x2 "," y2 "|" x3 "," y3 "|" x4 "," y4 "|" x1 "," y1) Gdip_FillPolygon(G, Brush%depth%, x4 "," y4 "|" x5 "," y5 "|" x3 "," y3 "|" x4 "," y4)   ; draw outline Gdip_DrawLines(G, Pen, x1 "," y1 "|" x2 "," y2 "|" x3 "," y3 "|" x4 "," y4 "|" x1 "," y1) Gdip_DrawLines(G, Pen, x4 "," y4 "|" x5 "," y5 "|" x3 "," y3 "|" x4 "," y4)   Pythagoras_tree(x4, y4, x5, y5, depth+1) Pythagoras_tree(x5, y5, x3, y3, depth+1) }   gdip1(){ global Width := A_ScreenWidth, Height := A_ScreenHeight Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop Gui, 1: Show, NA hwnd1 := WinExist() OnMessage(0x201, "WM_LBUTTONDOWN") hbm := CreateDIBSection(Width, Height) hdc := CreateCompatibleDC() obm := SelectObject(hdc, hbm) G := Gdip_GraphicsFromHDC(hdc) Gdip_SetSmoothingMode(G, 4) } ; --------------------------------------------------------------- WM_LBUTTONDOWN(){ PostMessage, 0xA1, 2 } ; --------------------------------------------------------------- gdip2(){ global Gdip_DeleteBrush(pBrush) Gdip_DeletePen(pPen) SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) } ; --------------------------------------------------------------- exit: gdip2() ExitApp return
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
#Ada
Ada
with Interfaces; use Interfaces;   package Random_Splitmix64 is   function next_Int return Unsigned_64; function next_float return Float; procedure Set_State (Seed : in Unsigned_64); end Random_Splitmix64;
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
#ALGOL_68
ALGOL 68
BEGIN # generate some pseudo random numbers using Splitmix64 # # note that although LONG INT is 64 bits in Algol 68G, LONG BITS is longer than 64 bits # LONG BITS mask 64 = LONG 16rffffffffffffffff; LONG BITS state := 16r1234567; LONG INT one shl 64 = ABS ( LONG 16r1 SHL 64 ); # sets the state to the specified seed value # PROC seed = ( LONG INT num )VOID: state := BIN num; # XOR and assign convenience operator # PRIO XORAB = 1; OP XORAB = ( REF LONG BITS x, LONG BITS v )REF LONG BITS: x := ( x XOR v ) AND mask 64; # add a LONG BITS value to a LONG BITS # OP +:= = ( REF LONG BITS r, LONG BITS v )REF LONG BITS: r := SHORTEN ( BIN ( LENG ABS r + LENG ABS v ) AND mask 64 ); # multiplies a LONG BITS value by a LONG BITS value # OP *:= = ( REF LONG BITS r, LONG BITS v )REF LONG BITS: r := SHORTEN ( BIN ( ABS LENG r * LENG ABS v ) AND mask 64 ); # gets the next pseudo random integer # PROC next int = LONG INT: BEGIN state +:= LONG 16r9e3779b97f4a7c15; LONG BITS z := state; z XORAB ( z SHR 30 ); z *:= LONG 16rbf58476d1ce4e5b9; z XORAB ( z SHR 27 ); z *:= LONG 16r94d049bb133111eb; z XORAB ( z SHR 31 ); ABS z END # next int # ; # gets the next pseudo random real # PROC next float = LONG REAL: next int / one shl 64; BEGIN # task test cases # seed( 1234567 ); print( ( whole( next int, 0 ), newline ) ); # 6457827717110365317 # print( ( whole( next int, 0 ), newline ) ); # 3203168211198807973 # print( ( whole( next int, 0 ), newline ) ); # 9817491932198370423 # print( ( whole( next int, 0 ), newline ) ); # 4593380528125082431 # print( ( whole( next int, 0 ), newline ) ); # 16408922859458223821 # # count the number of occurances of 0..4 in a sequence of pseudo random reals scaled to be in [0..5) # seed( 987654321 ); [ 0 : 4 ]INT counts; FOR i FROM LWB counts TO UPB counts DO counts[ i ] := 0 OD; TO 100 000 DO counts[ SHORTEN ENTIER ( next float * 5 ) ] +:= 1 OD; FOR i FROM LWB counts TO UPB counts DO print( ( whole( i, -2 ), ": ", whole( counts[ i ], -6 ) ) ) OD; print( ( newline ) ) END END
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. MIDDLE-SQUARE.   DATA DIVISION. WORKING-STORAGE SECTION. 01 STATE. 03 SEED PIC 9(6) VALUE 675248. 03 SQUARE PIC 9(12). 03 FILLER REDEFINES SQUARE. 05 FILLER PIC 9(3). 05 NEXT-SEED PIC 9(6). 05 FILLER PIC 9(3).   PROCEDURE DIVISION. BEGIN. PERFORM SHOW-NUM 5 TIMES. STOP RUN.   SHOW-NUM. PERFORM MAKE-RANDOM. DISPLAY SEED.   MAKE-RANDOM. MULTIPLY SEED BY SEED GIVING SQUARE. MOVE NEXT-SEED TO SEED.
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.
#F.23
F#
  // Pseudo-random numbers/Middle-square method. Nigel Galloway: January 5th., 2022 Seq.unfold(fun n->let n=n*n%1000000000L/1000L in Some(n,n)) 675248L|>Seq.take 5|>Seq.iter(printfn "%d")  
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Nim
Nim
import algorithm, sequtils, strutils, tables   const C = 0x2545F4914F6CDD1Du64   type XorShift = object state: uint64   func seed(gen: var XorShift; num: uint64) = gen.state = num   func nextInt(gen: var XorShift): uint32 = var x = gen.state x = x xor x shr 12 x = x xor x shl 25 x = x xor x shr 27 gen.state = x result = uint32((x * C) shr 32)   func nextFloat(gen: var XorShift): float = gen.nextInt().float / float(0xFFFFFFFFu32)     when isMainModule:   var gen: XorShift   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/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Perl
Perl
use strict; use warnings; no warnings 'portable'; use feature 'say'; use Math::AnyNum qw(:overload);   package Xorshift_star {   sub new { my ($class, %opt) = @_; bless {state => $opt{seed}}, $class; }   sub next_int { my ($self) = @_; my $state = $self->{state}; $state ^= $state >> 12; $state ^= $state << 25 & (2**64 - 1); $state ^= $state >> 27; $self->{state} = $state; ($state * 0x2545F4914F6CDD1D) >> 32 & (2**32 - 1); }   sub next_float { my ($self) = @_; $self->next_int / 2**32; } }   say 'Seed: 1234567, first 5 values:'; my $rng = Xorshift_star->new(seed => 1234567); say $rng->next_int for 1 .. 5;   my %h; say "\nSeed: 987654321, values histogram:"; $rng = Xorshift_star->new(seed => 987654321); $h{int 5 * $rng->next_float}++ for 1 .. 100_000; say "$_ $h{$_}" for sort keys %h;
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.
#Oz
Oz
declare I in thread {System.showInfo I#[34]#I#[34]} end I ="declare I in thread {System.showInfo I#[34]#I#[34]} end 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.
#Delphi
Delphi
  program PCG32_test;   {$APPTYPE CONSOLE} uses System.SysUtils, Velthuis.BigIntegers, System.Generics.Collections;   type TPCG32 = class public FState: BigInteger; FInc: BigInteger; mask64: BigInteger; mask32: BigInteger; k: BigInteger; constructor Create(seedState, seedSequence: BigInteger); overload; constructor Create(); overload; destructor Destroy; override; procedure Seed(seed_state, seed_sequence: BigInteger); function NextInt(): BigInteger; function NextIntRange(size: Integer): TArray<BigInteger>; function NextFloat(): Extended; end;   { TPCG32 }   constructor TPCG32.Create(seedState, seedSequence: BigInteger); begin Create(); Seed(seedState, seedSequence); end;   constructor TPCG32.Create; begin k := '6364136223846793005'; mask64 := (BigInteger(1) shl 64) - 1; mask32 := (BigInteger(1) shl 32) - 1; FState := 0; FInc := 0; end;   destructor TPCG32.Destroy; begin   inherited; end;   function TPCG32.NextFloat: Extended; begin Result := (NextInt.AsExtended / (BigInteger(1) shl 32).AsExtended); end;   function TPCG32.NextInt(): BigInteger; var old, xorshifted, rot, answer: BigInteger; begin old := FState; FState := ((old * k) + FInc) and mask64; xorshifted := (((old shr 18) xor old) shr 27) and mask32; rot := (old shr 59) and mask32; answer := (xorshifted shr rot.AsInteger) or (xorshifted shl ((-rot) and BigInteger(31)).AsInteger); Result := answer and mask32; end;   function TPCG32.NextIntRange(size: Integer): TArray<BigInteger>; var i: Integer; begin SetLength(Result, size); if size = 0 then exit;   for i := 0 to size - 1 do Result[i] := NextInt; end;   procedure TPCG32.Seed(seed_state, seed_sequence: BigInteger); begin FState := 0; FInc := ((seed_sequence shl 1) or 1) and mask64; nextint(); Fstate := (Fstate + seed_state); nextint(); end;   var PCG32: TPCG32; i, key: Integer; count: TDictionary<Integer, Integer>;   begin PCG32 := TPCG32.Create(42, 54);   for i := 0 to 4 do Writeln(PCG32.NextInt().ToString);   PCG32.seed(987654321, 1);   count := TDictionary<Integer, Integer>.Create();   for i := 1 to 100000 do begin key := Trunc(PCG32.NextFloat * 5); if count.ContainsKey(key) then count[key] := count[key] + 1 else count.Add(key, 1); end;   Writeln(#10'The counts for 100,000 repetitions are:');   for key in count.Keys do Writeln(key, ' : ', count[key]);   count.free; PCG32.free; Readln; end.  
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#C.23
C#
using System;   namespace PythagoreanQuadruples { class Program { const int MAX = 2200; const int MAX2 = MAX * MAX * 2;   static void Main(string[] args) { bool[] found = new bool[MAX + 1]; // all false by default bool[] a2b2 = new bool[MAX2 + 1]; // ditto int s = 3;   for(int a = 1; a <= MAX; a++) { int a2 = a * a; for (int b=a; b<=MAX; b++) { a2b2[a2 + b * b] = true; } }   for (int c = 1; c <= MAX; c++) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= MAX; d++) { if (a2b2[s1]) found[d] = true; s1 += s2; s2 += 2; } }   Console.WriteLine("The values of d <= {0} which can't be represented:", MAX); for (int d = 1; d < MAX; d++) { if (!found[d]) Console.Write("{0} ", d); } Console.WriteLine(); } } }
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
#BASIC256
BASIC256
  Subroutine pythagoras_tree(x1, y1, x2, y2, depth) If depth > 10 Then Return   dx = x2 - x1 : dy = y1 - y2 x3 = x2 - dy : y3 = y2 - dx x4 = x1 - dy : y4 = y1 - dx x5 = x4 + (dx - dy) / 2 y5 = y4 - (dx + dy) / 2 #draw the box Line x1, y1, x2, y2 : Line x2, y2, x3, y3 Line x3, y3, x4, y4 : Line x4, y4, x1, y1   Call pythagoras_tree(x4, y4, x5, y5, depth +1) Call pythagoras_tree(x5, y5, x3, y3, depth +1) End Subroutine   w = 800 : h = w * 11 \ 16 w2 = w \ 2 : diff = w \ 12   Clg FastGraphics Graphsize w, h Color green Call pythagoras_tree(w2 - diff, h - 10, w2 + diff, h - 10, 0) Refresh ImgSave "pythagoras_tree.jpg", "jpg" 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
#C
C
  #include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<time.h>   typedef struct{ double x,y; }point;   void pythagorasTree(point a,point b,int times){   point c,d,e;   c.x = b.x - (a.y - b.y); c.y = b.y - (b.x - a.x);   d.x = a.x - (a.y - b.y); d.y = a.y - (b.x - a.x);   e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2; e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2;   if(times>0){ setcolor(rand()%15 + 1);   line(a.x,a.y,b.x,b.y); line(c.x,c.y,b.x,b.y); line(c.x,c.y,d.x,d.y); line(a.x,a.y,d.x,d.y);   pythagorasTree(d,e,times-1); pythagorasTree(e,c,times-1); } }   int main(){   point a,b; double side; int iter;   time_t t;   printf("Enter initial side length : "); scanf("%lf",&side);   printf("Enter number of iterations : "); scanf("%d",&iter);   a.x = 6*side/2 - side/2; a.y = 4*side; b.x = 6*side/2 + side/2; b.y = 4*side;   initwindow(6*side,4*side,"Pythagoras Tree ?");   srand((unsigned)time(&t));   pythagorasTree(a,b,iter);   getch();   closegraph();   return 0;   }
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
#C
C
/* Written in 2015 by Sebastiano Vigna ([email protected])   To the extent possible under law, the author has dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.   See <http://creativecommons.org/publicdomain/zero/1.0/>. */   #include <stdint.h> #include <stdio.h> #include <math.h>   /* This is a fixed-increment version of Java 8's SplittableRandom generator See http://dx.doi.org/10.1145/2714064.2660195 and http://docs.oracle.com/javase/8/docs/api/java/util/SplittableRandom.html   It is a very fast generator passing BigCrush, and it can be useful if for some reason you absolutely want 64 bits of state. */   static uint64_t x; /* The state can be seeded with any value. */   uint64_t next() { uint64_t z = (x += 0x9e3779b97f4a7c15); z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >> 27)) * 0x94d049bb133111eb; return z ^ (z >> 31); }   double next_float() { return next() / pow(2.0, 64); }   int main() { int i, j; x = 1234567; for(i = 0; i < 5; ++i) printf("%llu\n", next()); /* needed to use %lu verb for GCC 7.5.0-3 */ x = 987654321; int vec5[5] = {0, 0, 0, 0, 0}; for(i = 0; i < 100000; ++i) { j = next_float() * 5.0; vec5[j] += 1; } for(i = 0; i < 5; ++i) printf("%d: %d ", i, vec5[i]); }  
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.
#Factor
Factor
USING: kernel math namespaces prettyprint ;   SYMBOL: seed 675248 seed set-global   : rand ( -- n ) seed get sq 1000 /i 1000000 mod dup seed set ;   5 [ rand . ] times
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.
#Forth
Forth
: next-random dup * 1000 / 1000000 mod ; : 5-random-num 5 0 do next-random dup . loop ; 675248 5-random-num
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.
#FreeBASIC
FreeBASIC
Dim Shared seed As Integer = 675248 Dim i As Integer Declare Function Rand As Integer For i = 1 To 5 Print Rand Next i Sleep   Function Rand As Integer Dim s As String s = Str(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/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Phix
Phix
with javascript_semantics include mpfr.e mpz cmult = mpz_init("0x2545F4914F6CDD1D"), state = mpz_init(), b64 = mpz_init("0x10000000000000000"), -- (truncate to 64 bits) b32 = mpz_init("0x100000000"), -- (truncate to 32 bits) tmp = mpz_init(), x = mpz_init() procedure seed(integer num) mpz_set_si(state,num) end procedure function next_int() mpz_set(x,state) -- x := state mpz_tdiv_q_2exp(tmp, x, 12) -- tmp := trunc(x/2^12) mpz_xor(x, x, tmp) -- x := xor_bits(x,tmp) mpz_mul_2exp(tmp, x, 25) -- tmp := x * 2^25. mpz_xor(x, x, tmp) -- x := xor_bits(x,tmp) mpz_fdiv_r(x, x, b64) -- x := remainder(x,b64) mpz_tdiv_q_2exp(tmp, x, 27) -- tmp := trunc(x/2^27) mpz_xor(x, x, tmp) -- x := xor_bits(x,tmp) mpz_fdiv_r(state, x, b64) -- state := remainder(x,b64) mpz_mul(x,x,cmult) -- x *= cmult mpz_tdiv_q_2exp(x, x, 32) -- x := trunc(x/2^32) mpz_fdiv_r(x, x, b32) -- x := remainder(x,b32) return mpz_get_atom(x) end function function next_float() return next_int() / #100000000 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 100000 do integer idx = floor(next_float()*5)+1 r[idx] += 1 end for ?r
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.
#PARI.2FGP
PARI/GP
()->quine
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.
#F.23
F#
  // PCG32. Nigel Galloway: August 13th., 2020 let N=6364136223846793005UL let seed n g=let g=g<<<1|||1UL in (g,(g+n)*N+g) let pcg32=Seq.unfold(fun(n,g)->let rot,xs=uint32(g>>>59),uint32(((g>>>18)^^^g)>>>27) in Some(uint32((xs>>>(int rot))|||(xs<<<(-(int rot)&&&31))),(n,g*N+n))) let pcgFloat n=pcg32 n|>Seq.map(fun n-> (float n)/4294967296.0)  
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.
#C.2B.2B
C++
#include <iostream> #include <vector>   constexpr int N = 2200; constexpr int N2 = 2 * N * N;   int main() { using namespace std;   vector<bool> found(N + 1); vector<bool> aabb(N2 + 1);   int s = 3;   for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { aabb[aa + b * b] = true; } }   for (int c = 1; c <= N; ++c) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= N; ++d) { if (aabb[s1]) { found[d] = true; } s1 += s2; s2 += 2; } }   cout << "The values of d <= " << N << " which can't be represented:" << endl; for (int d = 1; d <= N; ++d) { if (!found[d]) { cout << d << " "; } } cout << endl;   return 0; }
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#C.2B.2B
C++
#include <windows.h> #include <string> #include <iostream>   const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class tree { public: tree() { bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear(); clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 ); clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 ); clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 ); } void draw( int it, POINT a, POINT b ) { if( !it ) return; bmp.setPenColor( clr[it % 6] ); POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x }; POINT d = { a.x - df.y, a.y - df.x }; POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )}; drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c ); } void save( std::string p ) { bmp.saveBitmap( p ); } private: void drawSqr( POINT a, POINT b, POINT c, POINT d ) { HDC dc = bmp.getDC(); MoveToEx( dc, a.x, a.y, NULL ); LineTo( dc, b.x, b.y ); LineTo( dc, c.x, c.y ); LineTo( dc, d.x, d.y ); LineTo( dc, a.x, a.y ); } myBitmap bmp; DWORD clr[6]; }; int main( int argc, char* argv[] ) { POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER }, ptB = { ptA.x + LINE_LEN, ptA.y }; tree t; t.draw( 12, ptA, ptB ); // change this path t.save( "?:/pt.bmp" ); return 0; }
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
#Factor
Factor
USING: io kernel math math.bitwise math.functions math.statistics namespaces prettyprint sequences ;   SYMBOL: state   : seed ( n -- ) 64 bits state set ;   : next-int ( -- n ) 0x9e3779b97f4a7c15 state [ + 64 bits ] change state get -30 0xbf58476d1ce4e5b9 -27 0x94d049bb133111eb -31 1 [ [ dupd shift bitxor ] dip * 64 bits ] 2tri@ ;   : next-float ( -- x ) next-int 64 2^ /f ;   ! Test next-int "Seed: 1234567; first five integer values" print 1234567 seed 5 [ next-int . ] times nl   ! Test next-float "Seed: 987654321; first 100,000 float values histogram" print 987654321 seed 100,000 [ next-float 5 * >integer ] replicate histogram .
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
#Forth
Forth
variable rnd-state   : rnd-base-op ( z factor shift -- u ) 2 pick swap rshift rot xor * ;   : rnd-next ( -- u ) $9e3779b97f4a7c15 rnd-state +! rnd-state @ $bf58476d1ce4e5b9 #30 rnd-base-op $94d049bb133111eb #27 rnd-base-op #1 #31 rnd-base-op ;   #1234567 rnd-state ! cr rnd-next u. cr rnd-next u. cr rnd-next u. cr rnd-next u. cr rnd-next u. cr     : rnd-next-float ( -- f ) rnd-next 0 d>f 0 1 d>f f/ ;   create counts 0 , 0 , 0 , 0 , 0 , : counts-fill #987654321 rnd-state ! 100000 0 do rnd-next-float 5.0e0 f* f>d drop cells counts + dup @ 1+ swap ! loop ; : counts-disp 5 0 do cr i . ': emit bl emit counts i cells + @ . loop cr ;   counts-fill counts-disp
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.
#Go
Go
package main   import "fmt"   func random(seed int) int { return seed * seed / 1e3 % 1e6 }   func main() { seed := 675248 for i := 1; i <= 5; i++ { seed = random(seed) fmt.Println(seed) } }
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.
#Haskell
Haskell
findPseudoRandom :: Int -> Int findPseudoRandom seed = let square = seed * seed squarestr = show square enlarged = replicate ( 12 - length squarestr ) '0' ++ squarestr in read $ take 6 $ drop 3 enlarged   solution :: [Int] solution = tail $ take 6 $ iterate findPseudoRandom 675248
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Python
Python
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 const = 0x2545F4914F6CDD1D       class Xorshift_star():   def __init__(self, seed=0): self.state = seed & mask64   def seed(self, num): self.state = num & mask64   def next_int(self): "return random int between 0 and 2**32" x = self.state x = (x ^ (x >> 12)) & mask64 x = (x ^ (x << 25)) & mask64 x = (x ^ (x >> 27)) & mask64 self.state = x answer = (((x * const) & mask64) >> 32) & 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 = Xorshift_star() 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/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.
#Pascal
Pascal
const s=';begin writeln(#99#111#110#115#116#32#115#61#39,s,#39,s)end.';begin writeln(#99#111#110#115#116#32#115#61#39,s,#39,s)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.
#Factor
Factor
USING: accessors kernel locals math math.bitwise math.statistics prettyprint sequences ;   CONSTANT: const 6364136223846793005   TUPLE: pcg32 state inc ;   : <pcg32> ( -- pcg32 ) 0x853c49e6748fea9b 0xda3e39cb94b95bdb pcg32 boa ;   :: next-int ( pcg -- n ) pcg state>> :> old old const * pcg inc>> + 64 bits pcg state<< old -18 shift old bitxor -27 shift 32 bits :> shifted old -59 shift 32 bits :> r shifted r neg shift shifted r neg 31 bitand shift bitor 32 bits ;   : next-float ( pcg -- x ) next-int 1 32 shift /f ;   :: seed ( pcg st seq -- ) 0x0 pcg state<< seq 0x1 shift 1 bitor 64 bits pcg inc<< pcg next-int drop pcg state>> st + pcg state<< pcg next-int drop ;   ! Task <pcg32> 42 54 [ seed ] keepdd 5 [ dup next-int . ] times   987654321 1 [ seed ] keepdd 100,000 [ dup next-float 5 * >integer ] replicate nip histogram .
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.
#Go
Go
package main   import ( "fmt" "math" )   const CONST = 6364136223846793005   type Pcg32 struct{ state, inc uint64 }   func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }   func (pcg *Pcg32) seed(seedState, seedSequence uint64) { pcg.state = 0 pcg.inc = (seedSequence << 1) | 1 pcg.nextInt() pcg.state = pcg.state + seedState pcg.nextInt() }   func (pcg *Pcg32) nextInt() uint32 { old := pcg.state pcg.state = old*CONST + pcg.inc pcgshifted := uint32(((old >> 18) ^ old) >> 27) rot := uint32(old >> 59) return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31)) }   func (pcg *Pcg32) nextFloat() float64 { return float64(pcg.nextInt()) / (1 << 32) }   func main() { randomGen := Pcg32New() randomGen.seed(42, 54) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) }   var counts [5]int randomGen.seed(987654321, 1) 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/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.
#Crystal
Crystal
n = 2200 l_add, l = Hash(Int32, Bool).new(false), Hash(Int32, Bool).new(false) (1..n).each do |x| x2 = x * x (x..n).each { |y| l_add[x2 + y * y] = true } end   s = 3 (1..n).each do |x| s1 = s s += 2 s2 = s ((x+1)..n).each do |y| l[y] = true if l_add[s1] s1 += s2 s2 += 2 end end   puts (1..n).reject{ |x| l[x] }.join(" ")
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). Related tasks Fractal tree
#EasyLang
EasyLang
func tree x1 y1 x2 y2 depth . . if depth < 8 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) color3 0.3 0.2 + depth / 18 0.1 polygon [ x1 y1 x2 y2 x3 y3 x4 y4 ] polygon [ x3 y3 x4 y4 x5 y5 ] call tree x4 y4 x5 y5 depth + 1 call tree x5 y5 x3 y3 depth + 1 . . color3 0.3 0 0.1 call tree 41 90 59 90 0
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
#F.23
F#
// Pure F# Implementation of SplitMix64 let a: uint64 = 0x9e3779b97f4a7c15UL   let nextInt (state: uint64) = let newstate = state + (0x9e3779b97f4a7c15UL) let rand = newstate let rand = (rand ^^^ (rand >>> 30)) * 0xbf58476d1ce4e5b9UL let rand = (rand ^^^ (rand >>> 27)) * 0x94d049bb133111ebUL let rand = rand ^^^ (rand >>> 31) (rand, newstate)   let nextFloat (state: uint64) = let (rand, newState) = nextInt state let randf = (rand / (1UL <<< 64)) |> float (randf, newState)   [<EntryPoint>] let main argv = let state = 1234567UL let (first, state) = nextInt state let (second, state) = nextInt state let (third, state) = nextInt state let (fourth, state) = nextInt state let (fifth, state) = nextInt state printfn "%i" first printfn "%i" second printfn "%i" third printfn "%i" fourth printfn "%i" fifth 0
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
#Go
Go
package main   import ( "fmt" "math" )   type Splitmix64 struct{ state uint64 }   func Splitmix64New(state uint64) *Splitmix64 { return &Splitmix64{state} }   func (sm64 *Splitmix64) nextInt() uint64 { sm64.state += 0x9e3779b97f4a7c15 z := sm64.state z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9 z = (z ^ (z >> 27)) * 0x94d049bb133111eb return z ^ (z >> 31) }   func (sm64 *Splitmix64) nextFloat() float64 { return float64(sm64.nextInt()) / (1 << 64) }   func main() { randomGen := Splitmix64New(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) }   var counts [5]int randomGen = Splitmix64New(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/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.
#J
J
(_6{._3}.])&.:(10&#.^:_1)@(*~) ^: (>:i.6) 675248
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.
#jq
jq
# Input: a positive integer # Output: the "middle-square" def middle_square: (tostring|length) as $len | (. * .) | tostring | (3*length/4|ceil) as $n | .[ -$n : $len-$n] | if length == 0 then 0 else tonumber end;   # Input: a positive integer # Output: middle_square, applied recursively def middle_squares: middle_square | ., middle_squares;   limit(5; 675248 | middle_squares)
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.
#Julia
Julia
const seed = [675248]   function random() s = string(seed[] * seed[], pad=12) # turn a number into string, pad to 12 digits seed[] = parse(Int, s[begin+3:end-3]) # take middle of number string, parse to Int return seed[] end   # Middle-square method use   for i = 1:5 println(random()) end  
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.
#Nim
Nim
proc rand:int = var seed {.global.} = 675248 seed = int(seed*seed) div 1000 mod 1000000 return seed   for _ in 1..5: echo rand()
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Raku
Raku
class Xorshift-star { has $!state;   submethod BUILD ( Int :$seed where * > 0 = 1 ) { $!state = $seed }   method next-int { $!state +^= $!state +> 12; $!state +^= $!state +< 25 +& (2⁶⁴ - 1); $!state +^= $!state +> 27; ($!state * 0x2545F4914F6CDD1D) +> 32 +& (2³² - 1) }   method next-rat { self.next-int / 2³² } }   # Test next-int say 'Seed: 1234567; first five Int values'; my $rng = Xorshift-star.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 = Xorshift-star.new( :seed(987654321) ); say ( ($rng.next-rat * 5).floor xx 100_000 ).Bag;     # Test with default seed say "\nSeed: default; first five Int values"; $rng = Xorshift-star.new; .say for $rng.next-int xx 5;
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.
#Perl
Perl
$s = q($s = q(%s); printf($s, $s); ); printf($s, $s);  
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.
#Haskell
Haskell
import Data.Bits import Data.Word import System.Random import Data.List   data PCGen = PCGen !Word64 !Word64   mkPCGen state sequence = let n = 6364136223846793005 :: Word64 inc = (sequence `shiftL` 1) .|. 1 :: Word64 in PCGen ((inc + state)*n + inc) inc   instance RandomGen PCGen where next (PCGen state inc) = let n = 6364136223846793005 :: Word64 xs = fromIntegral $ ((state `shiftR` 18) `xor` state) `shiftR` 27 :: Word32 rot = fromIntegral $ state `shiftR` 59 :: Int in (fromIntegral $ (xs `shiftR` rot) .|. (xs `shiftL` ((-rot) .&. 31)) , PCGen (state * n + inc) inc)   split _ = error "PCG32 is not splittable"   randoms' :: RandomGen g => g -> [Int] randoms' g = unfoldr (pure . next) g   toFloat n = fromIntegral n / (2^32 - 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.
#D
D
import std.bitmanip : BitArray; import std.stdio;   enum N = 2_200; enum N2 = 2*N*N;   void main() { BitArray found; found.length = N+1;   BitArray aabb; aabb.length = N2+1;   uint s=3;   for (uint a=1; a<=N; ++a) { uint aa = a*a; for (uint b=1; b<N; ++b) { aabb[aa + b*b] = true; } }   for (uint c=1; c<=N; ++c) { uint s1 = s; s += 2; uint s2 = s; for (uint d=c+1; d<=N; ++d) { if (aabb[s1]) { found[d] = true; } s1 += s2; s2 += 2; } }   writeln("The values of d <= ", N, " which can't be represented:"); for (uint d=1; d<=N; ++d) { if (!found[d]) { write(d, ' '); } } writeln; }
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
#F.23
F#
type Point = { x:float; y:float } type Line = { left : Point; right : Point }   let draw_start_html = """<!DOCTYPE html> <html><head><title>Phytagoras tree</title> <style type="text/css">polygon{fill:none;stroke:black;stroke-width:1}</style> </head><body> <svg width="640" height="640">"""   let draw_end_html = """Sorry, your browser does not support inline SVG. </svg></body></html>"""   let svg_square x1 y1 x2 y2 x3 y3 x4 y4 = sprintf """<polygon points="%i %i %i %i %i %i %i %i" />""" (int x1) (int y1) (int x2) (int y2) (int x3) (int y3) (int x4) (int y4)   let out (x : string) = System.Console.WriteLine(x)   let sprout line = let dx = line.right.x - line.left.x let dy = line.left.y - line.right.y let line2 = { left = { x = line.left.x - dy; y = line.left.y - dx }; right = { x = line.right.x - dy ; y = line.right.y - dx } } let triangleTop = { x = line2.left.x + (dx - dy) / 2.; y = line2.left.y - (dx + dy) / 2. } [ { left = line2.left; right = triangleTop } { left = triangleTop; right = line2.right } ]   let draw_square line = let dx = line.right.x - line.left.x let dy = line.left.y - line.right.y svg_square line.left.x line.left.y line.right.x line.right.y (line.right.x - dy) (line.right.y - dx) (line.left.x - dy) (line.left.y - dx)   let rec generate lines = function | 0 -> () | n -> let next = lines |> List.collect (fun line -> (draw_square >> out) line sprout line ) generate next (n-1)     [<EntryPoint>] let main argv = let depth = 1 + if argv.Length > 0 then (System.UInt32.Parse >> int) argv.[0] else 2 out draw_start_html generate [{ left = { x = 275.; y = 500. }; right = { x = 375.; y = 500. } }] depth out draw_end_html 0
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
#Haskell
Haskell
import Data.Bits import Data.Word import Data.List   next :: Word64 -> (Word64, Word64) next state = f4 $ state + 0x9e3779b97f4a7c15 where f1 z = (z `xor` (z `shiftR` 30)) * 0xbf58476d1ce4e5b9 f2 z = (z `xor` (z `shiftR` 27)) * 0x94d049bb133111eb f3 z = z `xor` (z `shiftR` 31) f4 s = ((f3 . f2 . f1) s, s)   randoms = unfoldr (pure . next)   toFloat n = fromIntegral n / (2^64 - 1)
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
#Julia
Julia
const C1 = 0x9e3779b97f4a7c15 const C2 = 0xbf58476d1ce4e5b9 const C3 = 0x94d049bb133111eb   mutable struct Splitmix64 state::UInt end   """ return random int between 0 and 2**64 """ function next_int(smx::Splitmix64) z = smx.state = smx.state + C1 z = (z ⊻ (z >> 30)) * C2 z = (z ⊻ (z >> 27)) * C3 return z ⊻ (z >> 31) end   """ return random float between 0 and 1 """ next_float(smx::Splitmix64) = next_int(smx) / one(Int128) << 64   function testSplitmix64() random_gen = Splitmix64(1234567) for i in 1:5 println(next_int(random_gen)) end   random_gen = Splitmix64(987654321) hist = fill(0, 5) for _ in 1:100_000 hist[Int(floor(next_float(random_gen) * 5)) + 1] += 1 end foreach(n -> print(n - 1, ": ", hist[n], " "), 1:5) end   testSplitmix64()  
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.
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method use warnings;   sub msq { use feature qw( state ); state $seed = 675248; $seed = sprintf "%06d", $seed ** 2 / 1000 % 1e6; }   print msq, "\n" for 1 .. 5;
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.
#Phix
Phix
with javascript_semantics integer seed = 675248 function random() seed = remainder(floor(seed*seed/1000),1e6) -- seed = to_integer(sprintf("%012d",seed*seed)[4..9]) return seed end function for i=1 to 5 do ?random() end for
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#REXX
REXX
/*REXX program generates pseudo─random numbers using the XOR─shift─star 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= x2d(2545f4914f6cdd1d) /*initialize the constant to be used. */ o.12= copies(0, 12) /*construct 12 bits of zeros. */ o.25= copies(0, 25) /* " 25 " " " */ o.27= copies(0, 27) /* " 27 " " " */ 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()), 18) /*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**32 /*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(@.#), 14) /*show count of a random num.*/ end /*#*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ b2d: parse arg ?; return x2d( b2x(?) ) /*convert bin ──► decimal. */ d2b: parse arg ?; return right( x2b( d2x(?) ), 64, 0) /*convert dec ──► 64 bit bin.*/ commas: parse arg _; do ?=length(_)-3 to 1 by -3; _= insert(',', _, ?); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ next: procedure expose state const o.; x= d2b(state) /*convert STATE to binary. */ x = xor(x, left( o.12 || x, 64) ) /*shift right 12 bits and XOR*/ x = xor(x, right( x || o.25, 64) ) /* " left 25 " " " */ x = xor(x, left( o.27 || x, 64) ) /* " right 27 " " " */ state= b2d(x) /*set STATE to the latest X.*/ return b2d( left( d2b(state * const), 32) ) /*return a pseudo─random num.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ 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/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.
#Phix
Phix
constant c="constant c=%sprintf(1,c,{34&c&34})"printf(1,c,{34&c&34})
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.
#Java
Java
public class PCG32 { private static final long N = 6364136223846793005L;   private long state = 0x853c49e6748fea9bL; private long inc = 0xda3e39cb94b95bdbL;   public void seed(long seedState, long seedSequence) { state = 0; inc = (seedSequence << 1) | 1; nextInt(); state = state + seedState; nextInt(); }   public int nextInt() { long old = state; state = old * N + inc; int shifted = (int) (((old >>> 18) ^ old) >>> 27); int rot = (int) (old >>> 59); return (shifted >>> rot) | (shifted << ((~rot + 1) & 31)); }   public double nextFloat() { var u = Integer.toUnsignedLong(nextInt()); return (double) u / (1L << 32); }   public static void main(String[] args) { var r = new PCG32();   r.seed(42, 54); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println();   int[] counts = {0, 0, 0, 0, 0}; r.seed(987654321, 1); for (int i = 0; i < 100_000; i++) { int j = (int) Math.floor(r.nextFloat() * 5.0); counts[j]++; }   System.out.println("The counts for 100,000 repetitions are:"); for (int i = 0; i < counts.length; i++) { System.out.printf("  %d : %d\n", 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.
#FreeBASIC
FreeBASIC
' version 12-08-2017 ' compile with: fbc -s console   #Define max 2200   Dim As UInteger l, m, n, l2, l2m2 Dim As UInteger limit = max * 4 \ 15 Dim As UInteger max2 = limit * limit * 2 ReDim As Ubyte list_1(max2), list_2(max2 +1)   ' prime sieve, list_2(l) contains a 0 if l = prime For l = 4 To max2 Step 2 list_1(l) = 1 Next For l = 3 To max2 Step 2 If list_1(l) = 0 Then For m = l * l To max2 Step l * 2 list_1(m) = 1 Next End If Next   ' we do not need a and b (a and b are even, l = a \ 2, m = b \ 2) ' we only need to find d For l = 1 To limit l2 = l * l For m = l To limit l2m2 = l2 + m * m list_2(l2m2 +1) = 1 ' if l2m2 is a prime, no other factors exits If list_1(l2m2) = 0 Then Continue For ' find possible factors of l2m2 ' if l2m2 is odd, we need only to check the odd divisors For n = 2 + (l2m2 And 1) To Fix(Sqr(l2m2 -1)) Step 1 + (l2m2 And 1) If l2m2 Mod n = 0 Then ' set list_2(x) to 1 if solution is found list_2(l2m2 \ n + n) = 1 End If Next Next Next   For l = 1 To max If list_2(l) = 0 Then Print l; " "; Next Print   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep 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
#FreeBASIC
FreeBASIC
' version 03-12-2016 ' compile with: fbc -s gui ' or fbc -s console   Sub pythagoras_tree(x1 As Double, y1 As Double, x2 As Double, y2 As Double, depth As ULong)   If depth > 10 Then Return   Dim As Double dx = x2 - x1, dy = y1 - y2 Dim As Double x3 = x2 - dy, y3 = y2 - dx Dim As Double x4 = x1 - dy, y4 = y1 - dx Dim As Double x5 = x4 + (dx - dy) / 2 Dim As Double y5 = y4 - (dx + dy) / 2 'draw the box Line (x1, y1) - (x2, y2) : Line - (x3, y3) Line - (x4, y4) : Line - (x1, y1)   pythagoras_tree(x4, y4, x5, y5, depth +1) pythagoras_tree(x5, y5, x3, y3, depth +1)   End Sub   ' ------=< MAIN >=------ ' max for w is about max screensize - 500 Dim As ULong w = 800, h = w * 11 \ 16 Dim As ULong w2 = w \ 2, diff = w \ 12   ScreenRes w, h, 8 pythagoras_tree(w2 - diff, h -10 , w2 + diff , h -10 , 0) ' BSave "pythagoras_tree.bmp",0       ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[BitShiftLevelUint, MultiplyUint, GenerateRandomNumbers] BitShiftLevelUint[z_, n_] := BitShiftRight[z, n] MultiplyUint[z_, n_] := Mod[z n, 2^64] GenerateRandomNumbers[st_, n_] := Module[{state = st}, Table[ state += 16^^9e3779b97f4a7c15; state = Mod[state, 2^64]; z = state; z = MultiplyUint[BitXor[z, BitShiftLevelUint[z, 30]], 16^^bf58476d1ce4e5b9]; z = MultiplyUint[BitXor[z, BitShiftLevelUint[z, 27]], 16^^94d049bb133111eb]; Mod[BitXor[z, BitShiftLevelUint[z, 31]], 2^64] , {n} ] ] GenerateRandomNumbers[1234567, 5] nums = GenerateRandomNumbers[987654321, 10^5]; KeySort[Counts[Floor[5 nums/N[2^64]]]]
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
#Nim
Nim
import math, sequtils, strutils   const Two64 = 2.0^64   type Splitmix64 = object state: uint64   func initSplitmix64(seed: uint64): Splitmix64 = ## Initialize a Splitmiax64 PRNG. Splitmix64(state: seed)   func nextInt(r: var Splitmix64): uint64 = ## Return the next pseudorandom integer (actually a uint64 value). r.state += 0x9e3779b97f4a7c15u var z = r.state z = (z xor z shr 30) * 0xbf58476d1ce4e5b9u z = (z xor z shr 27) * 0x94d049bb133111ebu result = z xor z shr 31   func nextFloat(r: var Splitmix64): float = ## Retunr the next pseudorandom float (between 0.0 and 1.0 excluded). r.nextInt().float / Two64     when isMainModule:   echo "Seed = 1234567:" var prng = initSplitmix64(1234567) for i in 1..5: echo i, ": ", ($prng.nextInt).align(20)   echo "\nSeed = 987654321:" var counts: array[0..4, int] prng = initSplitmix64(987654321) for _ in 1..100_000: inc counts[int(prng.nextFloat * 5)] echo toSeq(counts.pairs).mapIt(($it[0]) & ": " & ($it[1])).join(", "
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
#Perl
Perl
use strict; use warnings; no warnings 'portable'; use feature 'say'; use Math::AnyNum qw(:overload);   package splitmix64 {   sub new { my ($class, %opt) = @_; bless {state => $opt{seed}}, $class; }   sub next_int { my ($self) = @_; my $next = $self->{state} = ($self->{state} + 0x9e3779b97f4a7c15) & (2**64 - 1); $next = ($next ^ ($next >> 30)) * 0xbf58476d1ce4e5b9 & (2**64 - 1); $next = ($next ^ ($next >> 27)) * 0x94d049bb133111eb & (2**64 - 1); ($next ^ ($next >> 31)) & (2**64 - 1); }   sub next_float { my ($self) = @_; $self->next_int / 2**64; } }   say 'Seed: 1234567, first 5 values:'; my $rng = splitmix64->new(seed => 1234567); say $rng->next_int for 1 .. 5;   my %h; say "\nSeed: 987654321, values histogram:"; $rng = splitmix64->new(seed => 987654321); $h{int 5 * $rng->next_float}++ for 1 .. 100_000; say "$_ $h{$_}" for sort keys %h;
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
#11l
11l
Int64 nTriples, nPrimitives, limit   F countTriples(Int64 =x, =y, =z) L V p = x + y + z I p > :limit R    :nPrimitives++  :nTriples += :limit I/ p   V t0 = x - 2 * y + 2 * z V t1 = 2 * x - y + 2 * z V t2 = t1 - y + z countTriples(t0, t1, t2)   t0 += 4 * y t1 += 2 * y t2 += 4 * y countTriples(t0, t1, t2)   z = t2 - 4 * x y = t1 - 4 * x x = t0 - 2 * x   L(p) 1..8 limit = Int64(10) ^ p nTriples = nPrimitives = 0 countTriples(3, 4, 5) print(‘Up to #11: #11 triples, #9 primitives.’.format(limit, nTriples, nPrimitives))
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.
#PureBasic
PureBasic
Procedure.i MSRandom() Static.i seed=675248 seed = (seed*seed/1000)%1000000 ProcedureReturn seed EndProcedure   If OpenConsole() For i=1 To 5 : PrintN(Str(i)+": "+Str(MSRandom())) : Next Input() EndIf
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.
#Python
Python
seed = 675248 def random(): global seed s = str(seed ** 2) while len(s) != 12: s = "0" + s seed = int(s[3:9]) return seed for i in range(0,5): print(random())  
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Ruby
Ruby
class Xorshift_star MASK64 = (1 << 64) - 1 MASK32 = (1 << 32) - 1   def initialize(seed = 0) = @state = seed & MASK64   def next_int x = @state x = x ^ (x >> 12) x = (x ^ (x << 25)) & MASK64 x = x ^ (x >> 27) @state = x (((x * 0x2545F4914F6CDD1D) & MASK64) >> 32) & MASK32 end   def next_float = next_int.fdiv((1 << 32))   end   random_gen = Xorshift_star.new(1234567) 5.times{ puts random_gen.next_int}   random_gen = Xorshift_star.new(987654321) tally = Hash.new(0) 100_000.times{ tally[(random_gen.next_float*5).floor] += 1 } puts tally.sort.map{|ar| ar.join(": ") }
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.
#PHP
PHP
<?php $p = '<?php $p = %c%s%c; printf($p,39,$p,39); ?> '; printf($p,39,$p,39); ?>
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.
#Julia
Julia
const mask32, CONST = 0xffffffff, UInt(6364136223846793005)   mutable struct PCG32 state::UInt64 inc::UInt64 PCG32(st=0x853c49e6748fea9b, i=0xda3e39cb94b95bdb) = new(st, i) end   """return random 32 bit unsigned int""" function next_int!(x::PCG32) old = x.state x.state = (old * CONST) + x.inc xorshifted = (((old >> 18) ⊻ old) >> 27) & mask32 rot = (old >> 59) & mask32 return ((xorshifted >> rot) | (xorshifted << ((-rot) & 31))) & mask32 end   """return random float between 0 and 1""" next_float!(x::PCG32) = next_int!(x) / (1 << 32)   function seed!(x::PCG32, st, seq) x.state = 0x0 x.inc = (UInt(seq) << 0x1) | 1 next_int!(x) x.state = x.state + UInt(st) next_int!(x) end   function testPCG32() random_gen = PCG32() seed!(random_gen, 42, 54) for _ in 1:5 println(next_int!(random_gen)) end seed!(random_gen, 987654321, 1) hist = fill(0, 5) for _ in 1:100_000 hist[Int(floor(next_float!(random_gen) * 5)) + 1] += 1 end println(hist) for n in 1:5 print(n - 1, ": ", hist[n], " ") end end   testPCG32()  
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.
#Kotlin
Kotlin
import kotlin.math.floor   class PCG32 { private var state = 0x853c49e6748fea9buL private var inc = 0xda3e39cb94b95bdbuL   fun nextInt(): UInt { val old = state state = old * N + inc val shifted = old.shr(18).xor(old).shr(27).toUInt() val rot = old.shr(59) return (shifted shr rot.toInt()) or shifted.shl((rot.inv() + 1u).and(31u).toInt()) }   fun nextFloat(): Double { return nextInt().toDouble() / (1L shl 32) }   fun seed(seedState: ULong, seedSequence: ULong) { state = 0u inc = (seedSequence shl 1).or(1uL) nextInt() state += seedState nextInt() }   companion object { private const val N = 6364136223846793005uL } }   fun main() { val r = PCG32()   r.seed(42u, 54u) println(r.nextInt()) println(r.nextInt()) println(r.nextInt()) println(r.nextInt()) println(r.nextInt()) println()   val counts = Array(5) { 0 } r.seed(987654321u, 1u) for (i in 0 until 100000) { val j = floor(r.nextFloat() * 5.0).toInt() counts[j] += 1 }   println("The counts for 100,000 repetitions are:") for (iv in counts.withIndex()) { println("  %d : %d".format(iv.index, iv.value)) } }
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Go
Go
package main   import "fmt"   const ( N = 2200 N2 = N * N * 2 )   func main() { s := 3 var s1, s2 int var r [N + 1]bool var ab [N2 + 1]bool   for a := 1; a <= N; a++ { a2 := a * a for b := a; b <= N; b++ { ab[a2 + b * b] = true } }   for c := 1; c <= N; c++ { s1 = s s += 2 s2 = s for d := c + 1; d <= N; d++ { if ab[s1] { r[d] = true } s1 += s2 s2 += 2 } }   for d := 1; d <= N; d++ { if !r[d] { fmt.Printf("%d ", d) } } fmt.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
#Go
Go
package main   import ( "image" "image/color" "image/draw" "image/png" "log" "os" )   const ( width, height = 800, 600 maxDepth = 11 // how far to recurse, between 1 and 20 is reasonable colFactor = uint8(255 / maxDepth) // adjusts the colour so leaves get greener further out fileName = "pythagorasTree.png" )   func main() { img := image.NewNRGBA(image.Rect(0, 0, width, height)) // create new image bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) // prepare white for background draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) // fill the background   drawSquares(340, 550, 460, 550, img, 0) // start off near the bottom of the image   imgFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer imgFile.Close() if err := png.Encode(imgFile, img); err != nil { imgFile.Close() log.Fatal(err) } }   func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) { if depth > maxDepth { return } dx, dy := bx-ax, ay-by x3, y3 := bx-dy, by-dx x4, y4 := ax-dy, ay-dx x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2 col := color.RGBA{0, uint8(depth) * colFactor, 0, 255} drawLine(ax, ay, bx, by, img, col) drawLine(bx, by, x3, y3, img, col) drawLine(x3, y3, x4, y4, img, col) drawLine(x4, y4, ax, ay, img, col) drawSquares(x4, y4, x5, y5, img, depth+1) drawSquares(x5, y5, x3, y3, img, depth+1) }   func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) { dx := abs(x1 - x0) dy := abs(y1 - y0) var sx, sy int = -1, -1 if x0 < x1 { sx = 1 } if y0 < y1 { sy = 1 } err := dx - dy for { img.Set(x0, y0, col) if x0 == x1 && y0 == y1 { break } e2 := 2 * err if e2 > -dy { err -= dy x0 += sx } if e2 < dx { err += dx y0 += sy } } } func abs(x int) int { if x < 0 { return -x } return x }
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
#Phix
Phix
with javascript_semantics include mpfr.e mpz state = mpz_init(), shift = mpz_init("0x9e3779b97f4a7c15"), mult1 = mpz_init("0xbf58476d1ce4e5b9"), mult2 = mpz_init("0x94d049bb133111eb"), b64 = mpz_init("0x10000000000000000"), -- (truncate to 64 bits) tmp = mpz_init(), z = mpz_init() procedure seed(integer num) mpz_set_si(state,num) end procedure procedure next_int() mpz_add(state, state, shift) -- state += shift mpz_fdiv_r(state, state, b64) -- state := remainder(z,b64) mpz_set(z, state) -- z := state mpz_tdiv_q_2exp(tmp, z, 30) -- tmp := trunc(z/2^30) mpz_xor(z, z, tmp) -- z := xor_bits(z,tmp) mpz_mul(z, z, mult1) -- z *= mult1 mpz_fdiv_r(z, z, b64) -- z := remainder(z,b64) mpz_tdiv_q_2exp(tmp, z, 27) -- tmp := trunc(z/2^27) mpz_xor(z, z, tmp) -- z := xor_bits(z,tmp) mpz_mul(z, z, mult2) -- z *= mult2 mpz_fdiv_r(z, z, b64) -- z := remainder(z,b64) mpz_tdiv_q_2exp(tmp, z, 31) -- tmp := trunc(z/2^31) mpz_xor(z, z, tmp) -- z := xor_bits(z,tmp) -- (result left in z) end procedure function next_float() next_int() mpfr f = mpfr_init_set_z(z) mpfr_div_z(f, f, b64) return mpfr_get_d(f) end function seed(1234567) for i=1 to 5 do next_int() printf(1,"%s\n",mpz_get_str(z)) end for seed(987654321) sequence r = repeat(0,5) for i=1 to 100000 do integer rdx = floor(next_float()*5)+1 r[rdx] += 1 end for ?r
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
#360_Assembly
360 Assembly
* Pythagorean triples - 12/06/2018 PYTHTRI CSECT USING PYTHTRI,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability MVC PMAX,=F'1' pmax=1 LA R6,1 i=1 DO WHILE=(C,R6,LE,=F'6') do i=1 to 6 L R5,PMAX pmax MH R5,=H'10' *10 ST R5,PMAX pmax=pmax*10 MVC PRIM,=F'0' prim=0 MVC COUNT,=F'0' count=0 L R1,PMAX pmax BAL R14,ISQRT isqrt(pmax) SRA R0,1 /2 ST R0,NMAX nmax=isqrt(pmax)/2 LA R7,1 n=1 DO WHILE=(C,R7,LE,NMAX) do n=1 to nmax LA R9,1(R7) m=n+1 LR R5,R9 m AR R5,R7 +n MR R4,R9 *m SLA R5,1 *2 LR R8,R5 p=2*m*(m+n) DO WHILE=(C,R8,LE,PMAX) do while p<=pmax LR R1,R9 m LR R2,R7 n BAL R14,GCD gcd(m,n) IF C,R0,EQ,=F'1' THEN if gcd(m,n)=1 then L R2,PRIM prim LA R2,1(R2) +1 ST R2,PRIM prim=prim+1 L R4,PMAX pmax SRDA R4,32 ~ DR R4,R8 /p A R5,COUNT +count ST R5,COUNT count=count+pmax/p ENDIF , endif LA R9,2(R9) m=m+2 LR R5,R9 m AR R5,R7 +n MR R4,R9 *m SLA R5,1 *2 LR R8,R5 p=2*m*(m+n) ENDDO , enddo n LA R7,1(R7) n++ ENDDO , enddo n L R1,PMAX pmax XDECO R1,XDEC edit pmax MVC PG+15(9),XDEC+3 output pmax L R1,COUNT count XDECO R1,XDEC edit count MVC PG+33(9),XDEC+3 output count L R1,PRIM prim XDECO R1,XDEC edit prim MVC PG+55(9),XDEC+3 output prim XPRNT PG,L'PG print LA R6,1(R6) i++ ENDDO , enddo i L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling sav NMAX DS F nmax PMAX DS F pmax COUNT DS F count PRIM DS F prim PG DC CL80'Max Perimeter: ........., Total: ........., Primitive:' XDEC DS CL12 GCD EQU * --------------- function gcd(a,b) STM R2,R7,GCDSA save context LR R3,R1 c=a LR R4,R2 d=b GCDLOOP LR R6,R3 c SRDA R6,32 ~ DR R6,R4 /d LTR R6,R6 if c mod d=0 BZ GCDELOOP then leave loop LR R5,R6 e=c mod d LR R3,R4 c=d LR R4,R5 d=e B GCDLOOP loop GCDELOOP LR R0,R4 return(d) LM R2,R7,GCDSA restore context BR R14 return GCDSA DS 6A context store ISQRT EQU * --------------- function isqrt(n) STM R3,R10,ISQRTSA save context LR R6,R1 n=r1 LR R10,R6 sqrtn=n SRA R10,1 sqrtn=n/2 IF LTR,R10,Z,R10 THEN if sqrtn=0 then LA R10,1 sqrtn=1 ELSE , else LA R9,0 snm2=0 LA R8,0 snm1=0 LA R7,0 sn=0 LA R3,0 okexit=0 DO UNTIL=(C,R3,EQ,=A(1)) do until okexit=1 AR R10,R7 sqrtn=sqrtn+sn LR R9,R8 snm2=snm1 LR R8,R7 snm1=sn LR R4,R6 n SRDA R4,32 ~ DR R4,R10 /sqrtn SR R5,R10 -sqrtn SRA R5,1 /2 LR R7,R5 sn=(n/sqrtn-sqrtn)/2 IF C,R7,EQ,=F'0',OR,CR,R7,EQ,R9 THEN if sn=0 or sn=snm2 then LA R3,1 okexit=1 ENDIF , endif ENDDO , enddo until ENDIF , endif LR R5,R10 sqrtn MR R4,R10 *sqrtn IF CR,R5,GT,R6 THEN if sqrtn*sqrtn>n then BCTR R10,0 sqrtn=sqrtn-1 ENDIF , endif LR R0,R10 return(sqrtn) LM R3,R10,ISQRTSA restore context BR R14 return ISQRTSA DS 8A context store YREGS END PYTHTRI
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.
#Raku
Raku
sub msq { state $seed = 675248; $seed = $seed² div 1000 mod 1000000; }   say msq() xx 5;
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.
#Red
Red
Red[] seed: 675248 rand: does [seed: to-integer (seed * 1.0 * seed / 1000) % 1000000] ; multiply by 1.0 to avoid integer overflow (32-bit) loop 5 [print rand]
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.
#Ruby
Ruby
def middle_square (seed) return to_enum(__method__, seed) unless block_given? s = seed.digits.size loop { yield seed = (seed*seed).to_s.rjust(s*2, "0")[s/2, s].to_i } end   puts middle_square(675248).take(5)
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Sidef
Sidef
class Xorshift_star(state) {   define ( mask32 = (2**32 - 1), mask64 = (2**64 - 1), )   method next_int { state ^= (state >> 12) state ^= (state << 25 & mask64) state ^= (state >> 27) (state * 0x2545F4914F6CDD1D) >> 32 & mask32 }   method next_float { self.next_int / (mask32+1) } }   say 'Seed: 1234567, first 5 values:'; var rng = Xorshift_star(1234567) say 5.of { rng.next_int }   say "\nSeed: 987654321, values histogram:"; var rng = Xorshift_star(987654321) var histogram = Bag(1e5.of { floor(5*rng.next_float) }...) histogram.pairs.sort.each { .join(": ").say }
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.
#PicoLisp
PicoLisp
('((X) (list (lit X) (lit X))) '((X) (list (lit X) (lit X))))
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.
#PL.2FI
PL/I
s:proc options(main)reorder;dcl sysprint file,m(7)init( ' s:proc options(main)reorder\dcl sysprint file,m(7)init(', ' *)char(99),i,j,(translate,substr)builtin,c char\i=1\j=n', ' \do i=1 to 6\put skip list('' '''''')\do j=2 to 56\c=substr', ' (m(i),j)\put edit(c)(a)\n:proc\put list(translate(m(i),', ' ''5e''x,''e0''x))\end n\if c='''''''' then put edit(c)(a)\end\ ', ' put edit('''''','')(a(50))\end\do i=2 to 6\j=n\end\end s\ ', *)char(99),i,j,(translate,substr)builtin,c char;i=1;j=n  ;do i=1 to 6;put skip list(' ''');do j=2 to 56;c=substr (m(i),j);put edit(c)(a);n:proc;put list(translate(m(i), '5e'x,'e0'x));end n;if c='''' then put edit(c)(a);end; put edit(''',')(a(50));end;do i=2 to 6;j=n;end;end s;
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of gen #1 */ x2 = [0, 0, 0] /* list of three last values of gen #2 */ method seed(u64 seed_state) assert seed_state in range >0 and < d x1 = [seed_state, 0, 0] x2 = [seed_state, 0, 0] end method method next_int() x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1 x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2 x1 = [x1i, x1[0], x1[1]] /* Keep last three */ x2 = [x2i, x2[0], x2[1]] /* Keep last three */ z = (x1i - x2i) % m1 answer = (z + 1) return answer end method method next_float(): return float next_int() / d end method end class MRG32k3a Use: random_gen = instance MRG32k3a random_gen.seed(1234567) print(random_gen.next_int()) /* 1459213977 */ print(random_gen.next_int()) /* 2827710106 */ print(random_gen.next_int()) /* 4245671317 */ print(random_gen.next_int()) /* 3877608661 */ print(random_gen.next_int()) /* 2595287583 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers generated with the seed `1234567` are as shown above Show that for an initial seed of '987654321' the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931 Show your output here, on this page.
#11l
11l
V a1 = [Int64(0), 1403580, -810728] V m1 = Int64(2) ^ 32 - 209 V a2 = [Int64(527612), 0, -1370589] V m2 = Int64(2) ^ 32 - 22853 V d = m1 + 1   T MRG32k3a [Int64] x1, x2   F (seed_state = 123) .seed(seed_state)   F seed(Int64 seed_state) assert(seed_state C Int64(0) <.< :d, ‘Out of Range 0 x < #.’.format(:d)) .x1 = [Int64(seed_state), 0, 0] .x2 = [Int64(seed_state), 0, 0]   F next_int() ‘return random int in range 0..d’ V x1i = (sum(zip(:a1, .x1).map((aa, xx) -> aa * xx)) % :m1 + :m1) % :m1 V x2i = (sum(zip(:a2, .x2).map((aa, xx) -> aa * xx)) % :m2 + :m2) % :m2 .x1 = [x1i] [+] .x1[0.<2] .x2 = [x2i] [+] .x2[0.<2] V z = ((x1i - x2i) % :m1 + :m1) % :m1 R z + 1   F next_float() ‘return random float between 0 and 1’ R Float(.next_int()) / :d   V random_gen = MRG32k3a() random_gen.seed(1234567) L 5 print(random_gen.next_int())   random_gen.seed(987654321) V hist = Dict(0.<5, i -> (i, 0)) L 100'000 hist[Int(random_gen.next_float() * 5)]++ print(hist)
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.
#Lua
Lua
function uint32(n) return n & 0xffffffff end   function uint64(n) return n & 0xffffffffffffffff end   N = 6364136223846793005 state = 0x853c49e6748fea9b inc = 0xda3e39cb94b95bdb   function pcg32_seed(seed_state, seed_sequence) state = 0 inc = (seed_sequence << 1) | 1 pcg32_int() state = state + seed_state pcg32_int() end   function pcg32_int() local old = state state = uint64(old * N + inc) local shifted = uint32(((old >> 18) ~ old) >> 27) local rot = uint32(old >> 59) return uint32((shifted >> rot) | (shifted << ((~rot + 1) & 31))) end   function pcg32_float() return 1.0 * pcg32_int() / (1 << 32) end   -------------------------------------------------------------------   pcg32_seed(42, 54) print(pcg32_int()) print(pcg32_int()) print(pcg32_int()) print(pcg32_int()) print(pcg32_int()) print()   counts = { 0, 0, 0, 0, 0 } pcg32_seed(987654321, 1) for i=1,100000 do local j = math.floor(pcg32_float() * 5.0) + 1 counts[j] = counts[j] + 1 end   print("The counts for 100,000 repetitions are:") for i=1,5 do print(" " .. (i - 1) .. ": " .. counts[i]) end
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   a,   b,   c,   and   d, find   (and show here)   those values of   d   that   can't   be represented. Show the values of   d   on one line of output   (optionally with a title). Related tasks   Euler's sum of powers conjecture.   Pythagorean triples. Reference   the Wikipedia article:   Pythagorean quadruple.
#Haskell
Haskell
powersOfTwo :: [Int] powersOfTwo = iterate (2 *) 1   unrepresentable :: [Int] unrepresentable = merge powersOfTwo ((5 *) <$> powersOfTwo)   merge :: [Int] -> [Int] -> [Int] merge xxs@(x:xs) yys@(y:ys) | x < y = x : merge xs yys | otherwise = y : merge xxs ys   main :: IO () main = do putStrLn "The values of d <= 2200 which can't be represented." print $ takeWhile (<= 2200) unrepresentable
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
#Haskell
Haskell
mkBranches :: [(Float,Float)] -> [[(Float,Float)]] mkBranches [a, b, c, d] = let d = 0.5 <*> (b <+> (-1 <*> a)) l1 = d <+> orth d l2 = orth l1 in [ [a <+> l2, b <+> (2 <*> l2), a <+> l1, a] , [a <+> (2 <*> l1), b <+> l1, b, b <+> l2] ] where (a, b) <+> (c, d) = (a+c, b+d) n <*> (a, b) = (a*n, b*n) orth (a, b) = (-b, a)
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
#Object_Pascal
Object Pascal
  program splitmix64;   {$IF Defined(FPC)}{$MODE Delphi}{$ENDIF} {$INLINE ON} {$Q-}{$R-}   { Written in 2015 by Sebastiano Vigna ([email protected]) http://prng.di.unimi.it/splitmix64.c   Onject Pascal port written in 2020 by I. Kakoulidis   To the extent possible under law, the author has dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.   See <http://creativecommons.org/publicdomain/zero/1.0/>. }   { This is a fixed-increment version of Java 8's SplittableRandom generator See http://dx.doi.org/10.1145/2714064.2660195 and http://docs.oracle.com/javase/8/docs/api/java/util/SplittableRandom.html   It is a very fast generator passing BigCrush, and it can be useful if for some reason you absolutely want 64 bits of state. } uses Math;   type TSplitMix64 = record state: UInt64; procedure Init(seed: UInt64); inline; function Next(): UInt64; inline; function NextFloat(): double; inline; end;   procedure TSplitMix64.Init(seed: UInt64); begin state := seed; end;   function TSplitMix64.Next(): UInt64; begin state := state + UInt64($9e3779b97f4a7c15); Result := state; Result := (Result xor (Result shr 30)) * UInt64($bf58476d1ce4e5b9); Result := (Result xor (Result shr 27)) * UInt64($94d049bb133111eb); Result := Result xor (Result shr 31); end;   function TSplitMix64.NextFloat(): Double; begin Result := Next() / 18446744073709551616.0; end;   var r: TSplitMix64; i, j: Integer; vec: array[0..4] of Integer;   begin j := 0; r.Init(1234567); for i := 0 to 4 do WriteLn(r.Next());   r.Init(987654321); for i := 0 to 99999 do begin j := Trunc(r.NextFloat() * 5.0); Inc(vec[j]); end;   for i := 0 to 4 do Write(i, ': ', vec[i], ' '); end.  
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Action.21
Action!
DEFINE PTR="CARD" DEFINE ENTRY_SIZE="3" TYPE TRIPLE=[BYTE a,b,c] TYPE TRIPLES=[ PTR buf ;BYTE ARRAY BYTE count]   PTR FUNC GetItemAddr(TRIPLES POINTER arr BYTE index) PTR addr   addr=arr.buf+index*ENTRY_SIZE RETURN (addr)   PROC PrintTriples(TRIPLES POINTER arr) INT i TRIPLE POINTER t   FOR i=0 TO arr.count-1 DO t=GetItemAddr(arr,i) PrintF("(%B %B %B) ",t.a,t.b,t.c) OD RETURN   PROC Init(TRIPLES POINTER arr BYTE ARRAY b) arr.buf=b arr.count=0 RETURN   PROC AddItem(TRIPLES POINTER arr TRIPLE POINTER t) TRIPLE POINTER p   p=GetItemAddr(arr,arr.count) p.a=t.a p.b=t.b p.c=t.c arr.count==+1 RETURN   PROC FindTriples(TRIPLES POINTER res BYTE limit) BYTE ARRAY data(100) BYTE half,i,j,k TRIPLE t   Init(res,data) half=limit/2 FOR i=1 TO half DO FOR j=i TO half DO FOR k=j TO limit DO IF i+j+k<limit AND i*i+j*j=k*k THEN t.a=i t.b=j t.c=k AddItem(res,t) FI OD OD OD RETURN   BYTE FUNC Gcd(BYTE a,b) BYTE tmp   IF a<b THEN tmp=a a=b b=tmp FI   WHILE b#0 DO tmp=a MOD b a=b b=tmp OD RETURN (a)   BYTE FUNC IsPrimitive(TRIPLE POINTER t) IF Gcd(t.a,t.b)>1 THEN RETURN (0) FI IF Gcd(t.b,t.c)>1 THEN RETURN (0) FI IF Gcd(t.a,t.c)>1 THEN RETURN (0) FI RETURN (1)   PROC FindPrimitives(TRIPLES POINTER arr,res) BYTE ARRAY data(100) INT i TRIPLE POINTER t   Init(res,data) FOR i=0 TO arr.count-1 DO t=GetItemAddr(arr,i) IF IsPrimitive(t) THEN AddItem(res,t) FI OD RETURN   PROC Main() DEFINE LIMIT="100" TRIPLES res,res2   FindTriples(res,LIMIT) PrintF("There are %B pythagorean triples with a perimeter less than %B:%E%E",res.count,LIMIT) PrintTriples(res)   FindPrimitives(res,res2) PrintF("%E%E%E%B of them are primitive:%E%E",res2.count) PrintTriples(res2) RETURN
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.
#Sidef
Sidef
class MiddleSquareMethod(seed, k = 1000) { method next { seed = (seed**2 // k % k**2) } }   var obj = MiddleSquareMethod(675248) say 5.of { obj.next }
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.
#uBasic.2F4tH
uBasic/4tH
If Info("wordsize") < 64 Then Print "This needs a 64-bit uBasic" : End   s = 675248 For i = 1 To 5 Print Set(s, FUNC(_random(s))) Next   End   _random Param (1) : Return (a@*a@/1000%1000000)
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.
#UNIX_Shell
UNIX Shell
seed=675248 random(){ seed=`expr $seed \* $seed / 1000 % 1000000` return seed } for ((i=1;i<=5;i++)); do random echo $? done
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Swift
Swift
import Foundation   struct XorshiftStar { private let magic: UInt64 = 0x2545F4914F6CDD1D private var state: UInt64   init(seed: UInt64) { state = seed }   mutating func nextInt() -> UInt64 { state ^= state &>> 12 state ^= state &<< 25 state ^= state &>> 27   return (state &* magic) &>> 32 }   mutating func nextFloat() -> Float { return Float(nextInt()) / Float(1 << 32) } }   extension XorshiftStar: RandomNumberGenerator, IteratorProtocol, Sequence { mutating func next() -> UInt64 { return nextInt() }   mutating func next() -> UInt64? { return nextInt() } }   for (i, n) in XorshiftStar(seed: 1234567).lazy.enumerated().prefix(5) { print("\(i): \(n)") }   var gen = XorshiftStar(seed: 987654321) var counts = [Float: Int]()   for _ in 0..<100_000 { counts[floorf(gen.nextFloat() * 5), default: 0] += 1 }   print(counts)
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
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 Xorshift_star Generator (pseudo-code) /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class Xorshift use random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ Task Generate a class/set of functions that generates pseudo-random numbers as shown above. Show that the first five integers genrated 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: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 Show your output here, on this page.
#Wren
Wren
import "/big" for BigInt   var Const = BigInt.fromBaseString("2545F4914F6CDD1D", 16) var Mask64 = (BigInt.one << 64) - BigInt.one var Mask32 = (BigInt.one << 32) - BigInt.one   class XorshiftStar { construct new(state) { _state = state & Mask64 }   seed(num) { _state = num & Mask64}   nextInt { var x = _state x = (x ^ (x >> 12)) & Mask64 x = (x ^ (x << 25)) & Mask64 x = (x ^ (x >> 27)) & Mask64 _state = x return (((x * Const) & Mask64) >> 32) & Mask32 }   nextFloat { nextInt.toNum / 2.pow(32) } }   var randomGen = XorshiftStar.new(BigInt.new(1234567)) for (i in 0..4) System.print(randomGen.nextInt)   var counts = List.filled(5, 0) randomGen.seed(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/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.
#Plain_TeX
Plain TeX
This is TeX, Version 3.1415926 (no format preloaded) (q.tex \output {\message {\output \the \output \end }\batchmode }\end
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.
#Ada
Ada
package MRG32KA is type I64 is range -2**63..2**63 - 1; m1 : constant I64 := 2**32 - 209; m2 : constant I64 := 2**32 - 22853;   subtype state_value is I64 range 1..m1;   procedure Seed (seed_state : state_value); function Next_Int return I64; function Next_Float return Long_Float; end MRG32KA;  
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
C
#include <math.h> #include <stdio.h> #include <stdint.h>   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; }   // Constants // First generator const static int64_t a1[3] = { 0, 1403580, -810728 }; const static int64_t m1 = (1LL << 32) - 209; // Second generator const static int64_t a2[3] = { 527612, 0, -1370589 }; const static int64_t m2 = (1LL << 32) - 22853;   const static int64_t d = (1LL << 32) - 209 + 1; // m1 + 1   // the last three values of the first generator static int64_t x1[3]; // the last three values of the second generator static int64_t x2[3];   void seed(int64_t seed_state) { x1[0] = seed_state; x1[1] = 0; x1[2] = 0;   x2[0] = seed_state; x2[1] = 0; x2[2] = 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[2] = x1[1]; x1[1] = x1[0]; x1[0] = x1i;   // keep last three values of the second generator x2[2] = x2[1]; x2[1] = x2[0]; x2[0] = x2i;   return z + 1; }   double next_float() { return (double)next_int() / d; }   int main() { int counts[5] = { 0, 0, 0, 0, 0 }; int i;   seed(1234567); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("\n");   seed(987654321); for (i = 0; i < 100000; i++) { int64_t value = floor(next_float() * 5); counts[value]++; } for (i = 0; i < 5; i++) { printf("%d: %d\n", i, counts[i]); }   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.
#Nim
Nim
import algorithm, sequtils, strutils, tables   const N = 6364136223846793005u64   type PCG32 = object inc: uint64 state: uint64   func seed(gen: var PCG32; seedState, seedSequence: uint64) = gen.inc = seedSequence shl 1 or 1 gen.state = (gen.inc + seedState) * N + gen.inc   func nextInt(gen: var PCG32): uint32 = let xs = uint32((gen.state shr 18 xor gen.state) shr 27) let rot = int32(gen.state shr 59) result = uint32(xs shr rot or xs shl (-rot and 31)) gen.state = gen.state * N + gen.inc   func nextFloat(gen: var PCG32): float = gen.nextInt().float / float(0xFFFFFFFFu32)     when isMainModule:   var gen: PCG32   gen.seed(42, 54) for _ in 1..5: echo gen.nextInt()   echo "" gen.seed(987654321, 1) 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/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.
#Perl
Perl
use strict; use warnings; use feature 'say'; use Math::AnyNum qw(:overload);   package PCG32 {   use constant { mask32 => 2**32 - 1, mask64 => 2**64 - 1, const => 6364136223846793005, };   sub new { my ($class, %opt) = @_; my $seed = $opt{seed} // 1; my $incr = $opt{incr} // 2; $incr = $incr << 1 | 1 & mask64; my $state = (($incr + $seed) * const + $incr) & mask64; bless {incr => $incr, state => $state}, $class; }   sub next_int { my ($self) = @_; my $state = $self->{state}; my $shift = ($state >> 18 ^ $state) >> 27 & mask32; my $rotate = $state >> 59 & mask32; $self->{state} = ($state * const + $self->{incr}) & mask64; ($shift >> $rotate) | $shift << (32 - $rotate) & mask32; }   sub next_float { my ($self) = @_; $self->next_int / 2**32; } }   say "Seed: 42, Increment: 54, first 5 values:"; my $rng = PCG32->new(seed => 42, incr => 54); say $rng->next_int for 1 .. 5;   say "\nSeed: 987654321, Increment: 1, values histogram:"; my %h; $rng = PCG32->new(seed => 987654321, incr => 1); $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.
#J
J
    Filter =: (#~`)(`:6)   B =: *: A =: i. >: i. 2200   S1 =: , B +/ B NB. S1 is a raveled table of the sums of squares S1 =: <:&({:B)Filter S1 NB. remove sums of squares exceeding bound S1 =: ~. S1 NB. remove duplicate entries   S2 =: , B +/ S1 S2 =: <:&({:B)Filter S2 S2 =: ~. S2   RESULT =: (B -.@:e. S2) # A RESULT 1 2 4 5 8 10 16 20 32 40 64 80 128 160 256 320 512 640 1024 1280 2048    
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.
#Java
Java
  import java.util.ArrayList; import java.util.List;   public class PythagoreanQuadruples {   public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); }   // See: https://oeis.org/A094958 private static List<Long> getPythagoreanQuadruples(long max) { List<Long> list = new ArrayList<>(); long n = -1; long m = -1; while ( true ) { long nTest = (long) Math.pow(2, n+1); long mTest = (long) (5L * Math.pow(2, m+1)); long test = 0; if ( nTest > mTest ) { test = mTest; m++; } else { test = nTest; n++; } if ( test < max ) { list.add(test); } else { break; } } return list; }   }  
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
#IS-BASIC
IS-BASIC
100 PROGRAM "Pythagor.bas" 110 OPTION ANGLE DEGREES 120 LET SQ2=SQR(2) 130 SET VIDEO MODE 1:SET VIDEO COLOUR 0:SET VIDEO X 42:SET VIDEO Y 25 140 OPEN #101:"video:" 150 SET PALETTE 0,141 160 DISPLAY #101:AT 1 FROM 1 TO 25 170 PLOT 580,20;ANGLE 90; 180 CALL BROCCOLI(225,10) 190 DO 200 LOOP WHILE INKEY$="" 210 TEXT 220 DEF BROCCOLI(X,Y) 230 IF X<Y THEN EXIT DEF 240 CALL SQUARE(X) 250 PLOT FORWARD X,LEFT 45, 260 CALL BROCCOLI(X/SQ2,Y) 270 PLOT RIGHT 90,FORWARD X/SQ2, 280 CALL BROCCOLI(X/SQ2,Y) 290 PLOT BACK X/SQ2,LEFT 45,BACK X, 300 END DEF 310 DEF SQUARE(X) 320 FOR I=1 TO 4 330 PLOT FORWARD X;RIGHT 90; 340 NEXT 350 END DEF
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
#PicoLisp
PicoLisp
(zero *Split) # global state   (de mod64 (N) (& N `(hex "FFFFFFFFFFFFFFFF")) ) (de mod64+ (A B) (mod64 (+ A B)) ) (de mod64* (A B) (mod64 (* A B)) ) (de roundf (N) # rounds down (/ N (** 10 *Scl)) ) (de nextSplit () (setq *Split (mod64+ *Split `(hex "9e3779b97f4a7c15"))) (let Z *Split (setq Z (mod64* `(hex "bf58476d1ce4e5b9") (x| Z (>> 30 Z))) Z (mod64* `(hex "94d049bb133111eb") (x| Z (>> 27 Z))) ) (x| Z (>> 31 Z)) ) )   (prinl "First 5 numbers:") (setq *Split 1234567) (do 5 (println (nextSplit)) )   (prinl "The counts for 100,000 repetitions are:") (scl 12) (off R) (setq *Split 987654321) (do 100000 (accu 'R (roundf (* 5 (*/ (nextSplit) 1.0 18446744073709551616))) 1 ) ) (mapc println (sort R))
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
#Python
Python
MASK64 = (1 << 64) - 1 C1 = 0x9e3779b97f4a7c15 C2 = 0xbf58476d1ce4e5b9 C3 = 0x94d049bb133111eb       class Splitmix64():   def __init__(self, seed=0): self.state = seed & MASK64   def seed(self, num): self.state = num & MASK64   def next_int(self): "return random int between 0 and 2**64" z = self.state = (self.state + C1) & MASK64 z = ((z ^ (z >> 30)) * C2) & MASK64 z = ((z ^ (z >> 27)) * C3) & MASK64 answer = (z ^ (z >> 31)) & MASK64   return answer   def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 64)     if __name__ == '__main__': random_gen = Splitmix64() 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_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
#Ada
Ada
with Ada.Text_IO;   procedure Pythagorean_Triples is   type Large_Natural is range 0 .. 2**63-1; -- this is the maximum for gnat   procedure New_Triangle(A, B, C: Large_Natural; Max_Perimeter: Large_Natural; Total_Cnt, Primitive_Cnt: in out Large_Natural) is Perimeter: constant Large_Natural := A + B + C; begin if Perimeter <= Max_Perimeter then Primitive_Cnt := Primitive_Cnt + 1; Total_Cnt  := Total_Cnt + Max_Perimeter / Perimeter; New_Triangle(A-2*B+2*C, 2*A-B+2*C, 2*A-2*B+3*C, Max_Perimeter, Total_Cnt, Primitive_Cnt); New_Triangle(A+2*B+2*C, 2*A+B+2*C, 2*A+2*B+3*C, Max_Perimeter, Total_Cnt, Primitive_Cnt); New_Triangle(2*B+2*C-A, B+2*C-2*A, 2*B+3*C-2*A, Max_Perimeter, Total_Cnt, Primitive_Cnt); end if; end New_Triangle;   T_Cnt, P_Cnt: Large_Natural;   begin for I in 1 .. 9 loop T_Cnt := 0; P_Cnt := 0; New_Triangle(3,4,5, 10**I, Total_Cnt => T_Cnt, Primitive_Cnt => P_Cnt); Ada.Text_IO.Put_Line("Up to 10 **" & Integer'Image(I) & " :" & Large_Natural'Image(T_Cnt) & " Triples," & Large_Natural'Image(P_Cnt) & " Primitives"); end loop; end Pythagorean_Triples;