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/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { ITERATIONS = 1000000 delete symbMap delete probMap delete counts initData();   for (i = 0; i < ITERATIONS; i++) { distribute(rand()) } showDistributions()   exit }   function distribute(rnd, cnt, symNum, sym, symPrb) { cnt = length(symbMap) for (symNum = 1; symNum <= cnt; symNum++) { sym = symbMap[symNum]; symPrb = probMap[sym]; rnd -= symPrb; if (rnd <= 0) { counts[sym]++ return; } } }   function showDistributions( s, sym, prb, actSum, expSum, totItr) { actSum = 0.0 expSum = 0.0 totItr = 0 printf "%-7s  %-7s  %-5s  %-5s\n", "symb", "num.", "act.", "expt." print "------- ------- ----- -----" for (s = 1; s <= length(symbMap); s++) { sym = symbMap[s] prb = counts[sym]/ITERATIONS actSum += prb expSum += probMap[sym] totItr += counts[sym] printf "%-7s  %7d  %1.3f  %1.3f\n", sym, counts[sym], prb, probMap[sym] } print "------- ------- ----- -----" printf "Totals:  %7d  %1.3f  %1.3f\n", totItr, actSum, expSum }   function initData( sym) { srand()   probMap["aleph"] = 1.0 / 5.0 probMap["beth"] = 1.0 / 6.0 probMap["gimel"] = 1.0 / 7.0 probMap["daleth"] = 1.0 / 8.0 probMap["he"] = 1.0 / 9.0 probMap["waw"] = 1.0 / 10.0 probMap["zyin"] = 1.0 / 11.0 probMap["heth"] = 1759.0 / 27720.0   symbMap[1] = "aleph" symbMap[2] = "beth" symbMap[3] = "gimel" symbMap[4] = "daleth" symbMap[5] = "he" symbMap[6] = "waw" symbMap[7] = "zyin" symbMap[8] = "heth"   for (sym in probMap) counts[sym] = 0; }  
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333. The problem is to list, for a delimited set of ancestors (from 1 to 99) : - the total of their own ancestors (LEVEL), - their own ancestors (ANCESTORS), - the total of the direct descendants (DESCENDANTS), - all the direct descendants. You only have to consider the prime factors < 100. A grand total of the descendants has to be printed at the end of the list. The task should be accomplished in a reasonable time-frame. Example : 46 = 2*23 --> 2+23 = 25, is the parent of 46. 25 = 5*5 --> 5+5 = 10, is the parent of 25. 10 = 2*5 --> 2+5 = 7, is the parent of 10. 7 is a prime factor and, as such, has no parent. 46 has 3 ancestors (7, 10 and 25). 46 has 557 descendants. The list layout and the output for Parent [46] : [46] Level: 3 Ancestors: 7, 10, 25 Descendants: 557 129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876 Some figures : The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99) Total Descendants 546.986
#Go
Go
package main   import ( "fmt" "sort" )   func getPrimes(max int) []int { if max < 2 { return []int{} } lprimes := []int{2} outer: for x := 3; x <= max; x += 2 { for _, p := range lprimes { if x%p == 0 { continue outer } } lprimes = append(lprimes, x) } return lprimes }   func main() { const maxSum = 99 descendants := make([][]int64, maxSum+1) ancestors := make([][]int, maxSum+1) for i := 0; i <= maxSum; i++ { descendants[i] = []int64{} ancestors[i] = []int{} } primes := getPrimes(maxSum)   for _, p := range primes { descendants[p] = append(descendants[p], int64(p)) for s := 1; s < len(descendants)-p; s++ { temp := make([]int64, len(descendants[s])) for i := 0; i < len(descendants[s]); i++ { temp[i] = int64(p) * descendants[s][i] } descendants[s+p] = append(descendants[s+p], temp...) } }   for _, p := range append(primes, 4) { le := len(descendants[p]) if le == 0 { continue } descendants[p][le-1] = 0 descendants[p] = descendants[p][:le-1] } total := 0   for s := 1; s <= maxSum; s++ { x := descendants[s] sort.Slice(x, func(i, j int) bool { return x[i] < x[j] }) total += len(descendants[s]) index := 0 for ; index < len(descendants[s]); index++ { if descendants[s][index] > int64(maxSum) { break } } for _, d := range descendants[s][:index] { ancestors[d] = append(ancestors[s], s) } if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) { continue } temp := fmt.Sprintf("%v", ancestors[s]) fmt.Printf("%2d: %d Ancestor(s): %-14s", s, len(ancestors[s]), temp) le := len(descendants[s]) if le <= 10 { fmt.Printf("%5d Descendant(s): %v\n", le, descendants[s]) } else { fmt.Printf("%5d Descendant(s): %v\b ...]\n", le, descendants[s][:10]) } } fmt.Println("\nTotal descendants", total) }
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion   call :push 10 "item ten" call :push 2 "item two" call :push 100 "item one hundred" call :push 5 "item five"   call :pop & echo !order! !item! call :pop & echo !order! !item! call :pop & echo !order! !item! call :pop & echo !order! !item! call :pop & echo !order! !item!   goto:eof     :push set temp=000%1 set queu%temp:~-3%=%2 goto:eof   :pop set queu >nul 2>nul if %errorlevel% equ 1 (set order=-1&set item=no more items & goto:eof) for /f "tokens=1,2 delims==" %%a in ('set queu') do set %%a=& set order=%%a& set item=%%~b& goto:next :next set order= %order:~-3% goto:eof
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#F.23
F#
type point = { x:float; y:float } type circle = { center: point; radius: float; }   let new_circle x y r = { center = { x=x; y=y }; radius = r }   let print_circle c = printfn "Circle(x=%.2f, y=%.2f, r=%.2f)" c.center.x c.center.y c.radius   let xyr c = c.center.x, c.center.y, c.radius   let solve_apollonius c1 c2 c3 s1 s2 s3 =   let x1, y1, r1 = xyr c1 let x2, y2, r2 = xyr c2 let x3, y3, r3 = xyr c3   let v11 = 2. * x2 - 2. * x1 let v12 = 2. * y2 - 2. * y1 let v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 let v14 = (2. * s2 * r2) - (2. * s1 * r1)   let v21 = 2. * x3 - 2. * x2 let v22 = 2. * y3 - 2. * y2 let v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 let v24 = (2. * s3 * r3) - (2. * s2 * r2)   let w12 = v12 / v11 let w13 = v13 / v11 let w14 = v14 / v11   let w22 = v22 / v21 - w12 let w23 = v23 / v21 - w13 let w24 = v24 / v21 - w14   let p = - w23 / w22 let q = w24 / w22 let m = - w12 * p - w13 let n = w14 - w12 * q   let a = n*n + q*q - 1. let b = 2.*m*n - 2.*n*x1 + 2.*p*q - 2.*q*y1 + 2.*s1*r1 let c = x1*x1 + m*m - 2.*m*x1 + p*p + y1*y1 - 2.*p*y1 - r1*r1   let d = b * b - 4. * a * c let rs = (- b - (sqrt d)) / (2. * a)   let xs = m + n * rs let ys = p + q * rs   new_circle xs ys rs     [<EntryPoint>] let main argv = let c1 = new_circle 0. 0. 1. let c2 = new_circle 4. 0. 1. let c3 = new_circle 2. 4. 2.   let r1 = solve_apollonius c1 c2 c3 1. 1. 1. print_circle r1   let r2 = solve_apollonius c1 c2 c3 (-1.) (-1.) (-1.) print_circle r2 0
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Make
Make
NAME=$(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))   all: @echo $(NAME)  
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#PicoLisp
PicoLisp
  (de prime? (N Lst) (let S (sqrt N) (for D Lst (T (> D S) T) (T (=0 (% N D)) NIL) ) ) )   (de take (N) (let I 1 (make (link 2) (do (dec N) (until (prime? (inc 'I 2) (made))) (link I) ) ) ) )   # This is a simple approach to calculate primorial may not be the fastest one (de primorial (N) (apply * (take N)) )   #print 1st 10 primorial numbers (for M 10 (prinl "primorial: "(primorial M)))   # print the length of primorial numbers. [prinl (length (primorial (** 10 1)] [prinl (length (primorial (** 10 2)] [prinl (length (primorial (** 10 3)] [prinl (length (primorial (** 10 4)] #The last one takes a very long time to compute. [prinl (length (primorial (** 10 5)]
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
#MATLAB_.2F_Octave
MATLAB / Octave
N= 100; a = 1:N; b = a(ones(N,1),:).^2; b = b+b'; b = sqrt(b); [y,x]=find(b==fix(b)); % test % here some alternative tests % b = b.^(1/k); [y,x]=find(b==fix(b)); % test 2 % [y,x]=find(b==(fix(b.^(1/k)).^k));  % test 3 % b=b.^(1/k); [y,x]=find(abs(b - round(b)) <= 4*eps*b);   z = sqrt(x.^2+y.^2); ix = (z+x+y<100) & (x < y) & (y < z); p = find(gcd(x(ix),y(ix))==1); % find primitive triples   printf('There are %i Pythagorean Triples and %i primitive triples with a perimeter smaller than %i.\n',... sum(ix), length(p), N);
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#JavaScript
JavaScript
if (some_condition) quit();
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#jq
jq
$ jq -n '"Hello", if 1 then error else 2 end' "Hello"
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#SPAD
SPAD
signature RADCATFIELD = sig type real val zero : real val one : real val + : real * real -> real val - : real * real -> real val * : real * real -> real val / : real * real -> real val sign : real -> real val sqrt : real -> real end   functor QR(F: RADCATFIELD) = struct structure A = struct local open Array in fun unitVector n = tabulate (n, fn i => if i=0 then F.one else F.zero) fun map f x = tabulate(length x, fn i => f(sub(x,i))) fun map2 f (x, y) = tabulate(length x, fn i => f(sub(x,i),sub(y,i))) val op + = map2 F.+ val op - = map2 F.- val op * = map2 F.* fun multc(c,x) = array(length x,c)*x fun dot (x,y) = foldl F.+ F.zero (x*y) fun outer f (x,y) = Array2.tabulate Array2.RowMajor (length x, length y, fn (i,j) => f(sub(x,i),sub(y,j))) fun copy x = map (fn x => x) x fun fromVector v = tabulate(Vector.length v, fn i => Vector.sub(v,i)) fun slice(x,i,sz) = let open ArraySlice val s = slice(x,i,sz) in Array.tabulate(length s, fn i => sub(s,i)) end end end structure M = struct local open Array2 in fun map f x = tabulate RowMajor (nRows x, nCols x, fn (i,j) => f(sub(x,i,j))) fun map2 f (x, y) = tabulate RowMajor (nRows x, nCols x, fn (i,j) => f(sub(x,i,j),sub(y,i,j))) fun scalarMatrix(m, x) = tabulate RowMajor (m,m,fn (i,j) => if i=j then x else F.zero) fun multc(c, x) = map (fn xij => F.*(c,xij)) x val op + = map2 F.+ val op - = map2 F.- fun column(x,i) = A.fromVector(Array2.column(x,i)) fun row(x,i) = A.fromVector(Array2.row(x,i)) fun x*y = tabulate RowMajor (nRows x, nCols y, fn (i,j) => A.dot(row(x,i), column(y,j))) fun multa(x,a) = Array.tabulate (nRows x, fn i => A.dot(row(x,i), a)) fun copy x = map (fn x => x) x fun subMatrix(h, i1, i2, j1, j2) = tabulate RowMajor (Int.+(Int.-(i2,i1),1), Int.+(Int.-(j2,j1),1), fn (a,b) => sub(h,Int.+(i1,a),Int.+(j1,b))) fun transpose m = tabulate RowMajor (nCols m, nRows m, fn (i,j) => sub(m,j,i)) fun updateSubMatrix(h,i,j,s) = tabulate RowMajor (nRows s, nCols s, fn (a,b) => update(h,Int.+(i,a),Int.+(j,b),sub(s,a,b))) end end fun toList a = List.tabulate(Array2.nRows a, fn i => List.tabulate(Array2.nCols a, fn j => Array2.sub(a,i,j))) fun householder a = let open Array val m = length a val len = F.sqrt(A.dot(a,a)) val u = A.+(a, A.multc(F.*(len,F.sign(sub(a,0))), A.unitVector m)) val v = A.multc(F./(F.one,sub(u,0)), u) val beta = F./(F.+(F.one,F.one),A.dot(v,v)) in M.-(M.scalarMatrix(m,F.one), M.multc(beta,A.outer F.* (v,v))) end fun qr mat = let open Array2 val (m,n) = dimensions mat val upperIndex = if m=n then Int.-(n,1) else n fun loop(i,qm,rm) = if i=upperIndex then {q=qm,r=rm} else let val x = A.slice(A.fromVector(column(rm,i)),i,NONE) val h = M.scalarMatrix(m,F.one) val _ = M.updateSubMatrix(h,i,i,householder x) in loop(Int.+(i,1), M.*(qm,h), M.*(h,rm)) end in loop(0, M.scalarMatrix(m,F.one), mat) end fun solveUpperTriangular(r,b) = let open Array val n = Array2.nCols r val x = array(n, F.zero) fun loop k = let val index = Int.min(Int.-(n,1),Int.+(k,1)) val _ = update(x,k, F./(F.-(sub(b,k), A.dot(A.slice(x,index,NONE), A.slice(M.row(r,k),index,NONE))), Array2.sub(r,k,k))) in if k=0 then x else loop(Int.-(k,1)) end in loop (Int.-(n,1)) end fun lsqr(a,b) = let val {q,r} = qr a val n = Array2.nCols r in solveUpperTriangular(M.subMatrix(r, 0, Int.-(n,1), 0, Int.-(n,1)), M.multa(M.transpose(q), b)) end fun pow(x,1) = x | pow(x,n) = F.*(x,pow(x,Int.-(n,1))) fun polyfit(x,y,n) = let open Array2 val a = tabulate RowMajor (Array.length x, Int.+(n,1), fn (i,j) => if j=0 then F.one else pow(Array.sub(x,i),j)) in lsqr(a,y) end end
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.
#Raku
Raku
my @count = 0, 0, 1; my $lock = Lock.new; put (1,2);   for 3..17 -> $n { my @even = (2..^$n).grep: * %% 2; my @odd = (3..^$n).grep: so * % 2; @even.permutations.race.map: -> @e { quietly next if @e[0] == 8|14; my $nope = 0; for @odd.permutations -> @o { quietly next unless (@e[0] + @o[0]).is-prime; my @list; for (@list = (flat (roundrobin(@e, @o)), $n)).rotor(2 => -1) { $nope++ and last unless .sum.is-prime; } unless $nope { put '1 ', @list unless @count[$n]; $lock.protect({ @count[$n]++ }); } $nope = 0; } } } put "\n", @count[2..*];
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#8086_Assembly
8086 Assembly
cpu 8086 org 100h section .text jmp demo ;;; Wilson primality test of CX. ;;; Zero flag set if CX prime. Destroys AX, BX, DX. wilson: xor ax,ax ; AX will hold intermediate fac-mod value inc ax mov bx,cx ; BX = factorial loop counter dec bx .loop: mul bx ; DX:AX = AX*BX div cx ; modulus goes in DX mov ax,dx dec bx ; Next value jnz .loop ; If not zero yet, go again inc ax ; fac-mod + 1 equal to input? cmp ax,cx ; Set flags according to result ret ;;; Demo: print primes under 256 demo: mov cx,2 .loop: call wilson ; Is it prime? jnz .next ; If not, try next number mov ax,cx call print ; Otherwise, print the number .next: inc cl ; Next number. jnz .loop ; If <256, try next number ret ;;; Print value in AX using DOS syscall print: mov bp,10 ; Divisor mov bx,numbuf ; Pointer to buffer .digit: xor dx,dx div bp ; Divide AX and get digit in DX add dl,'0' ; Make ASCII dec bx ; Store in buffer mov [bx],dl test ax,ax ; Done yet? jnz .digit ; If not, get next digit mov dx,bx ; Print buffer mov ah,9 ; 9 = MS-DOS syscall to print a string int 21h ret section .data db '*****' ; Space to hold ASCII number for output numbuf: db 13,10,'$'
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#8086_Assembly
8086 Assembly
#!/usr/local/bin/a68g --script #   PRAGMAT portcheck PRAGMAT PR portcheck PR   BEGIN PR heap=256M PR # algol68g pragma # ~ END;   PROC (REAL)REAL s = sin();   SKIP
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Ada
Ada
#!/usr/local/bin/a68g --script #   PRAGMAT portcheck PRAGMAT PR portcheck PR   BEGIN PR heap=256M PR # algol68g pragma # ~ END;   PROC (REAL)REAL s = sin();   SKIP
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   PRAGMAT portcheck PRAGMAT PR portcheck PR   BEGIN PR heap=256M PR # algol68g pragma # ~ END;   PROC (REAL)REAL s = sin();   SKIP
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#BASIC
BASIC
10 TRON: REM activate system trace pragma 20 TROFF: REM deactivate system trace pragma
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of the primes that immediately follow them. and This conspiracy among prime numbers seems, at first glance, to violate a longstanding assumption in number theory: that prime numbers behave much like random numbers. ─── (original authors from Stanford University): ─── Kannan Soundararajan and Robert Lemke Oliver The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime. Task Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed. Observation (Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime. Extra credit Do the same for one hundred million primes. Example for 10,000 primes 10000 first primes. Transitions prime % 10 → next-prime % 10. 1 → 1 count: 365 frequency: 3.65 % 1 → 3 count: 833 frequency: 8.33 % 1 → 7 count: 889 frequency: 8.89 % 1 → 9 count: 397 frequency: 3.97 % 2 → 3 count: 1 frequency: 0.01 % 3 → 1 count: 529 frequency: 5.29 % 3 → 3 count: 324 frequency: 3.24 % 3 → 5 count: 1 frequency: 0.01 % 3 → 7 count: 754 frequency: 7.54 % 3 → 9 count: 907 frequency: 9.07 % 5 → 7 count: 1 frequency: 0.01 % 7 → 1 count: 655 frequency: 6.55 % 7 → 3 count: 722 frequency: 7.22 % 7 → 7 count: 323 frequency: 3.23 % 7 → 9 count: 808 frequency: 8.08 % 9 → 1 count: 935 frequency: 9.35 % 9 → 3 count: 635 frequency: 6.35 % 9 → 7 count: 541 frequency: 5.41 % 9 → 9 count: 379 frequency: 3.79 %
#C
C
#include <assert.h> #include <stdbool.h> #include <stdio.h>   typedef unsigned char byte;   struct Transition { byte a, b; unsigned int c; } transitions[100];   void init() { int i, j; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { int idx = i * 10 + j; transitions[idx].a = i; transitions[idx].b = j; transitions[idx].c = 0; } } }   void record(int prev, int curr) { byte pd = prev % 10; byte cd = curr % 10; int i;   for (i = 0; i < 100; i++) { int z = 0; if (transitions[i].a == pd) { int t = 0; if (transitions[i].b == cd) { transitions[i].c++; break; } } } }   void printTransitions(int limit, int last_prime) { int i;   printf("%d primes, last prime considered: %d\n", limit, last_prime);   for (i = 0; i < 100; i++) { if (transitions[i].c > 0) { printf("%d->%d count: %5d frequency: %.2f\n", transitions[i].a, transitions[i].b, transitions[i].c, 100.0 * transitions[i].c / limit); } } }   bool isPrime(int n) { int s, t, a1, a2;   if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; if (n % 7 == 0) return n == 7; if (n % 11 == 0) return n == 11; if (n % 13 == 0) return n == 13; if (n % 17 == 0) return n == 17; if (n % 19 == 0) return n == 19;   // assuming that addition is faster then multiplication t = 23; a1 = 96; a2 = 216; s = t * t; while (s <= n) { if (n % t == 0) return false;   // first increment s += a1; t += 2; a1 += 24; assert(t * t == s);   if (s <= n) { if (n % t == 0) return false;   // second increment s += a2; t += 4; a2 += 48; assert(t * t == s); } }   return true; }   #define LIMIT 1000000 int main() { int last_prime = 3, n = 5, count = 2;   init(); record(2, 3);   while (count < LIMIT) { if (isPrime(n)) { record(last_prime, n); last_prime = n; count++; } n += 2;   if (count < LIMIT) { if (isPrime(n)) { record(last_prime, n); last_prime = n; count++; } n += 4; } }   printTransitions(LIMIT, last_prime);   return 0; }
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#AWK
AWK
  # syntax: GAWK -f PROPER_DIVISORS.AWK BEGIN { show = 0 # show divisors: 0=no, 1=yes print(" N cnt DIVISORS") for (i=1; i<=20000; i++) { divisors(i) if (i <= 10 || i == 100) { # including 100 as it was an example in task description printf("%5d  %3d  %s\n",i,Dcnt,Dstr) } if (Dcnt < max_cnt) { continue } if (Dcnt > max_cnt) { rec = "" max_cnt = Dcnt } rec = sprintf("%s%5d  %3d  %s\n",rec,i,Dcnt,show?Dstr:"divisors not shown") } printf("%s",rec) exit(0) } function divisors(n, i) { if (n == 1) { Dcnt = 0 Dstr = "" return } Dcnt = Dstr = 1 for (i=2; i<n; i++) { if (n % i == 0) { Dcnt++ Dstr = sprintf("%s %s",Dstr,i) } } return }  
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#BASIC256
BASIC256
dim letters$ = {"aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"} dim actual(8) fill 0 ## all zero by default dim probs = {1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 0} dim cumProbs(8)   cumProbs[0] = probs[0] for i = 1 to 6 cumProbs[i] = cumProbs[i - 1] + probs[i] next i cumProbs[7] = 1.0 probs[7] = 1.0 - cumProbs[6]   n = 1000000 sum = 0.0   for i = 1 to n rnd = rand ## random number where 0 <= rand < 1 begin case case rnd <= cumProbs[0] actual[0] += 1 case rnd <= cumProbs[1] actual[1] += 1 case rnd <= cumProbs[2] actual[2] += 1 case rnd <= cumProbs[3] actual[3] += 1 case rnd <= cumProbs[4] actual[4] += 1 case rnd <= cumProbs[5] actual[5] += 1 case rnd <= cumProbs[6] actual[6] += 1 else actual[7] += 1 end case next i   sumActual = 0   print "Letter", " Actual", "Expected" print "------", "--------", "--------" for i = 0 to 7 print ljust(letters$[i],14," "); print ljust(actual[i]/n,8,"0"); " "; sumActual += actual[i]/n print ljust(probs[i],8,"0") next i   print " ", "--------", "--------" print " ", ljust(sumActual,8,"0"), "1.000000" end
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333. The problem is to list, for a delimited set of ancestors (from 1 to 99) : - the total of their own ancestors (LEVEL), - their own ancestors (ANCESTORS), - the total of the direct descendants (DESCENDANTS), - all the direct descendants. You only have to consider the prime factors < 100. A grand total of the descendants has to be printed at the end of the list. The task should be accomplished in a reasonable time-frame. Example : 46 = 2*23 --> 2+23 = 25, is the parent of 46. 25 = 5*5 --> 5+5 = 10, is the parent of 25. 10 = 2*5 --> 2+5 = 7, is the parent of 10. 7 is a prime factor and, as such, has no parent. 46 has 3 ancestors (7, 10 and 25). 46 has 557 descendants. The list layout and the output for Parent [46] : [46] Level: 3 Ancestors: 7, 10, 25 Descendants: 557 129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876 Some figures : The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99) Total Descendants 546.986
#Haskell
Haskell
{-# LANGUAGE DeriveFunctor #-} import Data.Numbers.Primes (isPrime) import Data.List   ------------------------------------------------------------ -- memoization utilities   type Memo2 a = Memo (Memo a)   data Memo a = Node a (Memo a) (Memo a) deriving Functor   memo :: Integral a => Memo p -> a -> p memo (Node a l r) n | n == 0 = a | odd n = memo l (n `div` 2) | otherwise = memo r (n `div` 2 - 1)   nats :: Integral a => Memo a nats = Node 0 ((+1).(*2) <$> nats) ((*2).(+1) <$> nats)   memoize :: Integral a => (a -> b) -> (a -> b) memoize f = memo (f <$> nats)   memoize2 :: (Integral a, Integral b) => (a -> b -> c) -> (a -> b -> c) memoize2 f = memoize (memoize . f)   ------------------------------------------------------------   partProd = memoize2 partProdM where partProdM x p | p == 0 = [] | x == 0 = [1] | x < 0 = [] | isPrime p = ((p *) <$> partProdM (x - p) p) ++ partProd x (p - 1) | otherwise = partProd x (p - 1)   descendants = memoize descendantsM where descendantsM x = if x == 4 then [] else sort (partProd x (x - 1))   ancestors = memoize ancestorsM where ancestorsM z = concat [ ancestors x ++ [x] | x <- [z-1,z-2..1] , z `elem` descendants x ]   main = do mapM_ (putStrLn . task1) [1..15] putStrLn (task2 46) putStrLn (task2 99) putStrLn task3 where task1 n = show n ++ " ancestors:" ++ show (ancestors n) ++ " descendants:" ++ show (descendants n) task2 n = show n ++ " has " ++ show (length (ancestors n)) ++ " ancestors, " ++ show (length (descendants n)) ++ " descendants." task3 = "Total ancestors up to 99: " ++ show (sum $ length . ancestors <$> [1..99]) ++ "\nTotal descendants up to 99: " ++ show (sum $ length . descendants <$> [1..99])
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#C
C
#include <stdio.h> #include <stdlib.h>   typedef struct { int priority; char *data; } node_t;   typedef struct { node_t *nodes; int len; int size; } heap_t;   void push (heap_t *h, int priority, char *data) { if (h->len + 1 >= h->size) { h->size = h->size ? h->size * 2 : 4; h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t)); } int i = h->len + 1; int j = i / 2; while (i > 1 && h->nodes[j].priority > priority) { h->nodes[i] = h->nodes[j]; i = j; j = j / 2; } h->nodes[i].priority = priority; h->nodes[i].data = data; h->len++; }   char *pop (heap_t *h) { int i, j, k; if (!h->len) { return NULL; } char *data = h->nodes[1].data;   h->nodes[1] = h->nodes[h->len];   h->len--;   i = 1; while (i!=h->len+1) { k = h->len+1; j = 2 * i; if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) { k = j; } if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) { k = j + 1; } h->nodes[i] = h->nodes[k]; i = k; } return data; }   int main () { heap_t *h = (heap_t *)calloc(1, sizeof (heap_t)); push(h, 3, "Clear drains"); push(h, 4, "Feed cat"); push(h, 5, "Make tea"); push(h, 1, "Solve RC tasks"); push(h, 2, "Tax return"); int i; for (i = 0; i < 5; i++) { printf("%s\n", pop(h)); } return 0; }  
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#Fortran
Fortran
program Apollonius implicit none   integer, parameter :: dp = selected_real_kind(15)   type circle real(dp) :: x real(dp) :: y real(dp) :: radius end type   type(circle) :: c1 , c2, c3, r   c1 = circle(0.0, 0.0, 1.0) c2 = circle(4.0, 0.0, 1.0) c3 = circle(2.0, 4.0, 2.0)   write(*, "(a,3f12.8))") "External tangent:", SolveApollonius(c1, c2, c3, 1, 1, 1) write(*, "(a,3f12.8))") "Internal tangent:", SolveApollonius(c1, c2, c3, -1, -1, -1)   contains   function SolveApollonius(c1, c2, c3, s1, s2, s3) result(res) type(circle) :: res type(circle), intent(in) :: c1, c2, c3 integer, intent(in) :: s1, s2, s3   real(dp) :: x1, x2, x3, y1, y2, y3, r1, r2, r3 real(dp) :: v11, v12, v13, v14 real(dp) :: v21, v22, v23, v24 real(dp) :: w12, w13, w14 real(dp) :: w22, w23, w24 real(dp) :: p, q, m, n, a, b, c, det   x1 = c1%x; x2 = c2%x; x3 = c3%x y1 = c1%y; y2 = c2%y; y3 = c3%y r1 = c1%radius; r2 = c2%radius; r3 = c3%radius   v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 - 2*s1*r1   v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 v24 = 2*s3*r3 - 2*s2*r2   w12 = v12/v11 w13 = v13/v11 w14 = v14/v11   w22 = v22/v21-w12 w23 = v23/v21-w13 w24 = v24/v21-w14   p = -w23/w22 q = w24/w22 m = -w12*P - w13 n = w14 - w12*q   a = n*n + q*q - 1 b = 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1 c = x1*x1 + m*m - 2*m*x1 + p*p + y1*y1 - 2*p*y1 - r1*r1   det = b*b - 4*a*c res%radius = (-b-sqrt(det)) / (2*a) res%x = m + n*res%radius res%y = p + q*res%radius   end function end program
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
#!/usr/bin/env MathKernel -script ScriptName[] = Piecewise[ { {"Interpreted", Position[$CommandLine, "-script", 1] == {}} }, $CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]] ] Program = ScriptName[]; Print["Program: " <> Program]
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Mercury
Mercury
:- module program_name. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation.   main(!IO) :-  % The first argument is used as the program name if it is not otherwise  % available. (We could also have used the predicate io.progname_base/4  % if we did not want path preceding the program name.) io.progname("", ProgName, !IO), io.print_line(ProgName, !IO).   :- end_module program_name.
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#Python
Python
from pyprimes import nprimes from functools import reduce     primelist = list(nprimes(1000001)) # [2, 3, 5, ...]   def primorial(n): return reduce(int.__mul__, primelist[:n], 1)   if __name__ == '__main__': print('First ten primorals:', [primorial(n) for n in range(10)]) for e in range(7): n = 10**e print('primorial(%i) has %i digits' % (n, len(str(primorial(n)))))
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#Racket
Racket
#lang racket   (require (except-in math/number-theory nth-prime))   (define-syntax-rule (define/cache (name arg) body ...) (begin (define cache (make-hash)) (define (name arg) (hash-ref! cache arg (lambda () body ...)))))   (define (num-length n)  ;warning: this defines (num-length 0) as 0 (if (zero? n) 0 (add1 (num-length (quotient n 10)))))   (define/cache (nth-prime n) (if (zero? n) 2 (for/first ([p (in-naturals (add1 (nth-prime (sub1 n))))] #:when (prime? p)) p)))   (define (primorial n) (if (zero? n) 1 (* (primorial (sub1 n)) (nth-prime (sub1 n)))))   (displayln (for/list ([i (in-range 10)]) (primorial i)))   (for ([i (in-range 1 6)]) (printf "Primorial(10^~a) has ~a digits.\n" i (num-length (primorial (expt 10 i)))))
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Mercury
Mercury
  :- module comprehension. :- interface. :- import_module io. :- import_module int.   :- type triple ---> triple(int, int, int).   :- pred pythTrip(int::in,triple::out) is nondet. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module solutions.   pythTrip(Limit,triple(X,Y,Z)) :- nondet_int_in_range(1,Limit,X), nondet_int_in_range(X,Limit,Y), nondet_int_in_range(Y,Limit,Z), pow(Z,2) = pow(X,2) + pow(Y,2).   main(!IO) :- solutions((pred(Triple::out) is nondet :- pythTrip(20,Triple)),Result), write(Result,!IO).  
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Jsish
Jsish
assert(0 == 1);   if (problem) exit(1);
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Julia
Julia
  quit() # terminates program normally, with its child processes. See also exit(0).  
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#Standard_ML
Standard ML
signature RADCATFIELD = sig type real val zero : real val one : real val + : real * real -> real val - : real * real -> real val * : real * real -> real val / : real * real -> real val sign : real -> real val sqrt : real -> real end   functor QR(F: RADCATFIELD) = struct structure A = struct local open Array in fun unitVector n = tabulate (n, fn i => if i=0 then F.one else F.zero) fun map f x = tabulate(length x, fn i => f(sub(x,i))) fun map2 f (x, y) = tabulate(length x, fn i => f(sub(x,i),sub(y,i))) val op + = map2 F.+ val op - = map2 F.- val op * = map2 F.* fun multc(c,x) = array(length x,c)*x fun dot (x,y) = foldl F.+ F.zero (x*y) fun outer f (x,y) = Array2.tabulate Array2.RowMajor (length x, length y, fn (i,j) => f(sub(x,i),sub(y,j))) fun copy x = map (fn x => x) x fun fromVector v = tabulate(Vector.length v, fn i => Vector.sub(v,i)) fun slice(x,i,sz) = let open ArraySlice val s = slice(x,i,sz) in Array.tabulate(length s, fn i => sub(s,i)) end end end structure M = struct local open Array2 in fun map f x = tabulate RowMajor (nRows x, nCols x, fn (i,j) => f(sub(x,i,j))) fun map2 f (x, y) = tabulate RowMajor (nRows x, nCols x, fn (i,j) => f(sub(x,i,j),sub(y,i,j))) fun scalarMatrix(m, x) = tabulate RowMajor (m,m,fn (i,j) => if i=j then x else F.zero) fun multc(c, x) = map (fn xij => F.*(c,xij)) x val op + = map2 F.+ val op - = map2 F.- fun column(x,i) = A.fromVector(Array2.column(x,i)) fun row(x,i) = A.fromVector(Array2.row(x,i)) fun x*y = tabulate RowMajor (nRows x, nCols y, fn (i,j) => A.dot(row(x,i), column(y,j))) fun multa(x,a) = Array.tabulate (nRows x, fn i => A.dot(row(x,i), a)) fun copy x = map (fn x => x) x fun subMatrix(h, i1, i2, j1, j2) = tabulate RowMajor (Int.+(Int.-(i2,i1),1), Int.+(Int.-(j2,j1),1), fn (a,b) => sub(h,Int.+(i1,a),Int.+(j1,b))) fun transpose m = tabulate RowMajor (nCols m, nRows m, fn (i,j) => sub(m,j,i)) fun updateSubMatrix(h,i,j,s) = tabulate RowMajor (nRows s, nCols s, fn (a,b) => update(h,Int.+(i,a),Int.+(j,b),sub(s,a,b))) end end fun toList a = List.tabulate(Array2.nRows a, fn i => List.tabulate(Array2.nCols a, fn j => Array2.sub(a,i,j))) fun householder a = let open Array val m = length a val len = F.sqrt(A.dot(a,a)) val u = A.+(a, A.multc(F.*(len,F.sign(sub(a,0))), A.unitVector m)) val v = A.multc(F./(F.one,sub(u,0)), u) val beta = F./(F.+(F.one,F.one),A.dot(v,v)) in M.-(M.scalarMatrix(m,F.one), M.multc(beta,A.outer F.* (v,v))) end fun qr mat = let open Array2 val (m,n) = dimensions mat val upperIndex = if m=n then Int.-(n,1) else n fun loop(i,qm,rm) = if i=upperIndex then {q=qm,r=rm} else let val x = A.slice(A.fromVector(column(rm,i)),i,NONE) val h = M.scalarMatrix(m,F.one) val _ = M.updateSubMatrix(h,i,i,householder x) in loop(Int.+(i,1), M.*(qm,h), M.*(h,rm)) end in loop(0, M.scalarMatrix(m,F.one), mat) end fun solveUpperTriangular(r,b) = let open Array val n = Array2.nCols r val x = array(n, F.zero) fun loop k = let val index = Int.min(Int.-(n,1),Int.+(k,1)) val _ = update(x,k, F./(F.-(sub(b,k), A.dot(A.slice(x,index,NONE), A.slice(M.row(r,k),index,NONE))), Array2.sub(r,k,k))) in if k=0 then x else loop(Int.-(k,1)) end in loop (Int.-(n,1)) end fun lsqr(a,b) = let val {q,r} = qr a val n = Array2.nCols r in solveUpperTriangular(M.subMatrix(r, 0, Int.-(n,1), 0, Int.-(n,1)), M.multa(M.transpose(q), b)) end fun pow(x,1) = x | pow(x,n) = F.*(x,pow(x,Int.-(n,1))) fun polyfit(x,y,n) = let open Array2 val a = tabulate RowMajor (Array.length x, Int.+(n,1), fn (i,j) => if j=0 then F.one else pow(Array.sub(x,i),j)) in lsqr(a,y) end end
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.
#Rust
Rust
fn is_prime(n: u32) -> bool { assert!(n < 64); ((1u64 << n) & 0x28208a20a08a28ac) != 0 }   fn prime_triangle_row(a: &mut [u32]) -> bool { if a.len() == 2 { return is_prime(a[0] + a[1]); } for i in (1..a.len() - 1).step_by(2) { if is_prime(a[0] + a[i]) { a.swap(i, 1); if prime_triangle_row(&mut a[1..]) { return true; } a.swap(i, 1); } } false }   fn prime_triangle_count(a: &mut [u32]) -> u32 { let mut count = 0; if a.len() == 2 { if is_prime(a[0] + a[1]) { count += 1; } } else { for i in (1..a.len() - 1).step_by(2) { if is_prime(a[0] + a[i]) { a.swap(i, 1); count += prime_triangle_count(&mut a[1..]); a.swap(i, 1); } } } count }   fn print(a: &[u32]) { if a.is_empty() { return; } print!("{:2}", a[0]); for x in &a[1..] { print!(" {:2}", x); } println!(); }   fn main() { use std::time::Instant; let start = Instant::now(); for n in 2..21 { let mut a: Vec<u32> = (1..=n).collect(); if prime_triangle_row(&mut a) { print(&a); } } println!(); for n in 2..21 { let mut a: Vec<u32> = (1..=n).collect(); if n > 2 { print!(" "); } print!("{}", prime_triangle_count(&mut a)); } println!(); let time = start.elapsed(); println!("\nElapsed time: {} milliseconds", time.as_millis()); }
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.
#Swift
Swift
import Foundation   func isPrime(_ n: Int) -> Bool { guard n > 0 && n < 64 else { return false } return ((UInt64(1) << n) & 0x28208a20a08a28ac) != 0 }   func primeTriangleRow(_ a: inout [Int], start: Int, length: Int) -> Bool { if length == 2 { return isPrime(a[start] + a[start + 1]) } for i in stride(from: 1, to: length - 1, by: 2) { let index = start + i if isPrime(a[start] + a[index]) { a.swapAt(index, start + 1) if primeTriangleRow(&a, start: start + 1, length: length - 1) { return true } a.swapAt(index, start + 1) } } return false }   func primeTriangleCount(_ a: inout [Int], start: Int, length: Int) -> Int { var count = 0 if length == 2 { if isPrime(a[start] + a[start + 1]) { count += 1 } } else { for i in stride(from: 1, to: length - 1, by: 2) { let index = start + i if isPrime(a[start] + a[index]) { a.swapAt(index, start + 1) count += primeTriangleCount(&a, start: start + 1, length: length - 1) a.swapAt(index, start + 1) } } } return count }   func printRow(_ a: [Int]) { if a.count == 0 { return } print(String(format: "%2d", a[0]), terminator: "") for x in a[1...] { print(String(format: " %2d", x), terminator: "") } print() }   let startTime = CFAbsoluteTimeGetCurrent()   for n in 2...20 { var a = Array(1...n) if primeTriangleRow(&a, start: 0, length: n) { printRow(a) } } print()   for n in 2...20 { var a = Array(1...n) if n > 2 { print(" ", terminator: "") } print("\(primeTriangleCount(&a, start: 0, length: n))", terminator: "") } print()   let endTime = CFAbsoluteTimeGetCurrent() print("\nElapsed time: \(endTime - startTime) seconds")
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Ada
Ada
-- -- Determine primality using Wilon's theorem. -- Uses the approach from Algol W -- allowing large primes without the use of big numbers. -- with Ada.Text_IO; use Ada.Text_IO;   procedure Main is type u_64 is mod 2**64; package u_64_io is new modular_io (u_64); use u_64_io;   function Is_Prime (n : u_64) return Boolean is fact_Mod_n : u_64 := 1; begin if n < 2 then return False; end if; for i in 2 .. n - 1 loop fact_Mod_n := (fact_Mod_n * i) rem n; end loop; return fact_Mod_n = n - 1; end Is_Prime;   num : u_64 := 1; type cols is mod 12; count : cols := 0; begin while num < 500 loop if Is_Prime (num) then if count = 0 then New_Line; end if; Put (Item => num, Width => 6); count := count + 1; end if; num := num + 1; end loop; end Main;    
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#ALGOL_68
ALGOL 68
BEGIN # find primes using Wilson's theorem: # # p is prime if ( ( p - 1 )! + 1 ) mod p = 0 #   # returns true if p is a prime by Wilson's theorem, false otherwise # # computes the factorial mod p at each stage, so as to # # allow numbers whose factorial won't fit in 32 bits # PROC is wilson prime = ( INT p )BOOL: BEGIN INT factorial mod p := 1; FOR i FROM 2 TO p - 1 DO factorial mod p *:= i MODAB p OD; factorial mod p = p - 1 END # is wilson prime # ;   FOR i TO 100 DO IF is wilson prime( i ) THEN print( ( " ", whole( i, 0 ) ) ) FI OD END
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#C
C
  /*Almost every C program has the below line, the #include preprocessor directive is used to instruct the compiler which files to load before compiling the program.   All preprocessor commands begin with # */ #include<stdio.h>   /*The #define preprocessor directive is often used to create abbreviations for code segments*/ #define Hi printf("Hi There.");   /*It can be used, or misused, for rather innovative uses*/   #define start int main(){ #define end return 0;}   start   Hi   /*And here's the nice part, want your compiler to talk to you ? Just use the #warning pragma if you are using a C99 compliant compiler like GCC*/ #warning "Don't you have anything better to do ?"   #ifdef __unix__ #warning "What are you doing still working on Unix ?" printf("\nThis is an Unix system."); #elif _WIN32 #warning "You couldn't afford a 64 bit ?" printf("\nThis is a 32 bit Windows system."); #elif _WIN64 #warning "You couldn't afford an Apple ?" printf("\nThis is a 64 bit Windows system."); #endif   end   /*Enlightened ?*/  
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Common_Lisp
Common Lisp
? *features* (:EASYGUI :ASDF2 :ASDF :HEMLOCK :APPLE-OBJC-2.0 :APPLE-OBJC :PRIMARY-CLASSES :COMMON-LISP :OPENMCL :CCL :CCL-1.2 :CCL-1.3 :CCL-1.4 :CCL-1.5 :CCL-1.6 :CCL-1.7 :CCL-1.8 :CLOZURE :CLOZURE-COMMON-LISP :ANSI-CL :UNIX :OPENMCL-UNICODE-STRINGS :OPENMCL-NATIVE-THREADS :OPENMCL-PARTIAL-MOP :MCL-COMMON-MOP-SUBSET :OPENMCL-MOP-2 :OPENMCL-PRIVATE-HASH-TABLES :X86-64 :X86_64 :X86-TARGET :X86-HOST :X8664-TARGET :X8664-HOST :DARWIN-HOST :DARWIN-TARGET :DARWINX86-TARGET :DARWINX8664-TARGET :DARWINX8664-HOST :64-BIT-TARGET :64-BIT-HOST :DARWIN :LITTLE-ENDIAN-TARGET :LITTLE-ENDIAN-HOST)
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#D
D
-compile( [compressed, {inline,[pi/0]}] ).
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Erlang
Erlang
-compile( [compressed, {inline,[pi/0]}] ).
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Factor
Factor
// +build <expression>
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of the primes that immediately follow them. and This conspiracy among prime numbers seems, at first glance, to violate a longstanding assumption in number theory: that prime numbers behave much like random numbers. ─── (original authors from Stanford University): ─── Kannan Soundararajan and Robert Lemke Oliver The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime. Task Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed. Observation (Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime. Extra credit Do the same for one hundred million primes. Example for 10,000 primes 10000 first primes. Transitions prime % 10 → next-prime % 10. 1 → 1 count: 365 frequency: 3.65 % 1 → 3 count: 833 frequency: 8.33 % 1 → 7 count: 889 frequency: 8.89 % 1 → 9 count: 397 frequency: 3.97 % 2 → 3 count: 1 frequency: 0.01 % 3 → 1 count: 529 frequency: 5.29 % 3 → 3 count: 324 frequency: 3.24 % 3 → 5 count: 1 frequency: 0.01 % 3 → 7 count: 754 frequency: 7.54 % 3 → 9 count: 907 frequency: 9.07 % 5 → 7 count: 1 frequency: 0.01 % 7 → 1 count: 655 frequency: 6.55 % 7 → 3 count: 722 frequency: 7.22 % 7 → 7 count: 323 frequency: 3.23 % 7 → 9 count: 808 frequency: 8.08 % 9 → 1 count: 935 frequency: 9.35 % 9 → 3 count: 635 frequency: 6.35 % 9 → 7 count: 541 frequency: 5.41 % 9 → 9 count: 379 frequency: 3.79 %
#C.23
C#
using System;   namespace PrimeConspiracy { class Program { static void Main(string[] args) { const int limit = 1_000_000; const int sieveLimit = 15_500_000;   int[,] buckets = new int[10, 10]; int prevDigit = 2; bool[] notPrime = Sieve(sieveLimit);   for (int n = 3, primeCount = 1; primeCount < limit; n++) { if (notPrime[n]) continue;   int digit = n % 10; buckets[prevDigit, digit]++; prevDigit = digit; primeCount++; }   for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (buckets[i, j] != 0) { Console.WriteLine("{0} -> {1} count: {2,5:d} frequency : {3,6:0.00%}", i, j, buckets[i, j], 1.0 * buckets[i, j] / limit); } } } }   public static bool[] Sieve(int limit) { bool[] composite = new bool[limit]; composite[0] = composite[1] = true;   int max = (int)Math.Sqrt(limit); for (int n = 2; n <= max; n++) { if (!composite[n]) { for (int k = n * n; k < limit; k += n) { composite[k] = true; } } }   return composite; } } }
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#BASIC
BASIC
FUNCTION CountProperDivisors (number) IF number < 2 THEN CountProperDivisors = 0 count = 0 FOR i = 1 TO number \ 2 IF number MOD i = 0 THEN count = count + 1 NEXT i CountProperDivisors = count END FUNCTION   SUB ListProperDivisors (limit) IF limit < 1 THEN EXIT SUB FOR i = 1 TO limit PRINT USING "## ->"; i; IF i = 1 THEN PRINT " (None)"; FOR j = 1 TO i \ 2 IF i MOD j = 0 THEN PRINT " "; j; NEXT j PRINT NEXT i END SUB   most = 1 maxCount = 0   PRINT "The proper divisors of the following numbers are: "; CHR$(10) ListProperDivisors (10)   FOR n = 2 TO 20000 '' It is extremely slow in this loop count = CountProperDivisors(n) IF count > maxCount THEN maxCount = count most = n END IF NEXT n   PRINT PRINT most; " has the most proper divisors, namely "; maxCount END
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#BBC_BASIC
BBC BASIC
DIM item$(7), prob(7), cnt%(7) item$() = "aleph","beth","gimel","daleth","he","waw","zayin","heth" prob() = 1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720 IF ABS(SUM(prob())-1) > 1E-6 ERROR 100, "Probabilities don't sum to 1"   FOR trial% = 1 TO 1E6 r = RND(1) p = 0 FOR i% = 0 TO DIM(prob(),1) p += prob(i%) IF r < p cnt%(i%) += 1 : EXIT FOR NEXT NEXT   @% = &2060A PRINT "Item actual theoretical" FOR i% = 0 TO DIM(item$(),1) PRINT item$(i%), cnt%(i%)/1E6, prob(i%) NEXT
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#C
C
#include <stdio.h> #include <stdlib.h>   /* pick a random index from 0 to n-1, according to probablities listed in p[] which is assumed to have a sum of 1. The values in the probablity list matters up to the point where the sum goes over 1 */ int rand_idx(double *p, int n) { double s = rand() / (RAND_MAX + 1.0); int i; for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++); return i; }   #define LEN 8 #define N 1000000 int main() { const char *names[LEN] = { "aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth" }; double s, p[LEN] = { 1./5, 1./6, 1./7, 1./8, 1./9, 1./10, 1./11, 1e300 }; int i, count[LEN] = {0};   for (i = 0; i < N; i++) count[rand_idx(p, LEN)] ++;   printf(" Name Count Ratio Expected\n"); for (i = 0, s = 1; i < LEN; s -= p[i++]) printf("%6s%7d %7.4f%% %7.4f%%\n", names[i], count[i], (double)count[i] / N * 100, ((i < LEN - 1) ? p[i] : s) * 100);   return 0; }
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333. The problem is to list, for a delimited set of ancestors (from 1 to 99) : - the total of their own ancestors (LEVEL), - their own ancestors (ANCESTORS), - the total of the direct descendants (DESCENDANTS), - all the direct descendants. You only have to consider the prime factors < 100. A grand total of the descendants has to be printed at the end of the list. The task should be accomplished in a reasonable time-frame. Example : 46 = 2*23 --> 2+23 = 25, is the parent of 46. 25 = 5*5 --> 5+5 = 10, is the parent of 25. 10 = 2*5 --> 2+5 = 7, is the parent of 10. 7 is a prime factor and, as such, has no parent. 46 has 3 ancestors (7, 10 and 25). 46 has 557 descendants. The list layout and the output for Parent [46] : [46] Level: 3 Ancestors: 7, 10, 25 Descendants: 557 129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876 Some figures : The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99) Total Descendants 546.986
#J
J
require'strings files'   family=:3 :0 M. if. 2>y do. i.0 NB. no primes less than 2 else. p=. i.&.(p:inv) y (y#~1 p:y),~.;p (* family)&.>y-p end. )   familytree=: +/@q:^:a: ::(''"_)   descendants=: family -. ] ancestors=: 1 }. familytree level=: #@ancestors"0   taskfmt=:'None'"_^:(0=#)@rplc&(' ';', ')@":   task1=:3 :0 text=. '[',(":y),'] Level: ',(":level y),LF text=. text,'Ancestors: ',(taskfmt /:~ancestors y),LF if. #descendants y do. text=. text,'Descendants: ',(":#descendants y),LF text=. text,(taskfmt /:~descendants y),LF else. text=. text,'Descendants: None',LF end. text=. text,LF )   task=:3 :0 tot=. 'Total descendants ',(":#@; descendants&.> 1+i.y),LF ((;task1&.>1+i.y),tot) fwrite jpath '~user/temp/Ancestors.txt' )   task 99
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#C.23
C#
using System; using System.Collections.Generic;   namespace PriorityQueueExample { class Program { static void Main(string[] args) { // Starting with .NET 6.0 preview 2 (released March 11th, 2021), there's a built-in priority queue var p = new PriorityQueue<string, int>(); p.Enqueue("Clear drains", 3); p.Enqueue("Feed cat", 4); p.Enqueue("Make tea", 5); p.Enqueue("Solve RC tasks", 1); p.Enqueue("Tax return", 2); while (p.TryDequeue(out string task, out int priority)) { Console.WriteLine($"{priority}\t{task}"); } } } }   /* Output:   1 Solve RC tasks 2 Tax return 3 Clear drains 4 Feed cat 5 Make tea   */
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#FreeBASIC
FreeBASIC
  Dim As String circle1 = " 0.000, 0.000, 1.000" Dim As String circle2 = " 4.000, 0.000, 1.000" Dim As String circle3 = " 2.000, 4.000, 2.000"   Sub ApolloniusSolver(c1 As String, c2 As String, c3 As String, s1 As Single, s2 As Single, s3 As Single) Dim As Single x1, x2, x3, y1, y2, y3, r1, r2, r3 Dim As Single v11, v12, v13, v14, v21, v22, v23, v24, w12, w13, w14 Dim As Single w22, w23, w24,P, Q, M, N, a, b, c, D Dim As Single Radius, XPos, YPos   x1 = Val(Mid(c1, 3, 1)): y1 = Val(Mid(c1, 11, 1)): r1 = Val(Mid(c1, 19, 1)) x2 = Val(Mid(c2, 3, 1)): y2 = Val(Mid(c2, 11, 1)): r2 = Val(Mid(c2, 19, 1)) x3 = Val(Mid(c3, 3, 1)): y3 = Val(Mid(c3, 11, 1)): r3 = Val(Mid(c3, 19, 1))   v11 = 2 * x2 - 2 * x1 v12 = 2 * y2 - 2* y1 v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2 v14 = 2 * s2 * r2 - 2 * s1 * r1   v21 = 2 * x3 - 2 * x2 v22 = 2 * y3 - 2 * y2 v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3 v24 = 2 * s3 * r3 - 2 * s2 * r2   w12 = v12 / v11 w13 = v13 / v11 w14 = v14 / v11   w22 = v22 / v21 - w12 w23 = v23 / v21 - w13 w24 = v24 / v21 - w14   P = 0 - w23 / w22 Q = w24 / w22 M = 0 - w12 * P - w13 N = w14 - w12 * Q   a = N * N + Q * Q - 1 b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1 c = x1 * x1 + M * M -2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1   D = b * b - 4 * a * c   Radius = (0 - b - Sqr(D)) / (2 * a) XPos = M + N * Radius YPos = P + Q * Radius   Print Using " ##.###, ##.###, ##.###"; XPos; YPos; Radius End Sub   Print " x_pos y_pos radius" Print circle1 Print circle2 Print circle3 Print Print "R1: " : ApolloniusSolver(circle1, circle2, circle3, 1, 1, 1) Print "R2: " : ApolloniusSolver(circle1, circle2, circle3, -1, -1, -1) Sleep  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Mozart.2FOz
Mozart/Oz
all: test   test: scriptname ./scriptname   scriptname: scriptname.oz ozc -x scriptname.oz   clean: -rm scriptname -rm *.exe
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Nanoquery
Nanoquery
println args[1]
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#Raku
Raku
use Math::Primesieve;   my $sieve = Math::Primesieve.new; my @primes = $sieve.primes(10_000_000);   sub primorial($n) { [*] @primes[^$n] }   say "First ten primorials: {(primorial $_ for ^10)}"; say "primorial(10^$_) has {primorial(10**$_).chars} digits" for 1..5;
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#REXX
REXX
/*REXX program computes some primorial numbers for low numbers, and for various 10^n.*/ parse arg N H . /*get optional arguments: N, L, H */ if N=='' | N==',' then N= 10 /*Not specified? Then use the default.*/ if H=='' | H==',' then H= 100000 /* " " " " " " */ numeric digits 600000 /*be able to handle gihugic numbers. */ w= length( commas( digits() ) ) /*W: width of the largest commatized #*/ @.=.; @.0= 1; @.1= 2; @.2= 3; @.3= 5; @.4= 7; @.5= 11; @.6= 13 /*some low primes.*/ s.1= 4; s.2= 9; s.3= 25; s.4= 49; s.5= 121; s.6= 169 /*squared primes. */ #= 6 /*number of primes*/ do j=0 for N /*calculate the first N primorial #s.*/ say right(j, length(N))th(j) " primorial is: " right(commas(primorial(j) ), N+2) end /*j*/ say iw= length( commas(H) ) + 2 /*IW: width of largest commatized index*/ p= 1 /*initialize the first multiplier for P*/ do k=1 for H /*process a large range of numbers. */ p= p * prime(k) /*calculate the next primorial number. */ parse var k L 2 '' -1 R /*get the left and rightmost dec digits*/ if R\==0 then iterate /*if right─most decimal digit\==0, skip*/ if L\==1 then iterate /* " left─most " " \==1, " */ if strip(k, , 0)\==1 then iterate /*Not a power of 10? Then skip this K.*/ say right( commas(k), iw)th(k) ' primorial number length in decimal digits is:' , right( commas( length(p) ), w) end /*k*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _ th: parse arg th; return word('th st nd rd', 1+ (th//10)*(th//100%10\==1)*(th//10<4)) /*──────────────────────────────────────────────────────────────────────────────────────*/ primorial: procedure expose @. s. #; parse arg y;  != 1 /*obtain the arg Y. */ do p=0 to y;  != ! * prime(p) /*calculate product. */ end /*p*/; return ! /*return with the #. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ prime: procedure expose @. s. #; parse arg n; if @.n\==. then return @.n numeric digits 9 /*limit digs to min.*/ do j=@.#+2 by 2 /*start looking at #*/ if j//2==0 then iterate; if j//3==0 then iterate /*divisible by 2│3 ?*/ parse var j '' -1 _; if _==5 then iterate /*right─most dig≡5? */ if j//7==0 then iterate; if j//11==0 then iterate /*divisible by 7│11?*/ do k=6 while s.k<=j; if j//@.k==0 then iterate j /*divide by primes. */ end /*k*/ #= # + 1; @.#= j; s.#= j * j; return j /*next prime; return*/ end /*j*/
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
#Modula-3
Modula-3
MODULE PyTriple64 EXPORTS Main;   IMPORT IO, Fmt;   VAR tcnt, pcnt, max, i: INTEGER;   PROCEDURE NewTriangle(a, b, c: INTEGER; VAR tcount, pcount: INTEGER) = VAR perim := a + b + c; BEGIN IF perim <= max THEN pcount := pcount + 1; tcount := tcount + max DIV perim; NewTriangle(a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c, tcount, pcount); NewTriangle(a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c, tcount, pcount); NewTriangle(2*b+2*c-a, b+2*c-2*a, 2*b+3*c-2*a, tcount, pcount); END; END NewTriangle;   BEGIN i := 100;   REPEAT max := i; tcnt := 0; pcnt := 0; NewTriangle(3, 4, 5, tcnt, pcnt); IO.Put(Fmt.Int(i) & ": " & Fmt.Int(tcnt) & " Triples, " & Fmt.Int(pcnt) & " Primitives\n"); i := i * 10; UNTIL i = 10000000; END PyTriple64.
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { val problem = true if (problem) System.exit(1) // non-zero code passed to OS to indicate a problem println("Program terminating normally") // this line will not be executed }
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Lasso
Lasso
#!/usr/bin/lasso9 //[   handle => { stdoutnl('The end is here') }   stdoutnl('Starting execution')   abort   stdoutnl('Ending execution')
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#Stata
Stata
mata : qrd(a=(12,-51,4\6,167,-68\-4,24,-41),q=.,r=.)   : a 1 2 3 +-------------------+ 1 | 12 -51 4 | 2 | 6 167 -68 | 3 | -4 24 -41 | +-------------------+   : q 1 2 3 +----------------------------------------------+ 1 | -.8571428571 .3942857143 .3314285714 | 2 | -.4285714286 -.9028571429 -.0342857143 | 3 | .2857142857 -.1714285714 .9428571429 | +----------------------------------------------+   : r 1 2 3 +----------------------+ 1 | -14 -21 14 | 2 | 0 -175 70 | 3 | 0 0 -35 | +----------------------+
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.
#Visual_Basic_.NET
Visual Basic .NET
Option Strict On Option Explicit On   Imports System.IO   ''' <summary>Find solutions to the "Prime Triangle" - a triangle of numbers that sum to primes.</summary> Module vMain   Public Const maxNumber As Integer = 20 ' Largest number we will consider. Dim prime(2 * maxNumber) As Boolean ' prime sieve.   ''' <returns>The number of possible arrangements of the integers for a row in the prime triangle.</returns> Public Function countArrangements(ByVal n As Integer) As Integer If n < 2 Then ' No solutions for n < 2. Return 0 ElseIf n < 4 Then ' For 2 and 3. there is only 1 solution: 1, 2 and 1, 2, 3. For i As Integer = 1 To n Console.Out.Write(i.ToString.PadLeft(3)) Next i Console.Out.WriteLine() Return 1 Else ' 4 or more - must find the solutions. Dim printSolution As Boolean = true Dim used(n) As Boolean Dim number(n) As Integer ' The triangle row must have 1 in the leftmost and n in the rightmost elements. ' The numbers must alternate between even and odd in order for the sums to be prime. For i As Integer = 0 To n - 1 number(i) = i Mod 2 Next i used(1) = True number(n) = n used(n) = True ' Find the intervening numbers and count the solutions. Dim count As Integer = 0 Dim p As Integer = 2 Do While p > 0 Dim p1 As Integer = number(p - 1) Dim current As Integer = number(p) Dim [next] As Integer = current + 2 Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next])) [next] += 2 Loop If [next] >= n Then [next] = 0 End If If p = n - 1 Then ' We are at the final number before n. ' It must be the final even/odd number preceded by the final odd/even number. If [next] <> 0 Then ' Possible solution. If prime([next] + n) Then ' Found a solution. count += 1 If printSolution Then For i As Integer = 1 To n - 2 Console.Out.Write(number(i).ToString.PadLeft(3)) Next i Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3)) printSolution = False End If End If [next] = 0 End If ' Backtrack for more solutions. p -= 1 ' There will be a further backtrack as next is 0 ( there could only be one possible number at p - 1 ). End If If [next] <> 0 Then ' have a/another number that can appear at p. used(current) = False used([next]) = True number(p) = [next] ' Haven't found all the intervening digits yet. p += 1 ElseIf p <= 2 Then ' No more solutions. p = 0 Else ' Can't find a number for this position, backtrack. used(number(p)) = False number(p) = p Mod 2 p -= 1 End If Loop Return count End If End Function   Public Sub Main prime(2) = True For i As Integer = 3 To UBound(prime) Step 2 prime(i) = True Next i For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2 If prime(i) Then For s As Integer = i * i To Ubound(prime) Step i + i prime(s) = False Next s End If Next i   Dim arrangements(maxNumber) As Integer For n As Integer = 2 To UBound(arrangements) arrangements(n) = countArrangements(n) Next n For n As Integer = 2 To UBound(arrangements) Console.Out.Write(" " & arrangements(n)) Next n Console.Out.WriteLine()   End Sub   End Module
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#ALGOL_W
ALGOL W
begin  % find primes using Wilson's theorem:  %  % p is prime if ( ( p - 1 )! + 1 ) mod p = 0  %    % returns true if n is a prime by Wilson's theorem, false otherwise %  % computes the factorial mod p at each stage, so as to  %  % allow numbers whose factorial won't fit in 32 bits  % logical procedure isWilsonPrime ( integer value n ) ; begin integer factorialModN; factorialModN := 1; for i := 2 until n - 1 do factorialModN := ( factorialModN * i ) rem n; factorialModN = n - 1 end isWilsonPrime ;   for i := 1 until 100 do if isWilsonPrime( i ) then writeon( i_w := 1, s_w := 0, " ", i ); end.
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#APL
APL
wilson ← {⍵<2:0 ⋄ (⍵-1)=(⍵|×)/⍳⍵-1}
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Go
Go
// +build <expression>
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Icon_and_Unicon
Icon and Unicon
&trace # controls execution tracing &error # controls error handling
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#J
J
9!:1 random seed (incomplete specification of state -- see 9!:45) 9!:3 default display for non-nouns 9!:7 box drawing characters 9!:9 error messages 9!:11 print precision 9!:17 centering (or not) when box contents are smaller than boxes 9!:19 comparison tolerance 9!:21 memory limit 9!:25 security level 9!:27 text of immediate execution phrase 9!:29 enable immediate execution phrase 9!:33 execution time limit 9!:35 disable (or re-enable) assertions 9!:37 output control 9!:39 locales' hash table size 9!:41 retain (or not) whitespace and comments in explicit definitions 9!:43 which random number generator to use? 9!:45 what is the current state of that rng? 9!:49 enable reserved words for argument names
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Julia
Julia
x = rand(100, 100) y = rand(100, 100)   @inbounds begin for i = 1:100 for j = 1:100 x[i, j] *= y[i, j] y[i, j] += x[i, j] end end end  
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Kotlin
Kotlin
// version 1.0.6   @Suppress("UNUSED_VARIABLE")   fun main(args: Array<String>) { val s = "To be suppressed" }
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Lua
Lua
ffi = require("ffi") ffi.cdef[[ #pragma pack(1) typedef struct { char c; int i; } foo; #pragma pack(4) typedef struct { char c; int i; } bar; ]] print(ffi.sizeof(ffi.new("foo"))) print(ffi.sizeof(ffi.new("bar")))
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of the primes that immediately follow them. and This conspiracy among prime numbers seems, at first glance, to violate a longstanding assumption in number theory: that prime numbers behave much like random numbers. ─── (original authors from Stanford University): ─── Kannan Soundararajan and Robert Lemke Oliver The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime. Task Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed. Observation (Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime. Extra credit Do the same for one hundred million primes. Example for 10,000 primes 10000 first primes. Transitions prime % 10 → next-prime % 10. 1 → 1 count: 365 frequency: 3.65 % 1 → 3 count: 833 frequency: 8.33 % 1 → 7 count: 889 frequency: 8.89 % 1 → 9 count: 397 frequency: 3.97 % 2 → 3 count: 1 frequency: 0.01 % 3 → 1 count: 529 frequency: 5.29 % 3 → 3 count: 324 frequency: 3.24 % 3 → 5 count: 1 frequency: 0.01 % 3 → 7 count: 754 frequency: 7.54 % 3 → 9 count: 907 frequency: 9.07 % 5 → 7 count: 1 frequency: 0.01 % 7 → 1 count: 655 frequency: 6.55 % 7 → 3 count: 722 frequency: 7.22 % 7 → 7 count: 323 frequency: 3.23 % 7 → 9 count: 808 frequency: 8.08 % 9 → 1 count: 935 frequency: 9.35 % 9 → 3 count: 635 frequency: 6.35 % 9 → 7 count: 541 frequency: 5.41 % 9 → 9 count: 379 frequency: 3.79 %
#C.2B.2B
C++
#include <vector> #include <iostream> #include <cmath> #include <utility> #include <map> #include <iomanip>   bool isPrime( int i ) { int stop = std::sqrt( static_cast<double>( i ) ) ; for ( int d = 2 ; d <= stop ; d++ ) if ( i % d == 0 ) return false ; return true ; }   class Compare { public : Compare( ) { }   bool operator( ) ( const std::pair<int , int> & a , const std::pair<int, int> & b ) { if ( a.first != b.first ) return a.first < b.first ; else return a.second < b.second ; } };   int main( ) { std::vector<int> primes {2} ; int current = 3 ; while ( primes.size( ) < 1000000 ) { if ( isPrime( current ) ) primes.push_back( current ) ; current += 2 ; } Compare myComp ; std::map<std::pair<int, int>, int , Compare> conspiracy (myComp) ; for ( int i = 0 ; i < primes.size( ) -1 ; i++ ) { int a = primes[i] % 10 ; int b = primes[ i + 1 ] % 10 ; std::pair<int , int> numbers { a , b} ; conspiracy[numbers]++ ; } std::cout << "1000000 first primes. Transitions prime % 10 → next-prime % 10.\n" ; for ( auto it = conspiracy.begin( ) ; it != conspiracy.end( ) ; it++ ) { std::cout << (it->first).first << " -> " << (it->first).second << " count:" ; int frequency = it->second ; std::cout << std::right << std::setw( 15 ) << frequency << " frequency: " ; std::cout.setf(std::ios::fixed, std::ios::floatfield ) ; std::cout.precision( 2 ) ; std::cout << (static_cast<double>(frequency) / 1000000.0) * 100 << " %\n" ; } return 0 ; }
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#BaCon
BaCon
  FUNCTION ProperDivisor(nr, show)   LOCAL probe, total   FOR probe = 1 TO nr-1 IF MOD(nr, probe) = 0 THEN IF show THEN PRINT " ", probe; INCR total END IF NEXT   RETURN total   END FUNCTION   FOR x = 1 TO 10 PRINT x, ":"; IF ProperDivisor(x, 1) = 0 THEN PRINT " 0"; PRINT NEXT   FOR x = 1 TO 20000 DivisorCount = ProperDivisor(x, 0) IF DivisorCount > MaxDivisors THEN MaxDivisors = DivisorCount MagicNumber = x END IF NEXT   PRINT "Most proper divisors for number in the range 1-20000: ", MagicNumber, " with ", MaxDivisors, " divisors."  
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#C.23
C#
  using System;   class Program { static long TRIALS = 1000000L; private class Expv { public string name; public int probcount; public double expect; public double mapping;   public Expv(string name, int probcount, double expect, double mapping) { this.name = name; this.probcount = probcount; this.expect = expect; this.mapping = mapping; } }   static Expv[] items = { new Expv("aleph", 0, 0.0, 0.0), new Expv("beth", 0, 0.0, 0.0), new Expv("gimel", 0, 0.0, 0.0), new Expv("daleth", 0, 0.0, 0.0), new Expv("he", 0, 0.0, 0.0), new Expv("waw", 0, 0.0, 0.0), new Expv("zayin", 0, 0.0, 0.0), new Expv("heth", 0, 0.0, 0.0) };   static void Main(string[] args) { double rnum, tsum = 0.0; Random random = new Random();   for (int i = 0, rnum = 5.0; i < 7; i++, rnum += 1.0) { items[i].expect = 1.0 / rnum; tsum += items[i].expect; } items[7].expect = 1.0 - tsum;   items[0].mapping = 1.0 / 5.0; for (int i = 1; i < 7; i++) items[i].mapping = items[i - 1].mapping + 1.0 / ((double)i + 5.0); items[7].mapping = 1.0;   for (int i = 0; i < TRIALS; i++) { rnum = random.NextDouble(); for (int j = 0; j < 8; j++) if (rnum < items[j].mapping) { items[j].probcount++; break; } }   Console.WriteLine("Trials: {0}", TRIALS); Console.Write("Items: "); for (int i = 0; i < 8; i++) Console.Write(items[i].name.PadRight(9)); Console.WriteLine(); Console.Write("Target prob.: "); for (int i = 0; i < 8; i++) Console.Write("{0:0.000000} ", items[i].expect); Console.WriteLine(); Console.Write("Attained prob.: "); for (int i = 0; i < 8; i++) Console.Write("{0:0.000000} ", (double)items[i].probcount / (double)TRIALS); Console.WriteLine(); } }  
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333. The problem is to list, for a delimited set of ancestors (from 1 to 99) : - the total of their own ancestors (LEVEL), - their own ancestors (ANCESTORS), - the total of the direct descendants (DESCENDANTS), - all the direct descendants. You only have to consider the prime factors < 100. A grand total of the descendants has to be printed at the end of the list. The task should be accomplished in a reasonable time-frame. Example : 46 = 2*23 --> 2+23 = 25, is the parent of 46. 25 = 5*5 --> 5+5 = 10, is the parent of 25. 10 = 2*5 --> 2+5 = 7, is the parent of 10. 7 is a prime factor and, as such, has no parent. 46 has 3 ancestors (7, 10 and 25). 46 has 557 descendants. The list layout and the output for Parent [46] : [46] Level: 3 Ancestors: 7, 10, 25 Descendants: 557 129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876 Some figures : The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99) Total Descendants 546.986
#Java
Java
import java.io.*; import java.util.*;   public class PrimeDescendants { public static void main(String[] args) { try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) { printPrimeDesc(writer, 100); } catch (IOException ex) { ex.printStackTrace(); } }   private static void printPrimeDesc(Writer writer, int limit) throws IOException { List<Long> primes = findPrimes(limit);   List<Long> ancestor = new ArrayList<>(limit); List<List<Long>> descendants = new ArrayList<>(limit); for (int i = 0; i < limit; ++i) { ancestor.add(Long.valueOf(0)); descendants.add(new ArrayList<Long>()); }   for (Long prime : primes) { int p = prime.intValue(); descendants.get(p).add(prime); for (int i = 0; i + p < limit; ++i) { int s = i + p; for (Long n : descendants.get(i)) { Long prod = n * p; descendants.get(s).add(prod); if (prod < limit) ancestor.set(prod.intValue(), Long.valueOf(s)); } } }   // print the results int totalDescendants = 0; for (int i = 1; i < limit; ++i) { List<Long> ancestors = getAncestors(ancestor, i); writer.write("[" + i + "] Level: " + ancestors.size() + "\n"); writer.write("Ancestors: "); Collections.sort(ancestors); print(writer, ancestors);   writer.write("Descendants: "); List<Long> desc = descendants.get(i); if (!desc.isEmpty()) { Collections.sort(desc); if (desc.get(0) == i) desc.remove(0); } writer.write(desc.size() + "\n"); totalDescendants += desc.size(); if (!desc.isEmpty()) print(writer, desc); writer.write("\n"); } writer.write("Total descendants: " + totalDescendants + "\n"); }   // find the prime numbers up to limit private static List<Long> findPrimes(int limit) { boolean[] isprime = new boolean[limit]; Arrays.fill(isprime, true); isprime[0] = isprime[1] = false; for (int p = 2; p * p < limit; ++p) { if (isprime[p]) { for (int i = p * p; i < limit; i += p) isprime[i] = false; } } List<Long> primes = new ArrayList<>(); for (int p = 2; p < limit; ++p) { if (isprime[p]) primes.add(Long.valueOf(p)); } return primes; }   // returns all ancestors of n. n is not its own ancestor. private static List<Long> getAncestors(List<Long> ancestor, int n) { List<Long> result = new ArrayList<>(); for (Long a = ancestor.get(n); a != 0 && a != n; ) { n = a.intValue(); a = ancestor.get(n); result.add(Long.valueOf(n)); } return result; }   private static void print(Writer writer, List<Long> list) throws IOException { if (list.isEmpty()) { writer.write("none\n"); return; } int i = 0; writer.write(String.valueOf(list.get(i++))); for (; i != list.size(); ++i) writer.write(", " + list.get(i)); writer.write("\n"); } }
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#C.2B.2B
C++
#include <iostream> #include <string> #include <queue> #include <utility>   int main() { std::priority_queue<std::pair<int, std::string> > pq; pq.push(std::make_pair(3, "Clear drains")); pq.push(std::make_pair(4, "Feed cat")); pq.push(std::make_pair(5, "Make tea")); pq.push(std::make_pair(1, "Solve RC tasks")); pq.push(std::make_pair(2, "Tax return"));   while (!pq.empty()) { std::cout << pq.top().first << ", " << pq.top().second << std::endl; pq.pop(); }   return 0; }
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#FutureBasic
FutureBasic
Problem of Apollonius   include "NSLog.incl"   begin record Circle CGPoint center double radius CFStringRef locator end record   local fn CircleToString( c as Circle ) as CFStringRef end fn = fn StringWithFormat( @"%@ Circle( x = %0.3f, y = %0.3f, radius = %0.3f )", c.locator, c.center.x, c.center.y, c.radius )   local fn SolveApollonius( c1 as Circle, c2 as Circle, c3 as Circle, s1 as Double, s2 as Double, s3 as Double ) as Circle '~'1 Circle result   double x1 = c1.center.x double y1 = c1.center.y double r1 = c1.radius   double x2 = c2.center.x double y2 = c2.center.y double r2 = c2.radius   double x3 = c3.center.x double y3 = c3.center.y double r3 = c3.radius   double v11 = 2*x2 - 2*x1 double v12 = 2*y2 - 2*y1 double v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 double v14 = 2*s2*r2 - 2*s1*r1   double v21 = 2*x3 - 2*x2 double v22 = 2*y3 - 2*y2 double v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 double v24 = 2*s3*r3 - 2*s2*r2   double w12 = v12/v11 double w13 = v13/v11 double w14 = v14/v11   double w22 = v22/v21-w12 double w23 = v23/v21-w13 double w24 = v24/v21-w14   double P = -w23/w22 double Q = w24/w22 double M = -w12*P-w13 double N = w14 - w12*Q   double a = N*N + Q*Q - 1 double b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 double c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1   double D = b*b-4*a*c   double rs = (-b - sqr(D)) / (2*a) double xs = M + N * rs double ys = P + Q * rs   result.center.x = xs result.center.y = ys result.radius = rs   if ( s1 < 1 ) result.locator = @"Internal Tangent:" else result.locator = @"External Tangent:" end if end fn = result   Circle c1, c2, c3, c   c1.center.x = 0.0 : c1.center.y = 0.0 : c1.radius = 1.0 c2.center.x = 4.0 : c2.center.y = 0.0 : c2.radius = 1.0 c3.center.x = 2.0 : c3.center.y = 4.0 : c3.radius = 2.0   // External tangent c = fn SolveApollonius( c1, c2, c3, 1, 1, 1 ) NSLog( @"%@", fn CircleToString( c ) )   // Internal tangent c = fn SolveApollonius( c1, c2, c3, -1, -1, -1 ) NSLog( @"%@", fn CircleToString( c ) )   HandleEvents  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Nemerle
Nemerle
using System.Environment; ... def program_name = GetCommandLineArgs()[0]; ...
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   package org.rosettacode.samples   say 'Source: ' source say 'Program:' System.getProperty('sun.java.command') return  
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#Ring
Ring
  # Project: Primorial numbers load "bignumber.ring" decimals(0) num = 0 prim = 0 limit = 10000000 see "working..." + nl see "wait for done..." + nl while num < 100001 prim = prim + 1 prime = [] primorial(prim) end see "done..." + nl   func primorial(pr) n = 1 n2 = 0 flag = 1 while flag = 1 and n < limit nr = isPrime(n) if n=1 nr=1 ok if nr=1 n2 = n2 + 1 add(prime,n) ok if n2=pr flag=0 num = num + 1 ok n = n + 1 end pro = 1 str = "" for n=1 to len(prime) pro = FuncMultiply("" + pro,"" + prime[n]) str = str + prime[n] + "*" next str = left(str,len(str)-1) if pr < 11 see "primorial(" + string(pr-1) + ") : " + pro + nl ok if pr = 11 see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl but pr = 101 see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl but pr = 1001 see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl but pr = 10001 see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl but pr = 100001 see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl ok  
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#Ruby
Ruby
require 'prime'   def primorial_number(n) pgen = Prime.each (1..n).inject(1){|p,_| p*pgen.next} end   puts "First ten primorials: #{(0..9).map{|n| primorial_number(n)}}"   (1..5).each do |n| puts "primorial(10**#{n}) has #{primorial_number(10**n).to_s.size} digits" 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
#Nanoquery
Nanoquery
import math   // a function to check if three numbers are a valid triple def is_triple(a, b, c) if not (a < b) and (b < c) return false end   return (a^2 + b^2) = c^2 end   // a function to check if the numbers are coprime def is_coprime(a, b, c) global math return (math.gcd(a, b)=1) && (math.gcd(a, c)=1) && (math.gcd(b, c)=1) end   // the maximum perimeter to check perimeter = 100 perimeter2 = int(perimeter / 2) - 1 perimeter3 = int(perimeter / 3) - 1   // loop though and look for pythagorean triples ts = 0 ps = 0 for a in range(1, perimeter3) for b in range(a + 1, perimeter2) for c in range(b + 1, perimeter2) if (a + b + c) <= perimeter if is_triple(a,b,c) ts += 1 print a + ", " + b + ", " + c if is_coprime(a,b,c) ps += 1 print " primitive" end println end end end end end   print "Up to a perimeter of " + perimeter + ", there are " + ts println " triples, of which " + ps + " are primitive."
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Liberty_BASIC
Liberty BASIC
if 2 =2 then end
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decomposition. Task Demonstrate the QR decomposition on the example matrix from the Wikipedia article: A = ( 12 − 51 4 6 167 − 68 − 4 24 − 41 ) {\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}} and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used: Method Multiplying a given vector a {\displaystyle {\mathit {a}}} , for example the first column of matrix A {\displaystyle {\mathit {A}}} , with the Householder matrix H {\displaystyle {\mathit {H}}} , which is given as H = I − 2 u T u u u T {\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}} reflects a {\displaystyle {\mathit {a}}} about a plane given by its normal vector u {\displaystyle {\mathit {u}}} . When the normal vector of the plane u {\displaystyle {\mathit {u}}} is given as u = a − ∥ a ∥ 2 e 1 {\displaystyle u=a-\|a\|_{2}\;e_{1}} then the transformation reflects a {\displaystyle {\mathit {a}}} onto the first standard basis vector e 1 = [ 1 0 0 . . . ] T {\displaystyle e_{1}=[1\;0\;0\;...]^{T}} which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of a 1 {\displaystyle a_{1}} : u = a + sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}} and normalize with respect to the first element: v = u u 1 {\displaystyle v={\frac {u}{u_{1}}}} The equation for H {\displaystyle H} thus becomes: H = I − 2 v T v v v T {\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}} or, in another form H = I − β v v T {\displaystyle H=I-\beta vv^{T}} with β = 2 v T v {\displaystyle \beta ={\frac {2}{v^{T}v}}} Applying H {\displaystyle {\mathit {H}}} on a {\displaystyle {\mathit {a}}} then gives H a = − sign ( a 1 ) ∥ a ∥ 2 e 1 {\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}} and applying H {\displaystyle {\mathit {H}}} on the matrix A {\displaystyle {\mathit {A}}} zeroes all subdiagonal elements of the first column: H 1 A = ( r 11 r 12 r 13 0 ∗ ∗ 0 ∗ ∗ ) {\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}} In the second step, the second column of A {\displaystyle {\mathit {A}}} , we want to zero all elements but the first two, which means that we have to calculate H {\displaystyle {\mathit {H}}} with the first column of the submatrix (denoted *), not on the whole second column of A {\displaystyle {\mathit {A}}} . To get H 2 {\displaystyle H_{2}} , we then embed the new H {\displaystyle {\mathit {H}}} into an m × n {\displaystyle m\times n} identity: H 2 = ( 1 0 0 0 H 0 ) {\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}} This is how we can, column by column, remove all subdiagonal elements of A {\displaystyle {\mathit {A}}} and thus transform it into R {\displaystyle {\mathit {R}}} . H n . . . H 3 H 2 H 1 A = R {\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R} The product of all the Householder matrices H {\displaystyle {\mathit {H}}} , for every column, in reverse order, will then yield the orthogonal matrix Q {\displaystyle {\mathit {Q}}} . H 1 H 2 H 3 . . . H n = Q {\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q} The QR decomposition should then be used to solve linear least squares (Multiple regression) problems A x = b {\displaystyle {\mathit {A}}x=b} by solving R x = Q T b {\displaystyle R\;x=Q^{T}\;b} When R {\displaystyle {\mathit {R}}} is not square, i.e. m > n {\displaystyle m>n} we have to cut off the m − n {\displaystyle {\mathit {m}}-n} zero padded bottom rows. R = ( R 1 0 ) {\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}} and the same for the RHS: Q T b = ( q 1 q 2 ) {\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}} Finally, solve the square upper triangular system by back substitution: R 1 x = q 1 {\displaystyle R_{1}\;x=q_{1}}
#Tcl
Tcl
package require Tcl 8.5 namespace path {::tcl::mathfunc ::tcl::mathop} proc sign x {expr {$x == 0 ? 0 : $x < 0 ? -1 : 1}} proc norm vec { set s 0 foreach x $vec {set s [expr {$s + $x**2}]} return [sqrt $s] } proc unitvec n { set v [lrepeat $n 0.0] lset v 0 1.0 return $v } proc I n { set m [lrepeat $n [lrepeat $n 0.0]] for {set i 0} {$i < $n} {incr i} {lset m $i $i 1.0} return $m }   proc arrayEmbed {A B row col} { # $A will be copied automatically; Tcl values are copy-on-write lassign [size $B] mb nb for {set i 0} {$i < $mb} {incr i} { for {set j 0} {$j < $nb} {incr j} { lset A [expr {$row + $i}] [expr {$col + $j}] [lindex $B $i $j] } } return $A }   # Unlike the Common Lisp version, here we use a specialist subcolumn # extraction function: like that, there's a lot less intermediate memory allocation # and the code is actually clearer. proc subcolumn {A size column} { for {set i $column} {$i < $size} {incr i} {lappend x [lindex $A $i $column]} return $x }   proc householder A { lassign [size $A] m set U [m+ $A [.* [unitvec $m] [expr {[norm $A] * [sign [lindex $A 0 0]]}]]] set V [./ $U [lindex $U 0 0]] set beta [expr {2.0 / [lindex [matrix_multiply [transpose $V] $V] 0 0]}] return [m- [I $m] [.* [matrix_multiply $V [transpose $V]] $beta]] }   proc qrDecompose A { lassign [size $A] m n set Q [I $m] for {set i 0} {$i < ($m==$n ? $n-1 : $n)} {incr i} { # Construct the Householder matrix set H [arrayEmbed [I $m] [householder [subcolumn $A $n $i]] $i $i] # Apply to build the decomposition set Q [matrix_multiply $Q $H] set A [matrix_multiply $H $A] } return [list $Q $A] }
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.
#Wren
Wren
import "./fmt" for Fmt   var canFollow = [] var arrang = [] var bFirst = true   var pmap = {} for (i in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]) { pmap[i] = true }   var ptrs ptrs = Fn.new { |res, n, done| var ad = arrang[done-1] if (n - done <= 1) { if (canFollow[ad-1][n-1]) { if (bFirst) { Fmt.print("$2d", arrang) bFirst = false } res = res + 1 } } else { done = done + 1 var i = done - 1 while (i <= n-2) { var ai = arrang[i] if (canFollow[ad-1][ai-1]) { arrang.swap(i, done-1) res = ptrs.call(res, n, done) arrang.swap(i, done-1) } i = i + 2 } } return res }   var primeTriangle = Fn.new { |n| canFollow = List.filled(n, null) for (i in 0...n) { canFollow[i] = List.filled(n, false) for (j in 0...n) canFollow[i][j] = pmap.containsKey(i+j+2) } bFirst = true arrang = (1..n).toList return ptrs.call(0, n, 1) }   var counts = [] for (i in 2..20) { counts.add(primeTriangle.call(i)) } System.print() System.print(counts.join(" "))
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#AppleScript
AppleScript
on isPrime(n) if (n < 2) then return false set f to n - 1 repeat with i from (n - 2) to 2 by -1 set f to f * i mod n end repeat   return ((f + 1) mod n = 0) end isPrime   local output, n set output to {} repeat with n from 0 to 500 if (isPrime(n)) then set end of output to n end repeat output
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Arturo
Arturo
factorial: function [x]-> product 1..x   wprime?: function [n][ if n < 2 -> return false zero? mod add factorial sub n 1 1 n ]   print "Primes below 20 via Wilson's theorem:" print select 1..20 => wprime?
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
{.checks: off, optimization: speed.} # Checks are deactivated and code is generated for speed.   # Define a type Color as pure which implies that value names are declared in their own scope # and may/should be accessed with their type qualifier (as Color.Red). type Color {.pure.} = enum Red, Green, Blue   # Declare a procedure to inline if possible. proc odd(x: int): bool {.inline.} = (x and 1) != 0   # Declaration of a C external procedure. proc printf(formatstr: cstring) {.header: "<stdio.h>", importc: "printf", varargs.}   # Declaration of a deprecated procedure. If not used, no warning will be emitted. proc notUsed(x: int) {.used, deprecated.} = echo x   # Declaration of a type with an alignment constraint. type SseType = object sseData {.align(16).}: array[4, float32]   # Declaration of a procedure containing a variable to store in register, if possible, and a variable to store as global. proc p() = var x {.register.}: int var y {.global.} = "abcdef"   {.push checks: on.} # From here, checks are activated. ... {.pop.} # From here, checks are deactivated again.
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#NetRexx
NetRexx
{.checks: off, optimization: speed.} # Checks are deactivated and code is generated for speed.   # Define a type Color as pure which implies that value names are declared in their own scope # and may/should be accessed with their type qualifier (as Color.Red). type Color {.pure.} = enum Red, Green, Blue   # Declare a procedure to inline if possible. proc odd(x: int): bool {.inline.} = (x and 1) != 0   # Declaration of a C external procedure. proc printf(formatstr: cstring) {.header: "<stdio.h>", importc: "printf", varargs.}   # Declaration of a deprecated procedure. If not used, no warning will be emitted. proc notUsed(x: int) {.used, deprecated.} = echo x   # Declaration of a type with an alignment constraint. type SseType = object sseData {.align(16).}: array[4, float32]   # Declaration of a procedure containing a variable to store in register, if possible, and a variable to store as global. proc p() = var x {.register.}: int var y {.global.} = "abcdef"   {.push checks: on.} # From here, checks are activated. ... {.pop.} # From here, checks are deactivated again.
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Nim
Nim
{.checks: off, optimization: speed.} # Checks are deactivated and code is generated for speed.   # Define a type Color as pure which implies that value names are declared in their own scope # and may/should be accessed with their type qualifier (as Color.Red). type Color {.pure.} = enum Red, Green, Blue   # Declare a procedure to inline if possible. proc odd(x: int): bool {.inline.} = (x and 1) != 0   # Declaration of a C external procedure. proc printf(formatstr: cstring) {.header: "<stdio.h>", importc: "printf", varargs.}   # Declaration of a deprecated procedure. If not used, no warning will be emitted. proc notUsed(x: int) {.used, deprecated.} = echo x   # Declaration of a type with an alignment constraint. type SseType = object sseData {.align(16).}: array[4, float32]   # Declaration of a procedure containing a variable to store in register, if possible, and a variable to store as global. proc p() = var x {.register.}: int var y {.global.} = "abcdef"   {.push checks: on.} # From here, checks are activated. ... {.pop.} # From here, checks are deactivated again.
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Perl
Perl
use warnings; # use warnings pragma module use strict; # use strict pragma module
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#Phix
Phix
requires(JS) --requires(WINDOWS) -- (one of only, or --requires(LINUX) -- a special combo) requires("1.0.2") requires(32) -- or 64
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
#PicoLisp
PicoLisp
declare (t(100),i) fixed binary; i=101; t(i)=0;
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of the primes that immediately follow them. and This conspiracy among prime numbers seems, at first glance, to violate a longstanding assumption in number theory: that prime numbers behave much like random numbers. ─── (original authors from Stanford University): ─── Kannan Soundararajan and Robert Lemke Oliver The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime. Task Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed. Observation (Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime. Extra credit Do the same for one hundred million primes. Example for 10,000 primes 10000 first primes. Transitions prime % 10 → next-prime % 10. 1 → 1 count: 365 frequency: 3.65 % 1 → 3 count: 833 frequency: 8.33 % 1 → 7 count: 889 frequency: 8.89 % 1 → 9 count: 397 frequency: 3.97 % 2 → 3 count: 1 frequency: 0.01 % 3 → 1 count: 529 frequency: 5.29 % 3 → 3 count: 324 frequency: 3.24 % 3 → 5 count: 1 frequency: 0.01 % 3 → 7 count: 754 frequency: 7.54 % 3 → 9 count: 907 frequency: 9.07 % 5 → 7 count: 1 frequency: 0.01 % 7 → 1 count: 655 frequency: 6.55 % 7 → 3 count: 722 frequency: 7.22 % 7 → 7 count: 323 frequency: 3.23 % 7 → 9 count: 808 frequency: 8.08 % 9 → 1 count: 935 frequency: 9.35 % 9 → 3 count: 635 frequency: 6.35 % 9 → 7 count: 541 frequency: 5.41 % 9 → 9 count: 379 frequency: 3.79 %
#D
D
import std.algorithm; import std.range; import std.stdio; import std.typecons;   alias Transition = Tuple!(int, int);   bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return false; d += 4; } return true; }   auto generatePrimes() { import std.concurrency; return new Generator!int({ yield(2); int p = 3; while (p > 0) { if (isPrime(p)) { yield(p); } p += 2; } }); }   void main() { auto primes = generatePrimes().take(1_000_000).array; int[Transition] transMap; foreach (i; 0 .. primes.length - 1) { auto transition = Transition(primes[i] % 10, primes[i + 1] % 10); if (transition in transMap) { transMap[transition] += 1; } else { transMap[transition] = 1; } } auto sortedTransitions = transMap.keys.multiSort!(q{a[0] < b[0]}, q{a[1] < b[1]}); writeln("First 1,000,000 primes. Transitions prime % 10 -> next-prime % 10."); foreach (trans; sortedTransitions) { writef("%s -> %s count: %5d", trans[0], trans[1], transMap[trans]); writefln(" frequency: %4.2f%%", transMap[trans] / 10_000.0); } }
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given number   n {\displaystyle n}   greater than   1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). Related tasks   count in factors   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#11l
11l
F decompose(BigInt number) [BigInt] result V n = number BigInt i = 2 L n % i == 0 result.append(i) n I/= i i = 3 L n >= i * i L n % i == 0 result.append(i) n I/= i i += 2 I n != 1 result.append(n) R result   L(i) 2..9 print(decompose(i)) print(decompose(1023 * 1024)) print(decompose(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17)) print(decompose(BigInt(16860167264933) * 179951))
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#C
C
  #include <stdio.h> #include <stdbool.h>   int proper_divisors(const int n, bool print_flag) { int count = 0;   for (int i = 1; i < n; ++i) { if (n % i == 0) { count++; if (print_flag) printf("%d ", i); } }   if (print_flag) printf("\n");   return count; }   int main(void) { for (int i = 1; i <= 10; ++i) { printf("%d: ", i); proper_divisors(i, true); }   int max = 0; int max_i = 1;   for (int i = 1; i <= 20000; ++i) { int v = proper_divisors(i, false); if (v >= max) { max = v; max_i = i; } }   printf("%d with %d divisors\n", max_i, max); return 0; }  
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#C.2B.2B
C++
#include <cstdlib> #include <iostream> #include <vector> #include <utility> #include <algorithm> #include <ctime> #include <iomanip>   int main( ) { typedef std::vector<std::pair<std::string, double> >::const_iterator SPI ; typedef std::vector<std::pair<std::string , double> > ProbType ; ProbType probabilities ; probabilities.push_back( std::make_pair( "aleph" , 1/5.0 ) ) ; probabilities.push_back( std::make_pair( "beth" , 1/6.0 ) ) ; probabilities.push_back( std::make_pair( "gimel" , 1/7.0 ) ) ; probabilities.push_back( std::make_pair( "daleth" , 1/8.0 ) ) ; probabilities.push_back( std::make_pair( "he" , 1/9.0 ) ) ; probabilities.push_back( std::make_pair( "waw" , 1/10.0 ) ) ; probabilities.push_back( std::make_pair( "zayin" , 1/11.0 ) ) ; probabilities.push_back( std::make_pair( "heth" , 1759/27720.0 ) ) ; std::vector<std::string> generated ; //for the strings that are generatod std::vector<int> decider ; //holds the numbers that determine the choice of letters for ( int i = 0 ; i < probabilities.size( ) ; i++ ) { if ( i == 0 ) { decider.push_back( 27720 * (probabilities[ i ].second) ) ; } else { int number = 0 ; for ( int j = 0 ; j < i ; j++ ) { number += 27720 * ( probabilities[ j ].second ) ; } number += 27720 * probabilities[ i ].second ; decider.push_back( number ) ; } } srand( time( 0 ) ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { int randnumber = rand( ) % 27721 ; int j = 0 ; while ( randnumber > decider[ j ] ) j++ ; generated.push_back( ( probabilities[ j ]).first ) ; } std::cout << "letter frequency attained frequency expected\n" ; for ( SPI i = probabilities.begin( ) ; i != probabilities.end( ) ; i++ ) { std::cout << std::left << std::setw( 8 ) << i->first ; int found = std::count ( generated.begin( ) , generated.end( ) , i->first ) ; std::cout << std::left << std::setw( 21 ) << found / 1000000.0 ; std::cout << std::left << std::setw( 17 ) << i->second << '\n' ; } return 0 ; }
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333. The problem is to list, for a delimited set of ancestors (from 1 to 99) : - the total of their own ancestors (LEVEL), - their own ancestors (ANCESTORS), - the total of the direct descendants (DESCENDANTS), - all the direct descendants. You only have to consider the prime factors < 100. A grand total of the descendants has to be printed at the end of the list. The task should be accomplished in a reasonable time-frame. Example : 46 = 2*23 --> 2+23 = 25, is the parent of 46. 25 = 5*5 --> 5+5 = 10, is the parent of 25. 10 = 2*5 --> 2+5 = 7, is the parent of 10. 7 is a prime factor and, as such, has no parent. 46 has 3 ancestors (7, 10 and 25). 46 has 557 descendants. The list layout and the output for Parent [46] : [46] Level: 3 Ancestors: 7, 10, 25 Descendants: 557 129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876 Some figures : The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99) Total Descendants 546.986
#Julia
Julia
using Primes   function ancestraldecendants(maxsum) aprimes = primes(maxsum) descendants = [Vector{Int}() for _ in 1:maxsum + 1] ancestors = [Vector{Int}() for _ in 1:maxsum + 1] for p in aprimes push!(descendants[p + 1], p) foreach(s -> append!(descendants[s + p], [p * pr for pr in descendants[s]]), 2:length(descendants) - p) end foreach(p -> pop!(descendants[p + 1]), vcat(aprimes, [4])) total = 0 for s in 1:maxsum sort!(descendants[s + 1]) dstlen = length(descendants[s + 1]) total += dstlen idx = findfirst(x -> x > maxsum, descendants[s + 1]) idx = (idx == nothing) ? dstlen : idx - 1 foreach(d -> ancestors[d] = vcat(ancestors[s + 1], [s]), descendants[s + 1][1:idx]) if s in vcat(collect(0:20), 46, 74, 99) print(lpad(s, 3), ":", lpad("$(length(ancestors[s + 1]))", 2)) print(" Ancestor(s):", rpad("$(ancestors[s + 1])", 18)) print(lpad("$(length(descendants[s + 1]))", 5), " Descendant(s): ") println(rpad(dstlen <= 10 ? "$(descendants[s + 1])" : "$(descendants[s + 1][1:10])\b, ...]", 40)) end end print("Total descendants: ", total) end   ancestraldecendants(99)  
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333. The problem is to list, for a delimited set of ancestors (from 1 to 99) : - the total of their own ancestors (LEVEL), - their own ancestors (ANCESTORS), - the total of the direct descendants (DESCENDANTS), - all the direct descendants. You only have to consider the prime factors < 100. A grand total of the descendants has to be printed at the end of the list. The task should be accomplished in a reasonable time-frame. Example : 46 = 2*23 --> 2+23 = 25, is the parent of 46. 25 = 5*5 --> 5+5 = 10, is the parent of 25. 10 = 2*5 --> 2+5 = 7, is the parent of 10. 7 is a prime factor and, as such, has no parent. 46 has 3 ancestors (7, 10 and 25). 46 has 557 descendants. The list layout and the output for Parent [46] : [46] Level: 3 Ancestors: 7, 10, 25 Descendants: 557 129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876 Some figures : The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99) Total Descendants 546.986
#Kotlin
Kotlin
// version 1.1.2   const val MAXSUM = 99   fun getPrimes(max: Int): List<Int> { if (max < 2) return emptyList<Int>() val lprimes = mutableListOf(2) outer@ for (x in 3..max step 2) { for (p in lprimes) if (x % p == 0) continue@outer lprimes.add(x) } return lprimes }   fun main(args: Array<String>) { val descendants = Array(MAXSUM + 1) { mutableListOf<Long>() } val ancestors = Array(MAXSUM + 1) { mutableListOf<Int>() } val primes = getPrimes(MAXSUM)   for (p in primes) { descendants[p].add(p.toLong()) for (s in 1 until descendants.size - p) { val temp = descendants[s + p] + descendants[s].map { p * it } descendants[s + p] = temp.toMutableList() } }   for (p in primes + 4) descendants[p].removeAt(descendants[p].lastIndex) var total = 0   for (s in 1..MAXSUM) { descendants[s].sort() total += descendants[s].size for (d in descendants[s].takeWhile { it <= MAXSUM.toLong() }) { ancestors[d.toInt()] = (ancestors[s] + s).toMutableList() } if (s in 21..45 || s in 47..73 || s in 75 until MAXSUM) continue print("${"%2d".format(s)}: ${ancestors[s].size} Ancestor(s): ") print(ancestors[s].toString().padEnd(18)) print("${"%5d".format(descendants[s].size)} Descendant(s): ") println("${descendants[s].joinToString(", ", "[", "]", 10)}") }   println("\nTotal descendants $total") }
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#Clojure
Clojure
user=> (use 'clojure.data.priority-map)   ; priority-map can be used as a priority queue user=> (def p (priority-map "Clear drains" 3, "Feed cat" 4, "Make tea" 5, "Solve RC tasks" 1)) #'user/p user=> p {"Solve RC tasks" 1, "Clear drains" 3, "Feed cat" 4, "Make tea" 5}   ; You can use assoc or conj to add items user=> (assoc p "Tax return" 2) {"Solve RC tasks" 1, "Tax return" 2, "Clear drains" 3, "Feed cat" 4, "Make tea" 5}   ; peek to get first item, pop to give you back the priority-map with the first item removed user=> (peek p) ["Solve RC tasks" 1]   ; Merge priority-maps together user=> (into p [["Wax Car" 4]["Paint Fence" 1]["Sand Floor" 3]]) {"Solve RC tasks" 1, "Paint Fence" 1, "Clear drains" 3, "Sand Floor" 3, "Wax Car" 4, "Feed cat" 4, "Make tea" 5}
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#Go
Go
package main   import ( "fmt" "math" )   type circle struct { x, y, r float64 }   func main() { c1 := circle{0, 0, 1} c2 := circle{4, 0, 1} c3 := circle{2, 4, 2} fmt.Println(ap(c1, c2, c3, true)) fmt.Println(ap(c1, c2, c3, false)) }   func ap(c1, c2, c3 circle, s bool) circle { x1sq := c1.x * c1.x y1sq := c1.y * c1.y r1sq := c1.r * c1.r x2sq := c2.x * c2.x y2sq := c2.y * c2.y r2sq := c2.r * c2.r x3sq := c3.x * c3.x y3sq := c3.y * c3.y r3sq := c3.r * c3.r v11 := 2 * (c2.x - c1.x) v12 := 2 * (c2.y - c1.y) v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq v14 := 2 * (c2.r - c1.r) v21 := 2 * (c3.x - c2.x) v22 := 2 * (c3.y - c2.y) v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq v24 := 2 * (c3.r - c2.r) if s { v14 = -v14 v24 = -v24 } w12 := v12 / v11 w13 := v13 / v11 w14 := v14 / v11 w22 := v22/v21 - w12 w23 := v23/v21 - w13 w24 := v24/v21 - w14 p := -w23 / w22 q := w24 / w22 m := -w12*p - w13 n := w14 - w12*q a := n*n + q*q - 1 b := m*n - n*c1.x + p*q - q*c1.y if s { b -= c1.r } else { b += c1.r } b *= 2 c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq d := b*b - 4*a*c rs := (-b - math.Sqrt(d)) / (2 * a) return circle{m + n*rs, p + q*rs, rs} }
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#newLISP
newLISP
#!/usr/bin/env newlisp   (let ((program (main-args 1))) (println (format "Program: %s" program)) (exit))
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV. See also Command-line arguments Examples from GitHub.
#Nim
Nim
import os echo getAppFilename() # Prints the full path of the executed file echo paramStr(0) # Prints argv[0]
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#Rust
Rust
  extern crate primal; extern crate rayon; extern crate rug;   use rayon::prelude::*; use rug::Integer;   fn partial(p1 : usize, p2 : usize) -> String { let mut aux = Integer::from(1); let (_, hi) = primal::estimate_nth_prime(p2 as u64); let sieve = primal::Sieve::new(hi as usize); let prime1 = sieve.nth_prime(p1); let prime2 = sieve.nth_prime(p2);   for i in sieve.primes_from(prime1).take_while(|i| *i <= prime2) { aux = Integer::from(aux * i as u32); } aux.to_string_radix(10) }   fn main() { let mut j1 = Integer::new(); for k in [2,3,5,7,11,13,17,19,23,29].iter() { j1.assign_primorial(*k); println!("Primorial : {}", j1); } println!("Digits of primorial 10 : {}", partial(1, 10).chars().fold(0, |n, _| n + 1)); println!("Digits of primorial 100 : {}", partial(1, 100).chars().fold(0, |n, _| n + 1)); println!("Digits of primorial 1_000 : {}", partial(1, 1_000).chars().fold(0, |n, _| n + 1)); println!("Digits of primorial 10_000 : {}", partial(1, 10_000).chars().fold(0, |n, _| n + 1)); println!("Digits of primorial 100_000 : {}", partial(1, 100_000).chars().fold(0, |n, _| n + 1));   let mut auxi = Integer::from(1); let ranges = vec![[1, 300_000], [300_001, 550_000], [550_001, 800_000], [800_001, 1_000_000]]; let v = ranges.par_iter().map(|value| partial(value[0], value[1])).collect::<Vec<_>>(); for i in v.iter() { auxi =Integer::from(&auxi * i.parse::<Integer>().unwrap()); } let result = auxi.to_string_radix(10).chars().fold(0, |n, _| n+1); println!("Digits of primorial 1_000_000 : {}",result); }  
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×7)   primorial(5) =   2310       (2×3×5×7×11)   primorial(6) = 30030       (2×3×5×7×11×13)         ∙ ∙ ∙ To express this mathematically,   primorialn   is   the product of the first   n   (successive) primes:   p r i m o r i a l n = ∏ k = 1 n p r i m e k {\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}} ─── where   p r i m e k {\displaystyle prime_{k}}   is the   kth   prime number. In some sense, generating primorial numbers is similar to factorials. As with factorials, primorial numbers get large quickly. Task   Show the first ten primorial numbers   (0 ──► 9,   inclusive).   Show the length of primorial numbers whose index is:   10   100   1,000   10,000   and   100,000.   Show the length of the one millionth primorial number   (optional).   Use exact integers, not approximations. By   length   (above), it is meant the number of decimal digits in the numbers. Related tasks   Sequence of primorial primes   Factorial   Fortunate_numbers See also   the MathWorld webpage:   primorial   the Wikipedia   webpage:   primorial.   the   OEIS   webpage:   A002110.
#Scala
Scala
import spire.math.SafeLong import spire.implicits._   import scala.collection.parallel.immutable.ParVector   object Primorial { def main(args: Array[String]): Unit = { println( s"""|First 10 Primorials: |${LazyList.range(0, 10).map(n => f"$n: ${primorial(n).toBigInt}%,d").mkString("\n")} | |Lengths of Primorials: |${LazyList.range(1, 7).map(math.pow(10, _).toInt).map(i => f"$i%,d: ${primorial(i).toString.length}%,d").mkString("\n")} |""".stripMargin) }   def primorial(num: Int): SafeLong = if(num == 0) 1 else primesSL.take(num).to(ParVector).reduce(_*_) lazy val primesSL: Vector[SafeLong] = 2 +: ParVector.range(3, 20000000, 2).filter(n => !Iterator.range(3, math.sqrt(n).toInt + 1, 2).exists(n%_ == 0)).toVector.sorted.map(SafeLong(_)) }
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
#Nim
Nim
const u = [[ 1, -2, 2, 2, -1, 2, 2, -2, 3], [ 1, 2, 2, 2, 1, 2, 2, 2, 3], [-1, 2, 2, -2, 1, 2, -2, 2, 3]]   var total, prim = 0 maxPeri = 10   proc newTri(ins: array[0..2, int]) = var p = ins[0] + ins[1] + ins[2] if p > maxPeri: return inc(prim) total += maxPeri div p   for i in 0..2: newTri([u[i][0] * ins[0] + u[i][1] * ins[1] + u[i][2] * ins[2], u[i][3] * ins[0] + u[i][4] * ins[1] + u[i][5] * ins[2], u[i][6] * ins[0] + u[i][7] * ins[1] + u[i][8] * ins[2]])   while maxPeri <= 100_000_000: total = 0 prim = 0 newTri([3, 4, 5]) echo "Up to ", maxPeri, ": ", total, " triples, ", prim, " primitives" maxPeri *= 10
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Logo
Logo
bye  ; exits to shell   throw "toplevel  ; exits to interactive prompt   pause  ; escapes to interactive prompt for debugging continue  ; resumes after a PAUSE
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Lua
Lua
if some_condition then os.exit( number ) end