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/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 %
#Haskell
Haskell
import Data.List (group, sort) import Text.Printf (printf) import Data.Numbers.Primes (primes)   freq :: [(Int, Int)] -> Float freq xs = realToFrac (length xs) / 100   line :: [(Int, Int)] -> IO () line t@((n1, n2):xs) = printf "%d -> %d count: %5d frequency: %2.2f %%\n" n1 n2 (length t) (freq t)   main :: IO () main = mapM_ line $ groups primes where groups = tail . group . sort . (\n -> zip (0: n) n) . fmap (`mod` 10) . take 10000
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
#ALGOL_68
ALGOL 68
#IF long int possible THEN #   MODE LINT = LONG INT; LINT lmax int = long max int; OP LLENG = (INT i)LINT: LENG i, LSHORTEN = (LINT i)INT: SHORTEN i;   #ELSE   MODE LINT = INT; LINT lmax int = max int; OP LLENG = (INT i)LINT: i, LSHORTEN = (LINT i)INT: i;   FI#   OP LLONG = (INT i)LINT: LLENG i;   MODE YIELDLINT = PROC(LINT)VOID;   PROC (LINT, YIELDLINT)VOID gen decompose;   INT upb cache = bits width;   BITS cache := 2r0; BITS cached := 2r0;   PROC is prime = (LINT n)BOOL: ( BOOL has factor := FALSE, out := TRUE; # FOR LINT factor IN # gen decompose(n, # ) DO ( # ## (LINT factor)VOID:( IF has factor THEN out := FALSE; GO TO done FI; has factor := TRUE # OD # )); done: out );   PROC is prime cached := (LINT n)BOOL: ( LINT l half n = n OVER LLONG 2 - LLONG 1; IF l half n <= LLENG upb cache THEN INT half n = LSHORTEN l half n; IF half n ELEM cached THEN BOOL(half n ELEM cache) ELSE BOOL out = is prime(n); BITS mask = 2r1 SHL (upb cache - half n); cached := cached OR mask; IF out THEN cache := cache OR mask FI; out FI ELSE is prime(n) # above useful cache limit # FI );     PROC gen primes := (YIELDLINT yield)VOID:( yield(LLONG 2); LINT n := LLONG 3; WHILE n < l maxint - LLONG 2 DO yield(n); n +:= LLONG 2; WHILE n < l maxint - LLONG 2 AND NOT is prime cached(n) DO n +:= LLONG 2 OD OD );   # PROC # gen decompose := (LINT in n, YIELDLINT yield)VOID: ( LINT n := in n; # FOR LINT p IN # gen primes( # ) DO ( # ## (LINT p)VOID: IF p*p > n THEN GO TO done ELSE WHILE n MOD p = LLONG 0 DO yield(p); n := n OVER p OD FI # OD # ); done: IF n > LLONG 1 THEN yield(n) FI );   main:( # FOR LINT m IN # gen primes( # ) DO ( # ## (LINT m)VOID:( LINT p = LLONG 2 ** LSHORTEN m - LLONG 1; print(("2**",whole(m,0),"-1 = ",whole(p,0),", with factors:")); # FOR LINT factor IN # gen decompose(p, # ) DO ( # ## (LINT factor)VOID: print((" ",whole(factor,0))) # OD # ); print(new line); IF m >= LLONG 59 THEN GO TO done FI # OD # )); done: EMPTY )
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#AutoHotkey
AutoHotkey
If !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp }   OnExit, Exit gdip1()   incr := 0 π := 3.141592653589793 loop { incr := Mod(incr + 0.05, 360) x1 := Width/2 y1 := Height/2 length := 5 angle := incr Gdip_FillRoundedRectangle(G, pBrush, 0, 0, Width, Height, 0) loop 150 { x2 := x1 + length * Cos(angle * π/180) y2 := y1 + length * Sin(angle * π/180) Gdip_DrawLine(G, pPen, x1, y1, x2, y2) x1 := x2 y1 := y2 length := length + 3 angle := Mod(angle + incr, 360) } UpdateLayeredWindow(hwnd1, hdc, -1, -1, Width, Height) Sleep 25 } return ;---------------------------------------------------------------- Esc:: Pause, toggle ^Esc::ExitApp ;---------------------------------------------------------------- gdip1(){ global Width := A_ScreenWidth+1, Height := A_ScreenHeight+1 Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop Gui, 1: Show, NA hwnd1 := WinExist() hbm := CreateDIBSection(Width, Height) hdc := CreateCompatibleDC() obm := SelectObject(hdc, hbm) G := Gdip_GraphicsFromHDC(hdc) Gdip_SetSmoothingMode(G, 4) pBrush := Gdip_BrushCreateSolid("0xFF000000") pPen := Gdip_CreatePen("0xFF00FF00", 1) } ;---------------------------------------------------------------- gdip2(){ global Gdip_DeletePen(pPen) Gdip_DeleteBrush(pBrush) SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) } ;---------------------------------------------------------------- Exit: gdip2() Gdip_Shutdown(pToken) ExitApp Return ;----------------------------------------------------------------
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program testPrime64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStartPgm: .asciz "Program start \n" szMessEndPgm: .asciz "Program normal end.\n" szMessNotPrime: .asciz "Not prime.\n" szMessPrime: .asciz "Prime\n" szCarriageReturn: .asciz "\n"   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // program start ldr x0,qAdrszMessStartPgm // display start message bl affichageMess ldr x0,qVal bl isPrime // test prime ? cmp x0,#0 beq 1f ldr x0,qAdrszMessPrime // yes bl affichageMess b 2f 1: ldr x0,qAdrszMessNotPrime // no bl affichageMess 2:   ldr x0,qAdrszMessEndPgm // display end message bl affichageMess   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform system call qAdrszMessStartPgm: .quad szMessStartPgm qAdrszMessEndPgm: .quad szMessEndPgm qAdrszCarriageReturn: .quad szCarriageReturn qAdrszMessNotPrime: .quad szMessNotPrime qAdrszMessPrime: .quad szMessPrime //qVal: .quad 1042441 // test not prime //qVal: .quad 1046527 // test prime //qVal: .quad 37811 // test prime //qVal: .quad 1429671721 // test not prime (37811 * 37811) qVal: .quad 100000004437 // test prime /******************************************************************/ /* test if number is prime */ /******************************************************************/ /* x0 contains the number */ /* x0 return 1 if prime else return 0 */ isPrime: stp x1,lr,[sp,-16]! // save registers cmp x0,1 // <= 1 ? ble 98f cmp x0,3 // 2 and 3 prime ble 97f tst x0,1 // even ? beq 98f mov x11,3 // first divisor 1: udiv x12,x0,x11 msub x13,x12,x11,x0 // compute remainder cbz x13,98f // end if zero add x11,x11,#2 // increment divisor cmp x11,x12 // divisors<=quotient ? ble 1b // loop 97: mov x0,1 // return prime b 100f 98: mov x0,0 // not prime b 100f 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#AppleScript
AppleScript
-- This handler just returns the standardised real value. It's up to external processes to format it for display.   on standardisePrice(input) set integerPart to input div 1.0 set fractionalPart to input mod 1.0   if (fractionalPart is 0.0) then return input as real else if (fractionalPart < 0.06) then return integerPart + 0.1 else if (fractionalPart < 0.16) then return integerPart + 0.18 + (fractionalPart - 0.06) div 0.05 * 0.08 else if (fractionalPart < 0.36) then return integerPart + 0.32 + (fractionalPart - 0.16) div 0.05 * 0.06 else if (fractionalPart < 0.96) then return integerPart + 0.54 + (fractionalPart - 0.36) div 0.05 * 0.04 else return integerPart + 1.0 end if end standardisePrice   -- Test code: set originals to {} set standardised to {} repeat 20 times set price to (random number 100) / 100 set end of originals to text 2 thru -2 of ((price + 10.001) as text) set end of standardised to text 2 thru -2 of ((standardisePrice(price) + 10.001) as text) end repeat   set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to ", " set output to linefeed & "Originals: " & originals & linefeed & "Standardised: " & standardised set AppleScript's text item delimiters to astid return output
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
#Component_Pascal
Component Pascal
  MODULE RosettaProperDivisor; IMPORT StdLog;   PROCEDURE Pd*(n: LONGINT;OUT r: ARRAY OF LONGINT):LONGINT; VAR i,j: LONGINT; BEGIN i := 1;j := 0; IF n > 1 THEN WHILE (i < n) DO IF (n MOD i) = 0 THEN IF (j < LEN(r)) THEN r[j] := i END; INC(j) END; INC(i) END; END; RETURN j END Pd;   PROCEDURE Do*; VAR r: ARRAY 128 OF LONGINT; i,j,found,max,idxMx: LONGINT; mx: ARRAY 128 OF LONGINT; BEGIN FOR i := 1 TO 10 DO found := Pd(i,r); IF found > LEN(r) THEN (* Error. more pd than r can admit *) HALT(1) END; StdLog.Int(i);StdLog.String("[");StdLog.Int(found);StdLog.String("]:> "); FOR j := 0 TO found - 1 DO StdLog.Int(r[j]);StdLog.Char(' '); END; StdLog.Ln END;   max := 0;idxMx := 0; FOR i := 1 TO 20000 DO found := Pd(i,r); IF found > max THEN idxMx:= 0;mx[idxMx] := i;max := found ELSIF found = max THEN INC(idxMx);mx[idxMx] := i END; END; StdLog.String("Found: ");StdLog.Int(idxMx + 1); StdLog.String(" Numbers with the longest proper divisors ["); StdLog.Int(max);StdLog.String("]: ");StdLog.Ln; FOR i := 0 TO idxMx DO StdLog.Int(mx[i]);StdLog.Ln END END Do;   END RosettaProperDivisor.   ^Q RosettaProperDivisor.Do~  
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)
#ERRE
ERRE
PROGRAM PROB_CHOICE   DIM ITEM$[7],PROB[7],CNT[7]   BEGIN ITEM$[]=("aleph","beth","gimel","daleth","he","waw","zayin","heth")   PROB[0]=1/5.0 PROB[1]=1/6.0 PROB[2]=1/7.0 PROB[3]=1/8.0 PROB[4]=1/9.0 PROB[5]=1/10.0 PROB[6]=1/11.0 PROB[7]=1759/27720 SUM=0 FOR I%=0 TO UBOUND(PROB,1) DO SUM=SUM+PROB[I%] END FOR   IF ABS(SUM-1)>1E-6 THEN PRINT("Probabilities don't sum to 1") ELSE FOR TRIAL=1 TO 1E6 DO R=RND(1) P=0 FOR I%=0 TO UBOUND(PROB,1) DO P+=PROB[I%] IF R<P THEN CNT[I%]+=1 EXIT END IF END FOR END FOR PRINT("Item actual theoretical") PRINT("---------------------------------") FOR I%=0 TO UBOUND(ITEM$,1) DO WRITE("\ \ #.###### #.######";ITEM$[I%],CNT[I%]/1E6,PROB[I%]) END FOR END IF END PROGRAM
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)
#Euphoria
Euphoria
constant MAX = #3FFFFFFF constant times = 1e6 atom d,e sequence Mapps Mapps = { { "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, 0} }   for i = 1 to times do d = (rand(MAX)-1)/MAX e = 0 for j = 1 to length(Mapps) do e += Mapps[j][2] if d <= e then Mapps[j][3] += 1 exit end if end for end for   printf(1,"Sample times: %d\n",times) for j = 1 to length(Mapps) do d = Mapps[j][3]/times printf(1,"%-7s should be %f is %f | Deviatation %6.3f%%\n", {Mapps[j][1],Mapps[j][2],d,(1-Mapps[j][2]/d)*100}) end for
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
#Sidef
Sidef
var maxsum = 99 var primes = maxsum.primes   var descendants = (maxsum+1).of { [] } var ancestors = (maxsum+1).of { [] }   for p in (primes) { descendants[p] << p for s in (1 .. descendants.end-p) { descendants[s + p] << descendants[s].map {|q| p*q }... } }   for p in (primes + [4]) { descendants[p].pop }   var total = 0   for s in (1 .. maxsum) {   descendants[s].sort!   total += (var dsclen = descendants[s].len) var idx = descendants[s].first_index {|x| x > maxsum }   for d in (descendants[s].slice(0, idx)) { ancestors[d] = (ancestors[s] + [s]) }   if ((s <= 20) || (s ~~ [46, 74, 99])) { printf("%2d: %d Ancestor(s): %-15s %5s Descendant(s): %s\n", s, ancestors[s].len, "[#{ancestors[s].join(' ')}]", descendants[s].len, dsclen <= 10 ? descendants[s] : "[#{descendants[s].first(10).join(' ')} ...]") } }   say "\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.
#Delphi
Delphi
program Priority_queue;   {$APPTYPE CONSOLE}   uses System.SysUtils, Boost.Generics.Collection;   var Queue: TPriorityQueue<String>;   begin Queue := TPriorityQueue<String>.Create(['Clear drains', 'Feed cat', 'Make tea', 'Solve RC tasks', 'Tax return'], [3, 4, 5, 1, 2]);   while not Queue.IsEmpty do with Queue.DequeueEx do Writeln(Priority, ', ', value); end.
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.
#Julia
Julia
using Printf   module ApolloniusProblems   using Polynomials export Circle   struct Point{T<:Real} x::T y::T end   xcoord(p::Point) = p.x ycoord(p::Point) = p.y   struct Circle{T<:Real} c::Point{T} r::T end Circle(x::T, y::T, r::T) where T<:Real = Circle(Point(x, y), r)   radius(c::Circle) = c.r center(c::Circle) = c.c xcenter(c::Circle) = xcoord(center(c)) ycenter(c::Circle) = ycoord(center(c))   Base.show(io::IO, c::Circle) = @printf(io, "centered at (%0.4f, %0.4f) with radius %0.4f", xcenter(c), ycenter(c), radius(c))   function solve(ap::Vector{Circle{T}}, enc=()) where T<:Real length(ap) == 3 || error("This Apollonius problem needs 3 circles.") x = @. xcenter(ap) y = @. ycenter(ap) r = map(u -> ifelse(u ∈ enc, -1, 1), 1:3) .* radius.(ap) @views begin a = 2x[1] .- 2x[2:3] b = 2y[1] .- 2y[2:3] c = 2r[1] .- 2r[2:3] d = (x[1] ^ 2 + y[1] ^ 2 - r[1] ^ 2) .- (x[2:3] .^ 2 .+ y[2:3] .^ 2 .- r[2:3] .^ 2) end u = Poly([-det([b d]), det([b c])] ./ det([a b])) v = Poly([det([a d]), -det([a c])] ./ det([a b])) w = Poly([r[1], 1.0]) ^ 2 s = (u - x[1]) ^ 2 + (v - y[1]) ^ 2 - w r = filter(x -> iszero(imag(x)) && x > zero(x), roots(s)) length(r) < 2 || error("The solution is not unique.") length(r) == 1 || error("There is no solution.") r = r[1] return Circle(polyval(u, r), polyval(v, r), r) end   end # module ApolloniusProblem
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.
#Kotlin
Kotlin
// version 1.1.3   data class Circle(val x: Double, val y: Double, val r: Double)   val Double.sq get() = this * this   fun solveApollonius(c1: Circle, c2: Circle, c3: Circle, s1: Int, s2: Int, s3: Int): Circle { val (x1, y1, r1) = c1 val (x2, y2, r2) = c2 val (x3, y3, r3) = c3   val v11 = 2 * x2 - 2 * x1 val v12 = 2 * y2 - 2 * y1 val v13 = x1.sq - x2.sq + y1.sq - y2.sq - r1.sq + r2.sq val v14 = 2 * s2 * r2 - 2 * s1 * r1   val v21 = 2 * x3 - 2 * x2 val v22 = 2 * y3 - 2 * y2 val v23 = x2.sq - x3.sq + y2.sq - y3.sq - r2.sq + r3.sq val v24 = 2 * s3 * r3 - 2 * s2 * r2   val w12 = v12 / v11 val w13 = v13 / v11 val w14 = v14 / v11   val w22 = v22 / v21 - w12 val w23 = v23 / v21 - w13 val w24 = v24 / v21 - w14   val p = -w23 / w22 val q = w24 / w22 val m = -w12 * p - w13 val n = w14 - w12 * q   val a = n.sq + q.sq - 1 val b = 2 * m * n - 2 * n * x1 + 2 * p * q - 2 * q * y1 + 2 * s1 * r1 val c = x1.sq + m.sq - 2 * m * x1 + p.sq + y1.sq - 2 * p * y1 - r1.sq   val d = b.sq - 4 * a * c val rs = (-b - Math.sqrt(d)) / (2 * a) val xs = m + n * rs val ys = p + q * rs return Circle(xs, ys, rs) }   fun main(args: Array<String>) { val c1 = Circle(0.0, 0.0, 1.0) val c2 = Circle(4.0, 0.0, 1.0) val c3 = Circle(2.0, 4.0, 2.0) println(solveApollonius(c1, c2, c3, 1, 1, 1)) println(solveApollonius(c1, c2, c3,-1,-1,-1)) }
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.
#Phixmonti
Phixmonti
argument 1 get ?
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.
#PHP
PHP
<?php $program = $_SERVER["SCRIPT_NAME"]; echo "Program: $program\n"; ?>
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Phix
Phix
with javascript_semantics atom total, prim, maxPeri = 10 procedure tri(atom s0, s1, s2) atom p = s0 + s1 + s2 if p<=maxPeri then prim += 1 total += floor(maxPeri/p) tri( s0+2*(-s1+s2), 2*( s0+s2)-s1, 2*( s0-s1+s2)+s2); tri( s0+2*( s1+s2), 2*( s0+s2)+s1, 2*( s0+s1+s2)+s2); tri(-s0+2*( s1+s2), 2*(-s0+s2)+s1, 2*(-s0+s1+s2)+s2); end if end procedure while maxPeri<=1e8 do prim := 0; total := 0; tri(3, 4, 5); printf(1,"Up to %d: %d triples, %d primitives.\n", {maxPeri,total,prim}) maxPeri *= 10; end while
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.
#Nim
Nim
if problem1: quit QuitFailure   if problem2: quit "There is a problem", QuitFailure
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.
#Oberon-2
Oberon-2
  IF problem THEN HALT(1) 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
#Erlang
Erlang
  #! /usr/bin/escript   isprime(N) when N < 2 -> false; isprime(N) when N band 1 =:= 0 -> N =:= 2; isprime(N) -> fac_mod(N - 1, N) =:= N - 1.   fac_mod(N, M) -> fac_mod(N, M, 1). fac_mod(1, _, A) -> A; fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).   main(_) -> io:format("The first few primes (via Wilson's theorem) are: ~n~p~n", [[K || K <- lists:seq(1, 128), isprime(K)]]).  
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
#F.23
F#
  // Wilsons theorem. Nigel Galloway: August 11th., 2020 let wP(n,g)=(n+1I)%g=0I let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n" fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
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 %
#J
J
/:~ (~.,. ' ',. ":@(%/&1 999999)@(#/.~)) 2 (,'->',])&":/\ 10|p:i.1e6 1->1 42853 0.042853 1->3 77475 0.0774751 1->7 79453 0.0794531 1->9 50153 0.0501531 2->3 1 1e_6 3->1 58255 0.0582551 3->3 39668 0.039668 3->5 1 1e_6 3->7 72827 0.0728271 3->9 79358 0.0793581 5->7 1 1e_6 7->1 64230 0.0642301 7->3 68595 0.0685951 7->7 39603 0.039603 7->9 77586 0.0775861 9->1 84596 0.0845961 9->3 64371 0.0643711 9->7 58130 0.0581301 9->9 42843 0.042843
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 %
#Java
Java
public class PrimeConspiracy {   public static void main(String[] args) { final int limit = 1000_000; final int sieveLimit = 15_500_000;   int[][] buckets = new int[10][10]; int prevDigit = 2; boolean[] 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) { System.out.printf("%d -> %d : %2f%n", i, j, buckets[i][j] / (limit / 100.0)); } } } }   public static boolean[] sieve(int limit) { boolean[] composite = new boolean[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/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
#ALGOL-M
ALGOL-M
  BEGIN   INTEGER I, K, NFOUND; INTEGER ARRAY FACTORS[1:16];   COMMENT COMPUTE P MOD Q; INTEGER FUNCTION MOD (P, Q); INTEGER P, Q; BEGIN MOD := P - Q * (P / Q); END;   COMMENT FIND THE PRIME FACTORS OF N AND STORE IN THE EXTERNAL ARRAY "FACTORS", RETURNING THE NUMBER FOUND. IF N IS PRIME, IT WILL BE STORED AS THE FIRST AND ONLY FACTOR;   INTEGER FUNCTION PRIMEFACTORS(N); INTEGER N; BEGIN INTEGER P, COUNT; P := 2; COUNT := 1; WHILE N >= P * P DO BEGIN IF MOD(N, P) = 0 THEN BEGIN FACTORS[COUNT] := P; COUNT := COUNT + 1; N := N / P; END ELSE P := P + 1; END; FACTORS[COUNT] := N; PRIMEFACTORS := COUNT; END;   COMMENT -- EXERCISE THE ROUTINE;   FOR I := 77 STEP 2 UNTIL 99 DO BEGIN WRITE(I,":"); NFOUND := PRIMEFACTORS(I); FOR K := 1 STEP 1 UNTIL NFOUND DO BEGIN WRITEON(FACTORS[K]); END; END;   END  
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#C
C
  #include<graphics.h> #include<math.h>   #define factor M_PI/180 #define LAG 1000   void polySpiral(int windowWidth,int windowHeight){ int incr = 0, angle, i, length; double x,y,x1,y1;   while(1){ incr = (incr + 5)%360;   x = windowWidth/2; y = windowHeight/2;   length = 5; angle = incr;   for(i=1;i<=150;i++){ x1 = x + length*cos(factor*angle); y1 = y + length*sin(factor*angle); line(x,y,x1,y1);   length += 3;   angle = (angle + incr)%360;   x = x1; y = y1; } delay(LAG); cleardevice(); } }   int main() { initwindow(500,500,"Polyspiral");   polySpiral(500,500);   closegraph();   return 0; }  
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#11l
11l
F list_powerset(lst) V result = [[Int]()] L(x) lst result.extend(result.map(subset -> subset [+] [@x])) R result   print(list_powerset([1, 2, 3]))
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#ABAP
ABAP
class ZMLA_ROSETTA definition public create public .   public section.   types: enumber TYPE N LENGTH 60 . types: listof_enumber TYPE TABLE OF enumber .   class-methods IS_PRIME importing value(N) type ENUMBER returning value(OFLAG) type ABAP_BOOL . class-methods IS_PRIME_I importing value(N) type I returning value(OFLAG) type ABAP_BOOL . protected section. private section. ENDCLASS.       CLASS ZMLA_ROSETTA IMPLEMENTATION.     * <SIGNATURE>---------------------------------------------------------------------------------------+ * | Static Public Method ZMLA_ROSETTA=>IS_PRIME * +-------------------------------------------------------------------------------------------------+ * | [--->] N TYPE ENUMBER * | [<-()] OFLAG TYPE ABAP_BOOL * +--------------------------------------------------------------------------------------</SIGNATURE> method IS_PRIME. IF n < 2. oflag = abap_false. RETURN. ENDIF. IF n = 2 or n = 3. oflag = abap_true. RETURN. ENDIF. IF n mod 2 = 0 or n mod 3 = 0. oflag = abap_false. RETURN. ENDIF. DATA: lim type enumber, d type enumber, i TYPE i VALUE 2. lim = sqrt( n ). d = 5. WHILE d <= lim. IF n mod d = 0. oflag = abap_false. RETURN. ENDIF. d = d + i. i = 6 - i. " this modifies 2 into 4 and viceversa ENDWHILE. oflag = abap_true. RETURN. endmethod.     * <SIGNATURE>---------------------------------------------------------------------------------------+ * | Static Public Method ZMLA_ROSETTA=>IS_PRIME_I * +-------------------------------------------------------------------------------------------------+ * | [--->] N TYPE I * | [<-()] OFLAG TYPE ABAP_BOOL * +--------------------------------------------------------------------------------------</SIGNATURE> method IS_PRIME_I. IF n < 2. oflag = abap_false. RETURN. ENDIF. IF n = 2 or n = 3. oflag = abap_true. RETURN. ENDIF. IF n mod 2 = 0 or n mod 3 = 0. oflag = abap_false. RETURN. ENDIF. DATA: lim type i, d type i, i TYPE i VALUE 2. lim = sqrt( n ). d = 5. WHILE d <= lim. IF n mod d = 0. oflag = abap_false. RETURN. ENDIF. d = d + i. i = 6 - i. " this modifies 2 into 4 and viceversa ENDWHILE. oflag = abap_true. RETURN. endmethod. ENDCLASS.
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#Arturo
Arturo
pricePoints: [ 0.06 0.10 0.11 0.18 0.16 0.26 0.21 0.32 0.26 0.38 0.31 0.44 0.36 0.50 0.41 0.54 0.46 0.58 0.51 0.62 0.56 0.66 0.61 0.70 0.66 0.74 0.71 0.78 0.76 0.82 0.81 0.86 0.86 0.90 0.91 0.94 0.96 0.98 1.01 1.00 ]   getPricePoint: function [price][ loop pricePoints [limit,correct][ if price < limit -> return correct ] ]   tests: [0.3793 0.4425 0.0746 0.6918 0.2993 0.5486 0.7849 0.9383 0.2292]   loop tests 'test [ print [test "=>" getPricePoint test] ]
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
#D
D
void main() /*@safe*/ { import std.stdio, std.algorithm, std.range, std.typecons;   immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ => iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x);   iota(1, 11).map!properDivs.writeln; iota(1, 20_001).map!(n => tuple(properDivs(n).count, n)).reduce!max.writeln; }
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)
#Factor
Factor
USING: arrays assocs combinators.random io kernel macros math math.statistics prettyprint quotations sequences sorting formatting ; IN: rosettacode.proba   CONSTANT: data { { "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" f } }   MACRO: case-probas ( data -- case-probas ) [ first2 [ swap 1quotation 2array ] [ 1quotation ] if* ] map 1quotation ;   : expected ( name data -- float ) 2dup at [ 2nip ] [ nip values sift sum 1 swap - ] if* ; : generate ( # case-probas -- seq ) H{ } clone [ [ [ casep ] [ inc-at ] bi* ] 2curry times ] keep ; inline : normalize ( seq # -- seq ) [ clone ] dip [ /f ] curry assoc-map ; : summarize1 ( name value data -- ) [ over ] dip expected "%6s: %10f %10f\n" printf ; : summarize ( generated data -- ) "Key" "Value" "expected" "%6s  %10s %10s\n" printf [ summarize1 ] curry assoc-each ; : generate-normalized ( # proba -- seq ) [ generate ] [ drop normalize ] 2bi ; inline : example ( # data -- ) [ case-probas generate-normalized ] [ summarize ] bi ; inline
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)
#Fermat
Fermat
  trials:=1000000;   Array probs[8]; {store the probabilities} [probs]:=[<i=1,8> 1/(i+4)]; probs[8]:=1-Sigma<i=1,7>[probs[i,1]];   Func Round( a, b ) = (2*a+b)\(2*b).; {rounds a fraction with numerator a and denominator b}  ; {to the nearest integer (positive fractions only)}   Func Sel = {select a number from 1 to 8 according to the} r:=Rand|27720; {specified probabilities} if r < probs[1]*27720 then Return(1) fi; if r < Sigma<i=1,2>[probs[i]]*27720 then Return(2) fi; if r < Sigma<i=1,3>[probs[i]]*27720 then Return(3) fi; if r < Sigma<i=1,4>[probs[i]]*27720 then Return(4) fi; if r < Sigma<i=1,5>[probs[i]]*27720 then Return(5) fi; if r < Sigma<i=1,6>[probs[i]]*27720 then Return(6) fi; if r < Sigma<i=1,7>[probs[i]]*27720 then Return(7) fi; Return(8); .;   Array label[10]; {strings are not Fermat's strong suit} Func Letter(n) = {assign a Hebrew letter to the numbers 1-8} [label]:='heth '; if n = 1 then [label]:='aleph ' fi; if n = 2 then [label]:='beth ' fi; if n = 3 then [label]:='gimel ' fi; if n = 4 then [label]:='daleth ' fi; if n = 5 then [label]:='he ' fi; if n = 6 then [label]:='waw ' fi; if n = 7 then [label]:='zayin ' fi; .;   Array count[8]; {pick a bunch of random numbers} for i = 1 to trials do s:=Sel; count[s]:=count[s]+1; od;   for i = 1 to 8 do {now display some diagnostics} Letter(i); ctp:=count[i]/trials-probs[i];  !([label:char, count[i]/trials,' differs from ',probs[i]);  !(' by ',ctp, ' or about one part in ', Round(Denom(ctp),|Numer(ctp)|));  !!; od;   !!('The various probabilities add up to ',Sigma<i=1,8>[count[i]/trials]); {check if our trials add to 1}  
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
#Simula
Simula
COMMENT cim --memory-pool-size=512 allocate-descendants-to-their-ancestors.sim ; BEGIN     COMMENT ABSTRACT FRAMEWORK CLASSES ;   CLASS ITEM; BEGIN END ITEM;   CLASS ITEMLIST; BEGIN   CLASS ITEMARRAY(N); INTEGER N; BEGIN REF(ITEM) ARRAY DATA(0:N-1); END ITEMARRAY;   PROCEDURE EXPAND(N); INTEGER N; BEGIN INTEGER I; REF(ITEMARRAY) TEMP; TEMP :- NEW ITEMARRAY(N); FOR I := 0 STEP 1 UNTIL SIZE-1 DO TEMP.DATA(I) :- ITEMS.DATA(I); ITEMS :- TEMP; END EXPAND;   PROCEDURE APPEND(RI); REF(ITEM) RI; BEGIN IF SIZE + 1 > CAPACITY THEN BEGIN CAPACITY := 2 * CAPACITY; EXPAND(CAPACITY); END; ITEMS.DATA(SIZE) :- RI; SIZE := SIZE + 1; END APPEND;   PROCEDURE APPENDALL(IL); REF(ITEMLIST) IL; BEGIN INTEGER I; FOR I := 0 STEP 1 UNTIL IL.SIZE-1 DO APPEND(IL.ELEMENT(I)); END APPENDALL;   REF(ITEM) PROCEDURE ELEMENT(I); INTEGER I; BEGIN IF I < 0 OR I > SIZE-1 THEN ERROR("ELEMENT: INDEX OUT OF BOUNDS"); ELEMENT :- ITEMS.DATA(I); END ELEMENT;   REF(ITEM) PROCEDURE SETELEMENT(I, IT); INTEGER I; REF(ITEM) IT; BEGIN IF I < 0 OR I > SIZE-1 THEN ERROR("SETELEMENT: INDEX OUT OF BOUNDS"); ITEMS.DATA(I) :- IT; END SETELEMENT;   REF(ITEM) PROCEDURE POP; BEGIN REF(ITEM) RESULT; IF SIZE=0 THEN ERROR("POP: EMPTY ITEMLIST"); RESULT :- ITEMS.DATA(SIZE-1); ITEMS.DATA(SIZE-1) :- NONE; SIZE := SIZE-1; POP :- RESULT; END POP;   PROCEDURE SORT(COMPARE_PROC); PROCEDURE COMPARE_PROC IS INTEGER PROCEDURE COMPARE_PROC(IT1,IT2); REF(ITEM) IT1,IT2;; BEGIN PROCEDURE SWAP(I,J); INTEGER I,J; BEGIN REF(ITEM) T; T :- ITEMS.DATA(I); ITEMS.DATA(I) :- ITEMS.DATA(J); ITEMS.DATA(J) :- T; END SWAP; PROCEDURE QUICKSORT(L,R); INTEGER L,R; BEGIN REF(ITEM) PIVOT; INTEGER I, J; PIVOT :- ITEMS.DATA((L+R)//2); I := L; J := R; WHILE I <= J DO BEGIN WHILE COMPARE_PROC(ITEMS.DATA(I), PIVOT) < 0 DO I := I+1; WHILE COMPARE_PROC(PIVOT, ITEMS.DATA(J)) < 0 DO J := J-1; IF I <= J THEN BEGIN SWAP(I,J); I := I+1; J := J-1; END; END; IF L < J THEN QUICKSORT(L, J); IF I < R THEN QUICKSORT(I, R); END QUICKSORT; IF SIZE >= 2 THEN QUICKSORT(0,SIZE-1); END SORT;   INTEGER CAPACITY; INTEGER SIZE; REF(ITEMARRAY) ITEMS;   CAPACITY := 20; SIZE := 0; EXPAND(CAPACITY); END ITEMLIST;     COMMENT PROBLEM SPECIFIC PART ;     ITEM CLASS REALITEM(X); LONG REAL X; BEGIN END REALITEM;   ITEMLIST CLASS LIST_OF_REAL; BEGIN LONG REAL PROCEDURE ELEMENT(I); INTEGER I; ELEMENT := ITEMS.DATA(I) QUA REALITEM.X;   PROCEDURE APPEND(X); LONG REAL X; THIS ITEMLIST.APPEND(NEW REALITEM(X));   PROCEDURE SORT; BEGIN INTEGER PROCEDURE CMP(IT1,IT2); REF(ITEM) IT1,IT2; CMP := IF IT1 QUA REALITEM.X < IT2 QUA REALITEM.X THEN -1 ELSE IF IT1 QUA REALITEM.X > IT2 QUA REALITEM.X THEN +1 ELSE 0; THIS ITEMLIST.SORT(CMP); END SORT;   PROCEDURE OUTLIST; BEGIN INTEGER I; TEXT FMT; OUTTEXT("["); FMT :- BLANKS(20); FOR I := 0 STEP 1 UNTIL SIZE-1 DO BEGIN IF I < 3 OR I > SIZE-1-3 THEN BEGIN IF I > 0 THEN OUTTEXT(", "); FMT.PUTFIX(ELEMENT(I), 0); FMT.SETPOS(1); WHILE FMT.MORE DO BEGIN CHARACTER C; C := FMT.GETCHAR; IF C <> ' ' THEN OUTCHAR(C); END END ELSE BEGIN OUTTEXT(", ..."); I := SIZE-1-3; END; END; OUTTEXT("]"); END OUTLIST; END LIST_OF_REAL;     ITEM CLASS REALLISTITEM(LRL); REF(LIST_OF_REAL) LRL; BEGIN END REALLISTITEM;   ITEMLIST CLASS LIST_OF_REALLIST; BEGIN REF(LIST_OF_REAL) PROCEDURE ELEMENT(I); INTEGER I; ELEMENT :- ITEMS.DATA(I) QUA REALLISTITEM.LRL;   PROCEDURE APPEND(LRL); REF(LIST_OF_REAL) LRL; THIS ITEMLIST.APPEND(NEW REALLISTITEM(LRL));   PROCEDURE OUTLIST; BEGIN INTEGER I; OUTTEXT("["); FOR I := 0 STEP 1 UNTIL SIZE-1 DO BEGIN IF I > 0 THEN OUTTEXT(", "); ELEMENT(I).OUTLIST; END; OUTTEXT("]"); END OUTLIST; END LIST_OF_REALLIST;   REF(LIST_OF_REAL) PROCEDURE GET_PRIMES(MAX); INTEGER MAX; BEGIN REF(LIST_OF_REAL) LPRIMES; LPRIMES :- NEW LIST_OF_REAL; IF MAX < 2 THEN GOTO RETURN ELSE BEGIN INTEGER X; LPRIMES.APPEND(2); FOR X := 3 STEP 2 UNTIL MAX DO BEGIN INTEGER I; LONG REAL P; FOR I := 0 STEP 1 UNTIL LPRIMES.SIZE-1 DO BEGIN P := LPRIMES.ELEMENT(I); IF (X / P) = ENTIER(X / P) THEN GOTO BREAK; END; LPRIMES.APPEND(X); BREAK: END; END; RETURN: GET_PRIMES :- LPRIMES; END GET_PRIMES;   INTEGER MAXSUM, I, S, PRI, TOTAL, DI; REF(LIST_OF_REALLIST) DESCENDANTS, ANCESTORS; REF(LIST_OF_REAL) PRIMES, LR, LRS; LONG REAL P, D, PR; BOOLEAN TAKEWHILE; MAXSUM := 99;   DESCENDANTS :- NEW LIST_OF_REALLIST; ANCESTORS  :- NEW LIST_OF_REALLIST; FOR I := 0 STEP 1 UNTIL MAXSUM DO BEGIN DESCENDANTS.APPEND(NEW LIST_OF_REAL); ANCESTORS .APPEND(NEW LIST_OF_REAL); END;   PRIMES :- GET_PRIMES(MAXSUM);   FOR I := 0 STEP 1 UNTIL PRIMES.SIZE-1 DO BEGIN P := PRIMES.ELEMENT(I); DESCENDANTS.ELEMENT(P).APPEND(P); FOR S := 1 STEP 1 UNTIL DESCENDANTS.SIZE-P-1 DO BEGIN LRS :- DESCENDANTS.ELEMENT(S); FOR PRI := 0 STEP 1 UNTIL LRS.SIZE-1 DO BEGIN PR := LRS.ELEMENT(PRI); DESCENDANTS.ELEMENT(S + P).APPEND(P * PR); END; END; END;   FOR I := 0 STEP 1 UNTIL PRIMES.SIZE-1 DO BEGIN P := PRIMES.ELEMENT(I); DESCENDANTS.ELEMENT(P).POP; END; DESCENDANTS.ELEMENT(4).POP;   TOTAL := 0; FOR S := 1 STEP 1 UNTIL MAXSUM DO BEGIN LRS :- DESCENDANTS.ELEMENT(S); LRS.SORT; FOR DI := 0 STEP 1 UNTIL LRS.SIZE-1 DO BEGIN D := LRS.ELEMENT(DI); IF D <= MAXSUM THEN BEGIN REF(LIST_OF_REAL) ANCD; ANCD :- NEW LIST_OF_REAL; ANCD.APPENDALL(ANCESTORS.ELEMENT(S)); ANCD.APPEND(S); ANCESTORS.SETELEMENT(D, NEW REALLISTITEM(ANCD)); END ELSE GOTO BREAK; END; BREAK:   OUTTEXT("["); OUTINT(S, 0); OUTTEXT("] LEVEL: "); OUTINT(ANCESTORS.ELEMENT(S).SIZE, 0); OUTIMAGE;   OUTTEXT("ANCESTORS: "); ANCESTORS.ELEMENT(S).OUTLIST; OUTIMAGE;   OUTTEXT("DESCENDANTS: "); OUTINT(LRS.SIZE,0); OUTIMAGE;   LRS.OUTLIST; OUTIMAGE;   OUTIMAGE; TOTAL := TOTAL + LRS.SIZE; END;   OUTTEXT("TOTAL DESCENDANTS "); OUTINT(TOTAL, 0); OUTIMAGE; 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
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Math   Module Module1 Const MAXPRIME = 99 ' upper bound for the prime factors Const MAXPARENT = 99 ' greatest parent number   Const NBRCHILDREN = 547100 ' max number of children (total descendants)   Public Primes As New Collection() ' table of the prime factors Public PrimesR As New Collection() ' table of the prime factors in reversed order Public Ancestors As New Collection() ' table of the parent's ancestors   Public Parents(MAXPARENT + 1) As Integer ' index table of the root descendant (per parent) Public CptDescendants(MAXPARENT + 1) As Integer ' counter table of the descendants (per parent) Public Children(NBRCHILDREN) As ChildStruct ' table of the whole descendants Public iChildren As Integer ' max index of the Children table   Public Delimiter As String = ", " Public Structure ChildStruct Public Child As Long Public pLower As Integer Public pHigher As Integer End Structure Sub Main() Dim Parent As Short Dim Sum As Short Dim i As Short Dim TotDesc As Integer = 0 Dim MidPrime As Integer   If GetPrimes(Primes, MAXPRIME) = vbFalse Then Return End If   For i = Primes.Count To 1 Step -1 PrimesR.Add(Primes.Item(i)) Next   MidPrime = PrimesR.Item(1) / 2   For Each Prime In PrimesR Parents(Prime) = InsertChild(Parents(Prime), Prime) CptDescendants(Prime) += 1   If Prime > MidPrime Then Continue For End If   For Parent = 1 To MAXPARENT Sum = Parent + Prime   If Sum > MAXPARENT Then Exit For End If   If Parents(Parent) Then InsertPreorder(Parents(Parent), Sum, Prime) CptDescendants(Sum) += CptDescendants(Parent) End If Next Next   RemoveFalseChildren()   If MAXPARENT > MAXPRIME Then If GetPrimes(Primes, MAXPARENT) = vbFalse Then Return End If End If   FileOpen(1, "Ancestors.txt", OpenMode.Output)   For Parent = 1 To MAXPARENT GetAncestors(Parent) PrintLine(1, "[" & Parent.ToString & "] Level: " & Ancestors.Count.ToString)   If Ancestors.Count Then Print(1, "Ancestors: " & Ancestors.Item(1).ToString) For i = 2 To Ancestors.Count Print(1, ", " & Ancestors.Item(i).ToString) Next PrintLine(1) Ancestors.Clear() Else PrintLine(1, "Ancestors: None") End If   If CptDescendants(Parent) Then PrintLine(1, "Descendants: " & CptDescendants(Parent).ToString) Delimiter = "" PrintDescendants(Parents(Parent)) PrintLine(1) TotDesc += CptDescendants(Parent) Else PrintLine(1, "Descendants: None") End If   PrintLine(1) Next Primes.Clear() PrimesR.Clear() PrintLine(1, "Total descendants " & TotDesc.ToString) PrintLine(1) FileClose(1) End Sub Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short) Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)   If Children(_index).pLower Then InsertPreorder(Children(_index).pLower, _sum, _prime) End If   If Children(_index).pHigher Then InsertPreorder(Children(_index).pHigher, _sum, _prime) End If   Return Nothing End Function Function InsertChild(_index As Integer, _child As Long) As Integer If _index Then If _child <= Children(_index).Child Then Children(_index).pLower = InsertChild(Children(_index).pLower, _child) Else Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child) End If Else iChildren += 1 _index = iChildren Children(_index).Child = _child Children(_index).pLower = 0 Children(_index).pHigher = 0 End If   Return _index End Function Function RemoveFalseChildren() Dim Exclusions As New Collection   Exclusions.Add(4) For Each Prime In Primes Exclusions.Add(Prime) Next   For Each ex In Exclusions Parents(ex) = Children(Parents(ex)).pHigher CptDescendants(ex) -= 1 Next   Exclusions.Clear() Return Nothing End Function Function GetAncestors(_child As Short) Dim Child As Short = _child Dim Parent As Short = 0   For Each Prime In Primes If Child = 1 Then Exit For End If While Child Mod Prime = 0 Child /= Prime Parent += Prime End While Next   If Parent = _child Or _child = 1 Then Return Nothing End If   GetAncestors(Parent) Ancestors.Add(Parent) Return Nothing End Function Function PrintDescendants(_index As Integer) If Children(_index).pLower Then PrintDescendants(Children(_index).pLower) End If   Print(1, Delimiter.ToString & Children(_index).Child.ToString) Delimiter = ", "   If Children(_index).pHigher Then PrintDescendants(Children(_index).pHigher) End If   Return Nothing End Function Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean Dim Value As Integer = 3 Dim Max As Integer Dim Prime As Integer   If _maxPrime < 2 Then Return vbFalse End If   _primes.Add(2)   While Value <= _maxPrime Max = Floor(Sqrt(Value))   For Each Prime In _primes If Prime > Max Then _primes.Add(Value) Exit For End If   If Value Mod Prime = 0 Then Exit For End If Next   Value += 2 End While   Return vbTrue End Function End Module
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.
#EchoLisp
EchoLisp
  (lib 'tree) (define tasks (make-bin-tree 3 "Clear drains")) (bin-tree-insert tasks 2 "Tax return") (bin-tree-insert tasks 5 "Make tea") (bin-tree-insert tasks 1 "Solve RC tasks") (bin-tree-insert tasks 4 "Feed 🐡")   (bin-tree-pop-first tasks) → (1 . "Solve RC tasks") (bin-tree-pop-first tasks) → (2 . "Tax return") (bin-tree-pop-first tasks) → (3 . "Clear drains") (bin-tree-pop-first tasks) → (4 . "Feed 🐡") (bin-tree-pop-first tasks) → (5 . "Make tea") (bin-tree-pop-first tasks) → null   ;; similarly (bin-tree-pop-last tasks) → (5 . "Make tea") (bin-tree-pop-last tasks) → (4 . "Feed 🐡") ; etc.  
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.
#Lasso
Lasso
define solveApollonius(c1, c2, c3, s1, s2, s3) => { local( x1 = decimal(#c1->get(1)), y1 = decimal(#c1->get(2)), r1 = decimal(#c1->get(3)) ) local( x2 = decimal(#c2->get(1)), y2 = decimal(#c2->get(2)), r2 = decimal(#c2->get(3)) ) local( x3 = decimal(#c3->get(1)), y3 = decimal(#c3->get(2)), r3 = decimal(#c3->get(3)) ) local( 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   )   // Find a root of a quadratic equation. This requires the circle centers not to be e.g. colinear local( D = #b*#b-4*#a*#c, rs = (-#b - #D->sqrt)/(2*#a),   xs = #M+#N*#rs, ys = #P+#Q*#rs ) return (:#xs, #ys, #rs) } // Tests: solveApollonius((:0, 0, 1), (:4, 0, 1), (:2, 4, 2), 1,1,1) solveApollonius((:0, 0, 1), (:4, 0, 1), (:2, 4, 2), -1,-1,-1)  
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.
#Liberty_BASIC
Liberty BASIC
  circle1$ =" 0.000, 0.000, 1.000" circle2$ =" 4.000, 0.000, 1.000" circle3$ =" 2.000, 4.000, 2.000"   print " x_pos y_pos radius" print circle1$ print circle2$ print circle3$ print print ApolloniusSolver$( circle1$, circle2$, circle3$, 1, 1, 1) print ApolloniusSolver$( circle1$, circle2$, circle3$, -1, -1, -1)   end   function ApolloniusSolver$( c1$, c2$, c3$, s1, s2, s3) x1 =val( word$( c1$, 1, ",")): y1 =val( word$( c1$, 2, ",")): r1 =val( word$( c1$, 3, ",")) x2 =val( word$( c2$, 1, ",")): y2 =val( word$( c2$, 2, ",")): r2 =val( word$( c2$, 3, ",")) x3 =val( word$( c3$, 1, ",")): y3 =val( word$( c3$, 2, ",")): r3 =val( word$( c3$, 3, ","))   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   ApolloniusSolver$ =using( "###.###", XPos) +"," +using( "###.###", YPos) +using( "###.###", Radius) end function  
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.
#PicoLisp
PicoLisp
: (cmd) -> "/usr/bin/picolisp"
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.
#PowerBASIC
PowerBASIC
#INCLUDE "Win32API.inc" '[...] DIM fullpath AS ASCIIZ * 260, appname AS STRING GetModuleFileNameA 0, fullpath, 260 IF INSTR(fullpath, "\") THEN appname = MID$(fullpath, INSTR(-1, fullpath, "\") + 1) ELSE appname = fullpath END IF
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
#PHP
PHP
<?php   function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); }   $pytha = 0; $prim = 0; $max_p = 100;   for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break;   if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } }   echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' 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.
#Objeck
Objeck
if(problem) { Runtime->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.
#OCaml
OCaml
if problem then exit integerErrorCode; (* conventionally, error code 0 is the code for "OK", while anything else is an actual problem *)
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
#Factor
Factor
USING: formatting grouping io kernel lists lists.lazy math math.factorials math.functions prettyprint sequences ;   : wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ; : prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ; : primes ( -- list ) 1 lfrom [ prime? ] lfilter ;   "n prime?\n--- -----" print { 2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 } [ dup prime? "%-3d  %u\n" printf ] each nl   "First 120 primes via Wilson's theorem:" print 120 primes ltake list>array 20 group simple-table. nl   "1000th through 1015th primes:" print 16 primes 999 [ cdr ] times ltake list>array [ pprint bl ] each nl
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
#Fermat
Fermat
Func Wilson(n) = if ((n-1)!+1)|n = 0 then 1 else 0 fi.;
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 %
#Julia
Julia
using Printf, Primes using DataStructures   function counttransitions(upto::Integer) cnt = counter(Pair{Int,Int}) tot = 0 prv, nxt = 2, 3 while nxt ≤ upto push!(cnt, prv % 10 => nxt % 10) prv = nxt nxt = nextprime(nxt + 1) tot += 1 end return sort(Dict(cnt)), tot - 1 end   trans, tot = counttransitions(100_000_000)   println("First 100_000_000 primes, last digit transitions:") for ((i, j), fr) in trans @printf("%i → %i: freq. %3.4f%%\n", i, j, 100fr / tot) end
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 %
#Kotlin
Kotlin
// version 1.1.2 // compiled with flag -Xcoroutines=enable to suppress 'experimental' warning   import kotlin.coroutines.experimental.*   typealias Transition = Pair<Int, Int>   fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d : Int = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true }   fun generatePrimes() = buildSequence { yield(2) var p = 3 while (p <= Int.MAX_VALUE) { if (isPrime(p)) yield(p) p += 2 } }   fun main(args: Array<String>) { val primes = generatePrimes().take(1_000_000).toList() val transMap = mutableMapOf<Transition, Int>() for (i in 0 until primes.size - 1) { val transition = primes[i] % 10 to primes[i + 1] % 10 if (transMap.containsKey(transition)) transMap[transition] = transMap[transition]!! + 1 else transMap.put(transition, 1) } val sortedTransitions = transMap.keys.sortedBy { it.second }.sortedBy { it.first } println("First 1,000,000 primes. Transitions prime % 10 -> next-prime % 10.") for (trans in sortedTransitions) { print("${trans.first} -> ${trans.second} count: ${"%5d".format(transMap[trans])}") println(" frequency: ${"%4.2f".format(transMap[trans]!! / 10000.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
#Applesoft_BASIC
Applesoft BASIC
9040 PF(0) = 0 : SC = 0 9050 FOR CA = 2 TO INT( SQR(I)) 9060 IF I = 1 THEN RETURN 9070 IF INT(I / CA) * CA = I THEN GOSUB 9200 : GOTO 9060 9080 CA = CA + SC : SC = 1 9090 NEXT CA 9100 IF I = 1 THEN RETURN 9110 CA = I   9200 PF(0) = PF(0) + 1 9210 PF(PF(0)) = CA 9220 I = I / CA 9230 RETURN
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading;   namespace Polyspiral { public partial class Form1 : Form { private double inc;   public Form1() { Width = Height = 640; StartPosition = FormStartPosition.CenterScreen; SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);   var timer = new DispatcherTimer(); timer.Tick += (s, e) => { inc = (inc + 0.05) % 360; Refresh(); }; timer.Interval = new TimeSpan(0, 0, 0, 0, 40); timer.Start(); }   private void DrawSpiral(Graphics g, int len, double angleIncrement) { double x1 = Width / 2; double y1 = Height / 2; double angle = angleIncrement;   for (int i = 0; i < 150; i++) { double x2 = x1 + Math.Cos(angle) * len; double y2 = y1 - Math.Sin(angle) * len; g.DrawLine(Pens.Blue, (int)x1, (int)y1, (int)x2, (int)y2); x1 = x2; y1 = y2;   len += 3;   angle = (angle + angleIncrement) % (Math.PI * 2); } }   protected override void OnPaint(PaintEventArgs args) { var g = args.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.Clear(Color.White);   DrawSpiral(g, 5, ToRadians(inc)); }   private double ToRadians(double angle) { return Math.PI * angle / 180.0; } } }
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#ABAP
ABAP
  report z_powerset.   interface set. methods: add_element importing element_to_be_added type any returning value(new_set) type ref to set,   remove_element importing element_to_be_removed type any returning value(new_set) type ref to set,   contains_element importing element_to_be_found type any returning value(contains) type abap_bool,   get_size returning value(size) type int4,   is_equal importing set_to_be_compared_with type ref to set returning value(equal) type abap_bool,   get_elements exporting elements type any table,   stringify returning value(stringified_set) type string. endinterface.     class string_set definition. public section. interfaces: set.     methods: constructor importing elements type stringtab optional,   build_powerset returning value(powerset) type ref to string_set.     private section. data elements type stringtab. endclass.     class string_set implementation. method constructor. loop at elements into data(element). me->set~add_element( element ). endloop. endmethod.     method set~add_element. if not line_exists( me->elements[ table_line = element_to_be_added ] ). append element_to_be_added to me->elements. endif.   new_set = me. endmethod.     method set~remove_element. if line_exists( me->elements[ table_line = element_to_be_removed ] ). delete me->elements where table_line = element_to_be_removed. endif.   new_set = me. endmethod.     method set~contains_element. contains = cond abap_bool( when line_exists( me->elements[ table_line = element_to_be_found ] ) then abap_true else abap_false ). endmethod.     method set~get_size. size = lines( me->elements ). endmethod.     method set~is_equal. if set_to_be_compared_with->get_size( ) ne me->set~get_size( ). equal = abap_false.   return. endif.   loop at me->elements into data(element). if not set_to_be_compared_with->contains_element( element ). equal = abap_false.   return. endif. endloop.   equal = abap_true. endmethod.     method set~get_elements. elements = me->elements. endmethod.     method set~stringify. stringified_set = cond string( when me->elements is initial then `∅` when me->elements eq value stringtab( ( `∅` ) ) then `{ ∅ }` else reduce string( init result = `{ ` for element in me->elements next result = cond string( when element eq `` then |{ result }∅, | when strlen( element ) eq 1 and element ne `∅` then |{ result }{ element }, | else |{ result }\{{ element }\}, | ) ) ).   stringified_set = replace( val = stringified_set regex = `, $` with = ` }`). endmethod.     method build_powerset. data(powerset_elements) = value stringtab( ( `` ) ).   loop at me->elements into data(element). do lines( powerset_elements ) times. if powerset_elements[ sy-index ] ne `∅`. append |{ powerset_elements[ sy-index ] }{ element }| to powerset_elements. else. append element to powerset_elements. endif. enddo. endloop.   powerset = new string_set( powerset_elements ). endmethod. endclass.     start-of-selection. data(set1) = new string_set( ). data(set2) = new string_set( ). data(set3) = new string_set( ).   write: |𝑷( { set1->set~stringify( ) } ) -> { set1->build_powerset( )->set~stringify( ) }|, /.   set2->set~add_element( `∅` ). write: |𝑷( { set2->set~stringify( ) } ) -> { set2->build_powerset( )->set~stringify( ) }|, /.   set3->set~add_element( `1` )->add_element( `2` )->add_element( `3` )->add_element( `3` )->add_element( `4` )->add_element( `4` )->add_element( `4` ). write: |𝑷( { set3->set~stringify( ) } ) -> { set3->build_powerset( )->set~stringify( ) }|, /.  
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#ACL2
ACL2
(defun is-prime-r (x i) (declare (xargs :measure (nfix (- x i)))) (if (zp (- (- x i) 1)) t (and (/= (mod x i) 0) (is-prime-r x (1+ i)))))   (defun is-prime (x) (or (= x 2) (is-prime-r x 2)))
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#AutoHotkey
AutoHotkey
; Submitted by MasterFocus --- http://tiny.cc/iTunis   Loop { InputBox, OutputVar, Price Fraction Example, Insert the value to be rounded.`n* [ 0 < value < 1 ]`n* Press ESC or Cancel to exit, , 200, 150 If ErrorLevel Break MsgBox % "Input: " OutputVar "`nResult: " PriceFraction( OutputVar ) }   ;-----------------------------------------   PriceFraction( p_Input ) {   If p_Input is not float ; returns 0 if input is not a float Return 0   If ( ( p_Input <= 0 ) OR ( p_Input >= 1 ) ) ; returns 0 is input is out of range Return 0   ; declaring the table (arbitrary delimiters in use are '§' and '|') l_List := "0.06|0.10§0.11|0.18§0.16|0.26§0.21|0.32§0.26|0.38§0.31|0.44§0.36|0.50§0.41|0.54§0.46|0.58§0.51|0.62§0.56|0.66§0.61|0.70§0.66|0.74§0.71|0.78§0.76|0.82§0.81|0.86§0.86|0.90§0.91|0.94§0.96|0.98§1.01|1.00"   Loop, Parse, l_List, § ; retrieves each field (delimited by '§') { StringSplit, l_Array, A_LoopField, | ; splits current field (using delimiter '|') If ( p_Input <= l_Array1 ) Return l_Array2 ; returns the second value if input <= first value }   Return 0 ; returns 0, indicating failure (shouldn't be reached though)   }
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
#Delphi
Delphi
  program ProperDivisors;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, System.Generics.Collections;   type TProperDivisors = TArray<Integer>;   function GetProperDivisors(const value: Integer): TProperDivisors; var i, count: Integer; begin count := 0;   for i := 1 to value div 2 do begin if value mod i = 0 then begin inc(count); SetLength(result, count); Result[count - 1] := i; end; end; end;   procedure Println(values: TProperDivisors); var i: Integer; begin Write('['); if Length(values) > 0 then for i := 0 to High(values) do Write(Format('%2d', [values[i]])); Writeln(']'); end;   var number, max_count, count, max_number: Integer;   begin for number := 1 to 10 do begin write(number, ': '); Println(GetProperDivisors(number)); end;   max_count := 0; for number := 1 to 20000 do begin count := length(GetProperDivisors(number)); if count > max_count then begin max_count := count; max_number := number; end; end;   Write(max_number, ': ', max_count);   readln; 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)
#Forth
Forth
include random.fs   \ common factors of desired probabilities (1/5 .. 1/11) 2 2 * 2 * 3 * 3 * 5 * 7 * 11 * constant denom \ 27720   \ represent each probability as the numerator with 27720 as the denominator : ,numerators ( max min -- ) do denom i / , loop ;   \ final item is 27720 - sum(probs) : ,remainder ( denom addr len -- ) cells bounds do i @ - 1 cells +loop , ;   create probs 12 5 ,numerators denom probs 7 ,remainder create bins 8 cells allot   : choose ( -- 0..7 ) denom random 8 0 do probs i cells + @ - dup 0< if drop i unloop exit then loop abort" can't get here" ;   : trials ( n -- ) 0 do 1 bins choose cells + +! loop ;   : str-table create ( c-str ... n -- ) 0 do , loop does> ( n -- str len ) swap cells + @ count ;   here ," heth" here ," zayin" here ," waw" here ," he" here ," daleth" here ," gimel" here ," beth" here ," aleph" 8 str-table names   : .header cr ." Name" #tab emit ." Prob" #tab emit ." Actual" #tab emit ." Error" ; : .result ( n -- ) cr dup names type #tab emit dup cells probs + @ s>f denom s>f f/ fdup f. #tab emit dup cells bins + @ s>f 1e6 f/ fdup f. #tab emit f- fabs fs. ;   : .results .header 8 0 do i .result loop ;
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
#Wren
Wren
import "/math" for Int import "/sort" for Sort import "/fmt" for Fmt   var maxSum = 99   var descendants = List.filled(maxSum + 1, null) var ancestors = List.filled(maxSum + 1, null) for (i in 0..maxSum) { descendants[i] = [] ancestors[i] = [] } var primes = Int.primeSieve(maxSum) for (p in primes) { descendants[p].add(p) for (s in 1...descendants.count - p) { descendants[s + p].addAll(descendants[s].map { |d| p * d }) } } for (p in primes + [4]) descendants[p].removeAt(-1) var total = 0 for (s in 1..maxSum) { Sort.quick(descendants[s]) total = total + descendants[s].count for (d in descendants[s]) { if (d > maxSum) break ancestors[d] = ancestors[s] + [s] } if (s < 21 || s == 46 || s == 74 || s == maxSum) { Fmt.write("$2d: $d Ancestors[s]: $-18n", s, ancestors[s].count, ancestors[s]) var count = descendants[s].count var desc10 = (count <= 10) ? descendants[s] : descendants[s].take(10).toList + ["..."] Fmt.print("$5d Descendants[s]: $n", count, desc10) } } System.print("\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.
#Elixir
Elixir
defmodule Priority do def create, do: :gb_trees.empty   def insert( element, priority, queue ), do: :gb_trees.enter( priority, element, queue )   def peek( queue ) do {_priority, element, _new_queue} = :gb_trees.take_smallest( queue ) element end   def task do items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}] queue = Enum.reduce(items, create, fn({priority, element}, acc) -> insert( element, priority, acc ) end) IO.puts "peek priority: #{peek( queue )}" Enum.reduce(1..length(items), queue, fn(_n, q) -> write_top( q ) end) end   def top( queue ) do {_priority, element, new_queue} = :gb_trees.take_smallest( queue ) {element, new_queue} end   defp write_top( q ) do {element, new_queue} = top( q ) IO.puts "top priority: #{element}" new_queue end end   Priority.task
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Apolonius[a1_,b1_,c1_,a2_,b2_,c2_,a3_,b3_,c3_,S1_,S2_ ,S3_ ]:= Module[{x1=a1,y1=b1,r1=c1,x2=a2,y2=b2,r2=c2,x3=a3,y3=b3,r3=c3,s1=S1,s2=S2,s3=S3}, v11 = 2*x2 - 2*x1; v12 = 2*y2 - 2*y1; v13 = x1^2 - x2^2 + y1^2 - y2^2 - r1^2 + r2^2; v14 = 2*s2*r2 - 2*s1*r1;   v21 = 2*x3-2*x2 ; v22 = 2*y3 - 2*y2; v23 = x2^2 - x3^2 + y2^2 - y3^2 - r2^2 + r3^2; 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^2 + q^2-1; b = 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1; c = x1^2+m^2 - 2*m*x1 + p^2+y1^2 - 2*p*y1 - r1^2;   d= b^2 - 4*a*c; rs = (-b -Sqrt[d])/(2*a); xs = m + n*rs; ys = p + q*rs; Map[N,{xs, ys, rs} ]]
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.
#MUMPS
MUMPS
APOLLONIUS(CIR1,CIR2,CIR3,S1,S2,S3)  ;Circles are passed in as strings with three parts with a "^" separator in the order x^y^r  ;The three circles are CIR1, CIR2, and CIR3  ;The S1, S2, and S3 parameters determine if the solution will be internally or externally  ;tangent to the circle. (+1 external, -1 internal)  ;CIRR is the circle returned in the same format as the input circles  ;  ;Xn, Yn, and Rn are the values for a circle n - following the precedents from the  ;other examples because doing $Pieces would make this confusing to read NEW X1,X2,X3,Y1,Y2,Y3,R1,R2,R3,RS,V11,V12,V13,V14,V21,V22,V23,V24,W12,W13,W14,W22,W23,W24,P,M,N,Q,A,B,C,D NEW CIRR SET X1=$PIECE(CIR1,"^",1),X2=$PIECE(CIR2,"^",1),X3=$PIECE(CIR3,"^",1) SET Y1=$PIECE(CIR1,"^",2),Y2=$PIECE(CIR2,"^",2),Y3=$PIECE(CIR3,"^",2) SET R1=$PIECE(CIR1,"^",3),R2=$PIECE(CIR2,"^",3),R3=$PIECE(CIR3,"^",3) SET V11=(2*X2)-(2*X1) SET V12=(2*Y2)-(2*Y1) SET V13=(X1*X1)-(X2*X2)+(Y1*Y1)-(Y2*Y2)-(R1*R1)+(R2*R2) SET V14=(2*S2*R2)-(2*S1*R1) SET V21=(2*X3)-(2*X2) SET V22=(2*Y3)-(2*Y2) SET V23=(X2*X2)-(X3*X3)+(Y2*Y2)-(Y3*Y3)-(R2*R2)+(R3*R3) SET V24=(2*S3*R3)-(2*S2*R2) SET W12=V12/V11 SET W13=V13/V11 SET W14=V14/V11 SET W22=(V22/V21)-W12 ;Parentheses for insurance - MUMPS evaluates left to right SET W23=(V23/V21)-W13 SET W24=(V24/V21)-W14 SET P=-W23/W22 SET Q=W24/W22 SET M=-(W12*P)-W13 SET N=W14-(W12*Q) SET A=(N*N)+(Q*Q)-1 SET B=(2*M*N)-(2*N*X1)+(2*P*Q)-(2*Q*Y1)+(2*S1*R1) SET C=(X1*X1)+(M*M)+(2*M*X1)+(P*P)+(Y1*Y1)-(2*P*Y1)-(R1*R1) SET D=(B*B)-(4*A*C) SET RS=(-B-(D**.5))/(2*A) SET $PIECE(CIRR,"^",1)=M+(N*RS) SET $PIECE(CIRR,"^",2)=P+(Q*RS) SET $PIECE(CIRR,"^",3)=RS KILL X1,X2,X3,Y1,Y2,Y3,R1,R2,R3,RS,V11,V12,V13,V14,V21,V22,V23,V24,W12,W13,W14,W22,W23,W24,P,M,N,Q,A,B,C,D QUIT CIRR
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.
#PowerShell
PowerShell
  # write this in file <program.ps1> $MyInvocation.MyCommand.Name # launch with <.\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.
#Prolog
Prolog
% SWI-Prolog version 8.0.0 for i686-linux. % This will find itself, and return the knowledge base it is in. file_name(F) :- true , M = user % M is the module . , P = file_name(_) % P is the predicate . , source_file(M:P, F) % F is the file . , \+ predicate_property(M:P, imported_from(_)) .
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
#Picat
Picat
main :- garbage_collect(300_000_000), Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000], member(Max, Data), count_triples(Max, Total, Prim), printf("upto %d, there are %d Pythagorean triples (%d primitive.)%n", Max, Total, Prim), fail, nl.   count_triples(Max, Total, Prims) :- Ps = findall(S, (triple(Max, A, B, C), S is A + B + C)), Prims = Ps.len, Total = sum([Max div P : P in Ps]).   % - between_by/4 between_by(A, B, N, K) :- C = (B - A) div N, between(0, C, J), K = N*J + A.   % - Pythagorean triple generator triple(P, A, B, C) :- Max = floor(sqrt(P/2)) - 1, between(0, Max, M), Start = (M /\ 1) + 1, Pm = M - 1, between_by(Start, Pm, 2, N), gcd(M, N) == 1, X = M*M - N*N, Y = 2*M*N, C = M*M + N*N, order2(X, Y, A, B), (A + B + C) =< P.   order2(A, B, A, B) :- A < B, !. order2(A, B, B, A).
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.
#Oforth
Oforth
import: os   some_condition ifTrue: [ 0 OS.exit ]
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Ol
Ol
  (shutdown 0) ; it can be any exit code instead of provided 0  
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
#Forth
Forth
  : fac-mod ( n m -- r ) >r 1 swap begin dup 0> while dup rot * r@ mod swap 1- repeat drop rdrop ;   : ?prime ( n -- f ) dup 1- tuck swap fac-mod = ;   : .primes ( n -- ) cr 2 ?do i ?prime if i . then loop ;  
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
#FreeBASIC
FreeBASIC
function wilson_prime( n as uinteger ) as boolean dim as uinteger fct=1, i for i = 2 to n-1 'because (a mod n)*b = (ab mod n) 'it is not necessary to calculate the entire factorial fct = (fct * i) mod n next i if fct = n-1 then return true else return false end function   for i as uinteger = 2 to 100 if wilson_prime(i) then print i, next i
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 %
#Lua
Lua
-- Return boolean indicating whether or not n is prime function isPrime (n) if n <= 1 then return false end if n <= 3 then return true end if n % 2 == 0 or n % 3 == 0 then return false end local i = 5 while i * i <= n do if n % i == 0 or n % (i + 2) == 0 then return false end i = i + 6 end return true end   -- Return table of frequencies for final digits of consecutive primes function primeCon (limit) local count, x, last, ending = 2, 3, 3 local freqList = { [1] = {}, [2] = {[3] = 1}, [3] = {}, [5] = {}, [7] = {}, [9] = {} } repeat x = x + 2 if isPrime(x) then ending = x % 10 if freqList[last][ending] then freqList[last][ending] = freqList[last][ending] + 1 else freqList[last][ending] = 1 end last = ending count = count + 1 end until count == limit return freqList end   -- Main procedure local limit = 10^6 local t = primeCon(limit) for a = 1, 9 do for b = 1, 9 do if t[a] and t[a][b] then io.write(a .. " -> " .. b .. "\tcount: " .. t[a][b]) print("\tfrequency: " .. t[a][b] / limit * 100 .. " %") end end end
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
#Arturo
Arturo
decompose: function [num][ facts: to [:string] factors.prime num print [ pad.right (to :string num) ++ " = " ++ join.with:" x " facts 30 "{"++ (join.with:", " unique facts) ++ "}" ] ]   loop 2..40 => decompose
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#C.2B.2B
C++
  #include <windows.h> #include <sstream> #include <ctime>   const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = sinf( r ), c = cosf( r ), a = _x * c - _y * s, b = _x * s + _y * c; x = a; y = b; } vector2 add( const vector2& v ) { x += v.x; y += v.y; return *this; } float x, y; }; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap(){ DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ){ BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc );   width = w; height = h; return true; } void clear( BYTE clr = 0 ){ memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ){ if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ){ clr = c; createPen(); } void setPenWidth( int w ){ wid = w; createPen(); } void saveBitmap( std::string path ){ BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen(){ if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); myBitmap bmp; bmp.create( 600, 600 ); bmp.clear(); HDC dc = bmp.getDC(); float fs = ( TWO_PI ) / 100.f; int index = 0; std::string a = "f://users//images//test", b; float ang, len; vector2 p1, p2;   for( float step = 0.1f; step < 5.1f; step += .05f ) { ang = 0; len = 2; p1.set( 300, 300 ); bmp.setPenColor( RGB( rand() % 50 + 200, rand() % 300 + 220, rand() % 50 + 200 ) ); for( float xx = 0; xx < TWO_PI; xx += fs ) { MoveToEx( dc, (int)p1.x, (int)p1.y, NULL ); p2.set( 0, len ); p2.rotate( ang ); p2.add( p1 ); LineTo( dc, (int)p2.x, (int)p2.y ); p1 = p2; ang += step; len += step; } std::ostringstream ss; ss << index++; b = a + ss.str() + ".bmp"; bmp.saveBitmap( b ); bmp.clear(); } return 0; }  
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#11l
11l
F average(arr) R sum(arr) / Float(arr.len)   F poly_regression(x, y) V xm = average(x) V ym = average(y) V x2m = average(x.map(i -> i * i)) V x3m = average(x.map(i -> i ^ 3)) V x4m = average(x.map(i -> i ^ 4)) V xym = average(zip(x, y).map((i, j) -> i * j)) V x2ym = average(zip(x, y).map((i, j) -> i * i * j)) V sxx = x2m - xm * xm V sxy = xym - xm * ym V sxx2 = x3m - xm * x2m V sx2x2 = x4m - x2m * x2m V sx2y = x2ym - x2m * ym V b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) V c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) V a = ym - b * xm - c * x2m   F abc(xx) R (@a + @b * xx) + (@c * xx * xx)   print("y = #. + #.x + #.x^2\n".format(a, b, c)) print(‘ Input Approximation’) print(‘ x y y1’)   L(i) 0 .< x.len print(‘#2 #3 #3.1’.format(x[i], y[i], abc(i)))   V x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] V y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] poly_regression(x, y)
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#Ada
Ada
  with Ada.Text_IO, Ada.Command_Line; use Ada.Text_IO, Ada.Command_Line;   procedure powerset is begin for set in 0..2**Argument_Count-1 loop Put ("{"); declare k : natural := set; first : boolean := true; begin for i in 1..Argument_Count loop if k mod 2 = 1 then Put ((if first then "" else ",") & Argument (i)); first := false; end if; k := k / 2; -- we go to the next bit of "set" end loop; end; Put_Line("}"); end loop; end powerset;  
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Action.21
Action!
BYTE FUNC IsPrime(CARD a) CARD i   IF a<=1 THEN RETURN (0) FI   FOR i=2 TO a/2 DO IF a MOD i=0 THEN RETURN (0) FI OD RETURN (1)   PROC Test(CARD a) IF IsPrime(a) THEN PrintF("%I is prime%E",a) ELSE PrintF("%I is not prime%E",a) FI RETURN   PROC Main() Test(13) Test(997) Test(1) Test(6) Test(120) Test(0) RETURN
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#AWK
AWK
  BEGIN { O = ".06 .11 .16 .21 .26 .31 .36 .41 .46 .51 .56 .61 .66 .71 .76 .81 .86 .91 .96 1.01" N = ".10 .18 .26 .32 .38 .44 .50 .54 .58 .62 .66 .70 .74 .78 .82 .86 .90 .94 .98 1.00" fields = split(O,Oarr," ") # original values split(N,Narr," ") # replacement values for (i=-.01; i<=1.02; i+=.01) { # test printf("%5.2f = %4.2f\n",i,lookup(i)) } } function lookup(n, i) { if (n < 0 || n > 1.01) { return(0) # when input is out of range } for (i=1; i<=fields; i++) { # +10 is used because .11 returned .18 instead of .26 # under AWK95, GAWK, and MAWK; Thompson Automation's TAWK worked correctly if (n+10 < Oarr[i]+10) { return(Narr[i]) } } }  
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
#Dyalect
Dyalect
func properDivs(n) { if n == 1 { yield break } for x in 1..<n { if n % x == 0 { yield x } } }   for i in 1..10 { print("\(i): \(properDivs(i).ToArray())") }   var (num, max) = (0,0)   for i in 1..20000 { let count = properDivs(i).Length() if count > max { set (num, max) = (i, count) } }   print("\(num): \(max)")
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)
#Fortran
Fortran
PROGRAM PROBS   IMPLICIT NONE   INTEGER, PARAMETER :: trials = 1000000 INTEGER :: i, j, probcount(8) = 0 REAL :: expected(8), mapping(8), rnum CHARACTER(6) :: items(8) = (/ "aleph ", "beth ", "gimel ", "daleth", "he ", "waw ", "zayin ", "heth " /)   expected(1:7) = (/ (1.0/i, i=5,11) /) expected(8) = 1.0 - SUM(expected(1:7)) mapping(1) = 1.0 / 5.0 DO i = 2, 7 mapping(i) = mapping(i-1) + 1.0/(i+4.0) END DO mapping(8) = 1.0   DO i = 1, trials CALL RANDOM_NUMBER(rnum) DO j = 1, 8 IF (rnum < mapping(j)) THEN probcount(j) = probcount(j) + 1 EXIT END IF END DO END DO   WRITE(*, "(A,I10)") "Trials: ", trials WRITE(*, "(A,8A10)") "Items: ", items WRITE(*, "(A,8F10.6)") "Target Probability: ", expected WRITE(*, "(A,8F10.6)") "Attained Probability:", REAL(probcount) / REAL(trials)   ENDPROGRAM PROBS
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
#zkl
zkl
const maxsum=99;   primes:=Utils.Generator(Import("sieve.zkl").postponed_sieve) .pump(List,'wrap(p){ (p<=maxsum) and p or Void.Stop });   descendants,ancestors:=List()*(maxsum + 1), List()*(maxsum + 1);   foreach p in (primes){ descendants[p].insert(0,p); foreach s in ([1..descendants.len() - p - 1]){ descendants[s + p].merge(descendants[s].apply('*(p))); } }   // descendants[prime] is a list that starts with prime, remove prime. 4: ??? foreach p in (primes + 4) { descendants[p].pop(0) }   ta,td:=0,0; foreach s in ([1..maxsum]){ foreach d in (descendants[s].filter('<=(maxsum))){ ancestors[d]=ancestors[s].copy() + s; }   println("%2d Ancestors: ".fmt(s),ancestors[s].len() and ancestors[s] or "None"); println(" Descendants: ", if(z:=descendants[s]) String(z.len()," : ",z) else "None"); ta+=ancestors[s].len(); td+=descendants[s].len(); } println("Total ancestors: %,d".fmt(ta)); println("Total descendants: %,d".fmt(td));
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.
#Erlang
Erlang
  -module( priority_queue ).   -export( [create/0, insert/3, peek/1, task/0, top/1] ).   create() -> gb_trees:empty().   insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).   peek( Queue ) -> {_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ), Element.   task() -> Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}], Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ), io:fwrite( "peek priority: ~p~n", [peek( Queue )] ), lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).   top( Queue ) -> {_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ), {Element, New_queue}.       write_top( Q ) -> {Element, New_queue} = top( Q ), io:fwrite( "top priority: ~p~n", [Element] ), New_queue.  
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.
#Nim
Nim
import math   type Circle = tuple[x, y, r: float]   proc solveApollonius(c1, c2, c3: Circle; s1, s2, s3: float): Circle = let v11 = 2*c2.x - 2*c1.x v12 = 2*c2.y - 2*c1.y v13 = c1.x*c1.x - c2.x*c2.x + c1.y*c1.y - c2.y*c2.y - c1.r*c1.r + c2.r*c2.r v14 = 2*s2*c2.r - 2*s1*c1.r   v21 = 2*c3.x - 2*c2.x v22 = 2*c3.y - 2*c2.y v23 = c2.x*c2.x - c3.x*c3.x + c2.y*c2.y - c3.y*c3.y - c2.r*c2.r + c3.r*c3.r v24 = 2*s3*c3.r - 2*s2*c2.r   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*c1.x + 2*p*q - 2*q*c1.y + 2*s1*c1.r c = c1.x*c1.x + m*m - 2*m*c1.x + p*p + c1.y*c1.y - 2*p*c1.y - c1.r*c1.r   d = b*b-4*a*c rs = (-b-sqrt(d))/(2*a)   xs = m+n*rs ys = p+q*rs   return (xs, ys, rs)   let c1: Circle = (0.0, 0.0, 1.0) c2: Circle = (4.0, 0.0, 1.0) c3: Circle = (2.0, 4.0, 2.0)   echo solveApollonius(c1, c2, c3, 1.0, 1.0, 1.0) echo solveApollonius(c1, c2, c3, -1.0, -1.0, -1.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.
#PureBasic
PureBasic
If OpenConsole() PrintN(ProgramFilename())   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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.
#Python
Python
#!/usr/bin/env python   import sys   def main(): program = sys.argv[0] print("Program: %s" % program)   if __name__ == "__main__": main()
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
#PicoLisp
PicoLisp
(for (Max 10 (>= 100000000 Max) (* Max 10)) (let (Total 0 Prim 0 In (3 4 5)) (recur (In) (let P (apply + In) (when (>= Max P) (inc 'Prim) (inc 'Total (/ Max P)) (for Row (quote (( 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)) ) (recurse (mapcar '((U) (sum * U In)) Row) ) ) ) ) ) (prinl "Up to " Max ": " Total " triples, " Prim " primitives.") ) )
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.
#Oz
Oz
if Problem then {Application.exit 0} end
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#PARI.2FGP
PARI/GP
if(stuff, quit)
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
#F.C5.8Drmul.C3.A6
Fōrmulæ
# find primes using Wilson's theorem: # p is prime if ( ( p - 1 )! + 1 ) mod p = 0   isWilsonPrime := function( p ) local fModP, i; fModP := 1; for i in [ 2 .. p - 1 ] do fModP := fModP * i; fModP := fModP mod p; od; return fModP = p - 1; end; # isWilsonPrime   prime := []; for i in [ -4 .. 100 ] do if isWilsonPrime( i ) then Add( prime, i ); fi; od; Display( prime );
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
#GAP
GAP
# find primes using Wilson's theorem: # p is prime if ( ( p - 1 )! + 1 ) mod p = 0   isWilsonPrime := function( p ) local fModP, i; fModP := 1; for i in [ 2 .. p - 1 ] do fModP := fModP * i; fModP := fModP mod p; od; return fModP = p - 1; end; # isWilsonPrime   prime := []; for i in [ -4 .. 100 ] do if isWilsonPrime( i ) then Add( prime, i ); fi; od; Display( prime );
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 %
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
  StringForm["`` count: `` frequency: ``", Rule@@ #[[1]], StringPadLeft[ToString@ #[[2]], 8], PercentForm[N@ #[[2]]/(10^8 -1)]]& /@ Sort[Tally[Partition[Mod[Prime[Range[10^8]], 10], 2, 1]]] // Column  
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 %
#Nim
Nim
  # Prime conspiracy.   from algorithm import sorted from math import sqrt from sequtils import toSeq from strformat import fmt import tables   const N = 1_020_000_000.int # Size of sieve of Eratosthenes.   proc newSieve(): seq[bool] = ## Create a sieve with only odd values. ## Index "i" in sieve represents value "n = 2 * i + 3". result.setLen(N) for item in result.mitems: item = true # Apply sieve. var i = 0 const Limit = sqrt(2 * N.toFloat + 3).int while true: let n = 2 * i + 3 if n > Limit: break if result[i]: # Found prime, so eliminate multiples. for k in countup((n * n - 3) div 2, N - 1, n): result[k] = false inc i   var isPrime = newSieve()   proc countTransitions(isPrime: seq[bool]; nprimes: int) = ## Build the transition count table and print it.   var counts = [(2, 3)].toCountTable() # Count of transitions. var d1 = 3 # Last digit of first prime in transition. var count = 2 # Count of primes (starting with 2 and 3). for i in 1..isPrime.high: if isPrime[i]: inc count let d2 = (2 * i + 3) mod 10 # Last digit of second prime in transition. counts.inc((d1, d2)) if count == nprimes: break d1 = d2   # Check if sieve was big enough. if count < nprimes: echo fmt"Found only {count} primes; expected {nprimes} primes. Increase value of N." quit(QuitFailure)   # Print result. echo fmt"{nprimes} first primes. Transitions prime % 10 → next-prime % 10." for key in sorted(toSeq(counts.keys)): let count = counts[key] let freq = count.toFloat * 100 / nprimes.toFloat echo fmt"{key[0]} -> {key[1]}: count: {count:7d} frequency: {freq:4.2f}%" echo ""   isPrime.countTransitions(10_000) isPrime.countTransitions(1_000_000) isPrime.countTransitions(100_000_000)  
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
#AutoHotkey
AutoHotkey
MsgBox % factor(8388607) ; 47 * 178481   factor(n) { if (n = 1) return f = 2 while (f <= n) { if (Mod(n, f) = 0) { next := factor(n / f) return, % f "`n" next } f++ } }
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#Ceylon
Ceylon
import javafx.application { Application } import javafx.stage { Stage } import javafx.animation { AnimationTimer } import ceylon.numeric.float { remainder, cos, sin, toRadians } import javafx.scene.layout { BorderPane } import javafx.scene.canvas { Canvas } import javafx.scene { Scene } import javafx.scene.paint { Color }   shared void run() { Application.launch(`PolySpiralApp`); }   shared class PolySpiralApp() extends Application() {   value width = 600.0; value height = 600.0;   variable value incr = 0.0;   shared actual void start(Stage primaryStage) {   value canvas = Canvas(width, height); value graphics = canvas.graphicsContext2D;   object extends AnimationTimer() {   shared actual void handle(Integer now) {   incr = remainder(incr + 0.05, 360.0);   variable value x = width / 2.0; variable value y = width / 2.0; variable value length = 5.0; variable value angle = incr;   graphics.fillRect(0.0, 0.0, width, height); graphics.beginPath(); graphics.moveTo(x, y);   for (i in 1..150) { value radians = toRadians(angle); x = x + cos(radians) * length; y = y + sin(radians) * length; graphics.stroke = Color.hsb(angle, 1.0, 1.0); graphics.lineTo(x, y); length += 3; angle = remainder(angle + incr, 360.0); }   graphics.stroke(); } }.start();   value root = BorderPane(); root.center = canvas; value scene = Scene(root); primaryStage.title = "poly-spiral"; primaryStage.setScene(scene); primaryStage.show(); } }
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#FreeBASIC
FreeBASIC
#include "fbgfx.bi" #if __FB_LANG__ = "fb" Using FB '' Scan code constants are stored in the FB namespace in lang FB #endif #define pi 4 * Atn(1) #define Deg2Rad pi/180   Dim As Integer w = 900, h = w Screenres w, h, 8 Windowtitle "Polyspiral"   Dim As Integer incr = 0, angulo, longitud, x1, y1, x2, y2, N Do incr += 1 x1 = w / 2 y1 = h / 2 Pset (Fix(x1), Fix(y1)) longitud = 5 angulo = incr For N = 1 To 150 x2 = x1 + longitud * Cos(angulo * Deg2Rad) y2 = y1 + longitud * Sin(angulo * Deg2Rad) Line - (Fix(x2), Fix(y2)), N+16 x1 = x2 y1 = y2 longitud += 3 angulo += incr Next N Sleep 500 Cls Loop Until Multikey(SC_ESCAPE)
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Ada
Ada
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;   function Fit (X, Y : Real_Vector; N : Positive) return Real_Vector is A : Real_Matrix (0..N, X'Range); -- The plane begin for I in A'Range (2) loop for J in A'Range (1) loop A (J, I) := X (I)**J; end loop; end loop; return Solve (A * Transpose (A), A * Y); end Fit;
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#ALGOL_68
ALGOL 68
MODE MEMBER = INT;   PROC power set = ([]MEMBER s)[][]MEMBER:( [2**UPB s]FLEX[1:0]MEMBER r; INT upb r := 0; r[upb r +:= 1] := []MEMBER(()); FOR i TO UPB s DO MEMBER e = s[i]; FOR j TO upb r DO [UPB r[j] + 1]MEMBER x; x[:UPB x-1] := r[j]; x[UPB x] := e; # append to the end of x # r[upb r +:= 1] := x # append to end of r # OD OD; r[upb r] := s; r ); # Example: # test:( [][]MEMBER set = power set((1, 2, 4)); FOR member TO UPB set DO INT upb = UPB set[member]; FORMAT repr set = $"("f( upb=0 | $$ | $n(upb-1)(d", ")d$ )");"$; printf(($"set["d"] = "$,member, repr set, set[member],$l$)) OD )
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#ActionScript
ActionScript
function isPrime(n:int):Boolean { if(n < 2) return false; if(n == 2) return true; if((n & 1) == 0) return false; for(var i:int = 3; i <= Math.sqrt(n); i+= 2) if(n % i == 0) return false; return true; }
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#BASIC
BASIC
DECLARE FUNCTION PriceFraction! (price AS SINGLE)   RANDOMIZE TIMER DIM x AS SINGLE x = RND PRINT x, PriceFraction(x)   FUNCTION PriceFraction! (price AS SINGLE) 'returns price unchanged if invalid value SELECT CASE price CASE IS < 0! PriceFraction! = price CASE IS < .06 PriceFraction! = .1 CASE IS < .11 PriceFraction! = .18 CASE IS < .16 PriceFraction! = .26 CASE IS < .21 PriceFraction! = .32 CASE IS < .26 PriceFraction! = .38 CASE IS < .31 PriceFraction! = .44 CASE IS < .36 PriceFraction! = .5 CASE IS < .41 PriceFraction! = .54 CASE IS < .46 PriceFraction! = .58 CASE IS < .51 PriceFraction! = .62 CASE IS < .56 PriceFraction! = .66 CASE IS < .61 PriceFraction! = .7 CASE IS < .66 PriceFraction! = .74 CASE IS < .71 PriceFraction! = .78 CASE IS < .76 PriceFraction! = .82 CASE IS < .81 PriceFraction! = .86 CASE IS < .86 PriceFraction! = .9 CASE IS < .91 PriceFraction! = .94 CASE IS < .96 PriceFraction! = .98 CASE IS < 1.01 PriceFraction! = 1! CASE ELSE PriceFraction! = price END SELECT END FUNCTION
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
#EchoLisp
EchoLisp
  (lib 'list) ;; list-delete   ;; let n = product p_i^a_i , p_i prime ;; number of divisors = product (a_i + 1) - 1 (define (numdivs n) (1- (apply * (map (lambda(g) (1+ (length g))) (group (prime-factors n))))))   (remember 'numdivs)   ;; prime powers ;; input : a list g of grouped prime factors ( 3 3 3 ..) ;; returns (1 3 9 27 ...) (define (ppows g (mult 1)) (for/fold (ppows '(1)) ((a g)) (set! mult (* mult a)) (cons mult ppows)))   ;; proper divisors ;; decomp n into ((2 2 ..) ( 3 3 ..) ) prime factors groups ;; combines (1 2 4 8 ..) (1 3 9 ..) lists ;; remove n from the list   (define (divs n) (if (<= n 1) null (list-delete (for/fold (divs'(1)) ((g (map ppows (group (prime-factors n))))) (for*/list ((a divs) (b g)) (* a b))) n )))   ;; find number(s) with max # of proper divisors ;; returns list of (n . maxdivs) for n in range 2..N   (define (most-proper N) (define maxdivs 1) (define ndivs 0) (for/fold (most-proper null) ((n (in-range 2 N))) (set! ndivs (numdivs n)) #:continue (< ndivs maxdivs) (when (> ndivs maxdivs) (set!-values (most-proper maxdivs) (values null ndivs))) (cons (cons n maxdivs) most-proper)))      
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)
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim letters (0 To 7) As String = {"aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"} Dim actual (0 To 7) As Integer '' all zero by default Dim probs (0 To 7) As Double = {1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0} Dim cumProbs (0 To 7) As Double   cumProbs(0) = probs(0) For i As Integer = 1 To 6 cumProbs(i) = cumProbs(i - 1) + probs(i) Next cumProbs(7) = 1.0 probs(7) = 1.0 - cumProbs(6)   Randomize Dim rand As Double Dim n As Double = 1000000 Dim sum As Double = 0.0   For i As Integer = 1 To n rand = Rnd '' random number where 0 <= rand < 1 Select case rand Case Is <= cumProbs(0) actual(0) += 1 Case Is <= cumProbs(1) actual(1) += 1 Case Is <= cumProbs(2) actual(2) += 1 Case Is <= cumProbs(3) actual(3) += 1 Case Is <= cumProbs(4) actual(4) += 1 Case Is <= cumProbs(5) actual(5) += 1 Case Is <= cumProbs(6) actual(6) += 1 Case Else actual(7) += 1 End Select Next   Dim sumActual As Double = 0   Print "Letter", " Actual", "Expected" Print "------", "--------", "--------" For i As Integer = 0 To 7 Print letters(i), Print Using "#.######"; actual(i)/n; sumActual += actual(i)/n Print , Using "#.######"; probs(i) Next   Print , "--------", "--------" Print , Using "#.######"; sumActual; Print , Using "#.######"; 1.000000   Print Print "Press any key to quit" Sleep
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.
#F.23
F#
[<RequireQualifiedAccess>] module PriorityQ =   // type 'a treeElement = Element of uint32 * 'a type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end   type 'a tree = Node of uint32 * 'a treeElement * 'a tree list   type 'a heap = 'a tree list   [<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>] [<NoEquality; NoComparison>] type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap   let empty = HeapEmpty   let isEmpty = function | HeapEmpty -> true | _ -> false   let inline private rank (Node(r,_,_)) = r   let inline private root (Node(_,x,_)) = x   exception Empty_Heap   let peekMin = function | HeapEmpty -> None | HeapNotEmpty(min, _) -> Some (min.k, min.v)   let rec private findMin heap = match heap with | [] -> raise Empty_Heap //guarded so should never happen | [node] -> root node,[] | topnode::heap' -> let min,subheap = findMin heap' in let rtn = root topnode match subheap with | [] -> if rtn.k > min.k then min,[] else rtn,[] | minnode::heap'' -> let rmn = root minnode if rtn.k <= rmn.k then rtn,heap else rmn,minnode::topnode::heap''   let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) = if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2) else Node(r+1u,kv1,tree2::ts1)   let rec private insTree (newnode: 'a tree) heap = match heap with | [] -> [newnode] | topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap else insTree (mergeTree newnode topnode) heap'   let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[]) function | HeapEmpty -> HeapNotEmpty(kv,[nn]) | HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv HeapNotEmpty(nmin,insTree nn heap)   let rec private merge' heap1 heap2 = //doesn't guaranty minimum tree node as head!!! match heap1,heap2 with | _,[] -> heap1 | [],_ -> heap2 | topheap1::heap1',topheap2::heap2' -> match compare (rank topheap1) (rank topheap2) with | -1 -> topheap1::merge' heap1' heap2 | 1 -> topheap2::merge' heap1 heap2' | _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')   let merge oheap1 oheap2 = match oheap1,oheap2 with | _,HeapEmpty -> oheap1 | HeapEmpty,_ -> oheap2 | HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) -> let min = if min1.k > min2.k then min2 else min1 HeapNotEmpty(min,merge' heap1 heap2)   let rec private removeMinTree = function | [] -> raise Empty_Heap // will never happen as already guarded | [node] -> node,[] | t::ts -> let t',ts' = removeMinTree ts if (root t).k <= (root t').k then t,ts else t',t::ts'   let deleteMin = function | HeapEmpty -> HeapEmpty | HeapNotEmpty(_,heap) -> match heap with | [] -> HeapEmpty // should never occur: non empty heap with no elements | [Node(_,_,heap')] -> match heap' with | [] -> HeapEmpty | _ -> let min,_ = findMin heap' HeapNotEmpty(min,heap') | _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap HeapNotEmpty(min,nheap)   let replaceMin k v pq = push k v (deleteMin pq)   let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq   let popMin pq = match peekMin pq with | None -> None | Some(kv) -> Some(kv, deleteMin pq)   let toSeq pq = Seq.unfold popMin pq   let sort sq = sq |> fromSeq |> toSeq   let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
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.
#OCaml
OCaml
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 = Printf.printf "Circle(x=%.2f, y=%.2f, r=%.2f)\n" c.center.x c.center.y c.radius   let defxyr c = (c.center.x, c.center.y, c.radius)   let solve_apollonius ~c1 ~c2 ~c3 ~s1 ~s2 ~s3 = let ( * ) = ( *. ) in let ( / ) = ( /. ) in let ( + ) = ( +. ) in let ( - ) = ( -. ) in   let x1, y1, r1 = defxyr c1 and x2, y2, r2 = defxyr c2 and x3, y3, r3 = defxyr c3 in   let v11 = 2.0 * x2 - 2.0 * x1 and v12 = 2.0 * y2 - 2.0 * y1 and v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 and v14 = (2.0 * s2 * r2) - (2.0 * s1 * r1)   and v21 = 2.0 * x3 - 2.0 * x2 and v22 = 2.0 * y3 - 2.0 * y2 and v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 and v24 = (2.0 * s3 * r3) - (2.0 * s2 * r2) in   let w12 = v12 / v11 and w13 = v13 / v11 and w14 = v14 / v11 in   let w22 = v22 / v21 - w12 and w23 = v23 / v21 - w13 and w24 = v24 / v21 - w14 in   let p = -. w23 / w22 and q = w24 / w22 in let m = -. w12 * p - w13 and n = w14 - w12 * q in   let a = n*n + q*q - 1.0 and b = 2.0*m*n - 2.0*n*x1 + 2.0*p*q - 2.0*q*y1 + 2.0*s1*r1 and c = x1*x1 + m*m - 2.0*m*x1 + p*p + y1*y1 - 2.0*p*y1 - r1*r1 in   let d = b * b - 4.0 * a * c in let rs = (-. b - (sqrt d)) / (2.0 * a) in   let xs = m + n * rs and ys = p + q * rs in   (new_circle xs ys rs)   let () = let c1 = new_circle 0.0 0.0 1.0 and c2 = new_circle 4.0 0.0 1.0 and c3 = new_circle 2.0 4.0 2.0 in   let r1 = solve_apollonius c1 c2 c3 1.0 1.0 1.0 in print_circle r1;   let r2 = solve_apollonius c1 c2 c3 (-1.) (-1.) (-1.) in print_circle r2; ;;
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.
#R
R
#!/usr/bin/env Rscript   getProgram <- function(args) { sub("--file=", "", args[grep("--file=", args)]) }   args <- commandArgs(trailingOnly = FALSE) program <- getProgram(args)   cat("Program: ", program, "\n")   q("no")
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
#PL.2FI
PL/I
*process source attributes xref or(!); /********************************************************************* * REXX pgm counts number of Pythagorean triples * that exist given a max perimeter of N, * and also counts how many of them are primatives. * 05.05.2013 Walter Pachl translated from REXX version 2 *********************************************************************/ pyt: Proc Options(main); Dcl sysprint Print; Dcl (addr,mod,right) Builtin; Dcl memn Bin Fixed(31) Init(0); Dcl mabca(300) Char(12); Dcl 1 mabc, 2 ma Dec fixed(7), 2 mb Dec fixed(7), 2 mc Dec fixed(7); Dcl mabce Char(12) Based(addr(mabc)); Dcl 1 abc, 2 a Dec fixed(7), 2 b Dec fixed(7), 2 c Dec fixed(7); Dcl abce Char(12) Based(addr(abc)); Dcl (prims,trips,m,n,aa,aabb,cc,aeven,ab) Dec Fixed(7); mabca=''; trips=0; prims=0; n=100; la: Do a=3 To n/3; aa=a*a; /* limit side to 1/3 of perimeter.*/ aeven=mod(a,2)=0; lb:Do b=a+1 By 1+aeven; /* triangle can't be isosceles. */ ab=a+b; /* compute partial perimeter. */ If ab>=n Then Iterate la; /* a+b>perimeter? Try different A*/ aabb=aa+b*b; /* compute sum of a² + b² (cheat)*/ Do c=b+1 By 1; cc=c*c; /* 3rd side: also compute c² */ If aeven Then If mod(c,2)=0 Then Iterate; If ab+c>n Then Iterate la; /* a+b+c > perimeter? Try diff A.*/ If cc>aabb Then Iterate lb; /* c² > a²+b² ? Try different B.*/ If cc^=aabb Then Iterate; /* c² ¬= a²+b² ? Try different C.*/ If mema(abce) Then Iterate; trips=trips+1; /* eureka. */ prims=prims+1; /* count this primitive triple. */ Put Edit(a,b,c,' ',right(a**2+b**2,5),right(c**2,5),a+b+c) (Skip,f(4),2(f(5)),a,2(f(6)),f(9)); Do m=2 By 1; ma=a*m; mb=b*m; mc=c*m; /* gen non-primitives. */ If ma+mb+mc>n Then Leave; /* is this multiple a triple ? */ trips=trips+1; /* yuppers, then we found another.*/ If mod(m,2)=1 Then /* store as even multiple. */ call mems(mabce); Put Edit(ma,mb,mc,' * ', right(ma**2+mb**2,5),right(mc**2,5),ma+mb+mc) (Skip,f(4),2(f(5)),a,2(f(6)),f(9)); End; /* m */ End; /* c */ End; /* b */ End; /* a */ Put Edit('max perimeter = ',n, /* show a single line of output. */ 'Pythagorean triples =',trips, 'primitives =',prims) (Skip,a,f(5),2(x(9),a,f(4)));   mems: Proc(e); Dcl e Char(12); memn+=1; mabca(memn)=e; End;   mema: Proc(e) Returns(bit(1)); Dcl e Char(12); Do memi=1 To memn; If mabca(memi)=e Then Return('1'b); End; Return('0'b); End;   End;
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Pascal
Pascal
if true then begin halt end
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Perl
Perl
if ($problem) { exit integerErrorCode; # conventionally, error code 0 is the code for "OK" # (you can also omit the argument in this case) # while anything else is an actual problem }
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
#Go
Go
package main   import ( "fmt" "math/big" )   var ( zero = big.NewInt(0) one = big.NewInt(1) prev = big.NewInt(factorial(20)) )   // Only usable for n <= 20. func factorial(n int64) int64 { res := int64(1) for k := n; k > 1; k-- { res *= k } return res }   // If memo == true, stores previous sequential // factorial calculation for odd n > 21. func wilson(n int64, memo bool) bool { if n <= 1 || (n%2 == 0 && n != 2) { return false } if n <= 21 { return (factorial(n-1)+1)%n == 0 } b := big.NewInt(n) r := big.NewInt(0) z := big.NewInt(0) if !memo { z.MulRange(2, n-1) // computes factorial from scratch } else { prev.Mul(prev, r.MulRange(n-2, n-1)) // uses previous calculation z.Set(prev) } z.Add(z, one) return r.Rem(z, b).Cmp(zero) == 0 }   func main() { numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659} fmt.Println(" n prime") fmt.Println("--- -----") for _, n := range numbers { fmt.Printf("%3d  %t\n", n, wilson(n, false)) }   // sequential memoized calculation fmt.Println("\nThe first 120 prime numbers are:") for i, count := int64(2), 0; count < 1015; i += 2 { if wilson(i, true) { count++ if count <= 120 { fmt.Printf("%3d ", i) if count%20 == 0 { fmt.Println() } } else if count >= 1000 { if count == 1000 { fmt.Println("\nThe 1,000th to 1,015th prime numbers are:") } fmt.Printf("%4d ", i) } } if i == 2 { i-- } } fmt.Println() }
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 %
#PARI.2FGP
PARI/GP
  conspiracy(maxx)={ print("primes considered= ",maxx); x=matrix(9,9);cnt=0;p=2;q=2%10; while(cnt<=maxx, cnt+=1; m=q; p=nextprime(p+1); q= p%10; x[m,q]+=1); print (2," to ",3, " count: ",x[2,3]," freq ", 100./cnt,"  %" ); forstep(i=1,9,2, forstep(j=1,9,2, if( x[i,j]<1,continue); print (i," to ",j, " count: ",x[i,j]," freq ", 100.* x[i,j]/cnt,"  %" ))); print ("total transitions= ",cnt); print(p); }  
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
#AWK
AWK
# Usage: awk -f primefac.awk function pfac(n, r, f){ r = ""; f = 2 while (f <= n) { while(!(n % f)) { n = n / f r = r " " f } f = f + 2 - (f == 2) } return r }   # For each line of input, print the prime factors. { print pfac($1) }