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/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#VBA
VBA
Option Base 1 Private Function vtranspose(v As Variant) As Variant '-- transpose a vector of length m into an mx1 matrix, '-- eg {1,2,3} -> {1;2;3} vtranspose = WorksheetFunction.Transpose(v) End Function   Private Function mat_col(a As Variant, col As Integer) As Variant Dim res() As Doub...
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
#AWK
AWK
  # syntax: GAWK -f PRIMALITY_BY_WILSONS_THEOREM.AWK # converted from FreeBASIC BEGIN { start = 2 stop = 200 for (i=start; i<=stop; i++) { if (is_wilson_prime(i)) { printf("%5d%1s",i,++count%10?"":"\n") } } printf("\nWilson primality test range %d-%d: %d\n",start,stop,count) ...
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
#BASIC
BASIC
function wilson_prime(n) fct = 1 for i = 2 to n-1 fct = (fct * i) mod n next i if fct = n-1 then return True else return False end function   print "Primes below 100" & Chr(10) for i = 2 to 100 if wilson_prime(i) then print i; " "; next i end
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#PL.2FI
PL/I
declare (t(100),i) fixed binary; i=101; t(i)=0;
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#PowerShell
PowerShell
  #Requires -Version <N>[.<n>] #Requires –PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]] #Requires -Modules { <Module-Name> | <Hashtable> } #Requires –ShellId <ShellId> #Requires -RunAsAdministrator  
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Python
Python
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import __future__ >>> __future__.all_feature_names ['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals'...
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Racket
Racket
use MONKEY-TYPING; augment class Int { method times (&what) { what() xx self } # pretend like we're Ruby }
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 ...
#EchoLisp
EchoLisp
  (lib 'math) ;; (in-primes n) stream (decimals 4)   (define (print-trans trans m N) (printf "%d first primes. Transitions prime %% %d → next-prime %% %d." N m m) (define s (// (apply + (vector->list trans)) 100)) (for ((i (* m m)) (t trans)) #:continue (<= t 1) ;; get rid of 2,5 primes (printf " %d → %d count...
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 ...
#360_Assembly
360 Assembly
PRIMEDE CSECT USING PRIMEDE,R13 B 80(R15) skip savearea DC 17F'0' savearea DC CL8'PRIMEDE' STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 end prolog LA R2,0 ...
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#C.23
C#
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq;   internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) ...
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 invol...
#Clojure
Clojure
(defn to-cdf [pdf] (reduce (fn [acc n] (conj acc (+ (or (last acc) 0) n))) [] pdf))   (defn choose [cdf] (let [r (rand)] (count (filter (partial > r) cdf))))   (def *names* '[aleph beth gimel daleth he waw zayin heth]) (def *pdf* (map double [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720]))   (let ...
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 betw...
#Nim
Nim
import algorithm, strformat, strutils, sugar   const MaxSum = 99   func getPrimes(max: Positive): seq[int] = if max < 2: return result.add 2 for n in countup(3, max, 2): block check: for p in result: if n mod p == 0: break check result.add n   let primes = getPrimes(MaxSum)   var...
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 insert...
#CLU
CLU
prio_queue = cluster [P, T: type] is new, empty, push, pop where P has lt: proctype (P,P) returns (bool)   item = struct[prio: P, val: T] rep = array[item]   new = proc () returns (cvt) return (rep$create(0)) end new   empty = proc (pq: cvt) returns (bool) return (rep$...
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 ...
#Haskell
Haskell
data Circle = Circle { x, y, r :: Double } deriving (Show, Eq) data Tangent = Externally | Internally deriving Eq   {-- Solves the Problem of Apollonius (finding a circle tangent to three other circles in the plane).   Params: c1 = First circle of the problem. c2 = Second circle of the problem. c3 = Third circle ...
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 A...
#Oberon-2
Oberon-2
  MODULE ProgramName; IMPORT NPCT:Args, Out; BEGIN Out.Object("Program name: " + Args.Get(0));Out.Ln END ProgramName.  
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 A...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main(int argc, char **argv) { @autoreleasepool {   char *program = argv[0]; printf("Program: %s\n", program);   // Alternatively: NSString *program2 = [[NSProcessInfo processInfo] processName]; NSLog(@"Program: %@\n", program2);   }   return 0; }
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Sidef
Sidef
say ( 'First ten primorials: ', {|i| pn_primorial(i) }.map(^10).join(', ') )   { |i| say ("primorial(10^#{i}) has " + pn_primorial(10**i).len + ' digits') } << 1..6
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,...
#OCaml
OCaml
let isqrt n = let rec iter t = let d = n - t*t in if (0 <= d) && (d < t+t+1) (* t*t <= n < (t+1)*(t+1) *) then t else iter ((t+(n/t))/2) in iter 1   let rec gcd a b = let t = a mod b in if t = 0 then b else gcd b t   let coprime a b = gcd a b = 1   let num_to ms = let ctr = ref 0 in ...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { For i=1 to 200 Thread { k++ Print "Thread:"; num, "k=";k } as M Thread M Execute { static num=M, k=1000*i } Thread M interval 100+900*rnd next i   Task.Main 20 { if random(10)=1 then Set End } } Che...
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...
#M4
M4
beginning define(`problem',1) ifelse(problem,1,`m4exit(1)') ending
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#Wren
Wren
import "/matrix" for Matrix import "/fmt" for Fmt   var minor = Fn.new { |x, d| var nr = x.numRows var nc = x.numCols var m = Matrix.new(nr, nc) for (i in 0...d) m[i, i] = 1 for (i in d...nr) { for (j in d...nc) m[i, j] = x[i, j] } return m }   var vmadd = Fn.new { |a, b, s| var ...
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
#C
C
#include <stdbool.h> #include <stdint.h> #include <stdio.h>   uint64_t factorial(uint64_t n) { uint64_t product = 1;   if (n < 2) { return 1; }   for (; n > 0; n--) { uint64_t prev = product; product *= n; if (product < prev) { fprintf(stderr, "Overflowed\n");...
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
#C.23
C#
using System; using System.Linq; using System.Collections; using static System.Console; using System.Collections.Generic; using BI = System.Numerics.BigInteger;   class Program {   // initialization const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st; static string ms1 = "W...
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Raku
Raku
use MONKEY-TYPING; augment class Int { method times (&what) { what() xx self } # pretend like we're Ruby }
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#REXX
REXX
The REXX language has several pragmatic statements: ∙   NUMERIC DIGITS   {nnn} ∙   NUMERIC FORM     {ENGINEERING │ SCIENTIFIC} ∙   NUMERIC FUZZ     {nnn} ∙   OPTIONS         {xxx yyy zzz} ∙   TRACE         {options} ∙   SIGNAL         {ON │ OFF}   LOSTDIGITS ∙   SIGNAL         {ON │ OFF}   ...
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Scala
Scala
@inline @tailrec
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Tcl
Tcl
set -vx # Activate both script line output and command line arguments pragma set +vx # Deactivate both pragmatic directives
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#UNIX_Shell
UNIX Shell
set -vx # Activate both script line output and command line arguments pragma set +vx # Deactivate both pragmatic directives
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 ...
#Elixir
Elixir
defmodule Prime do def conspiracy(m) do IO.puts "#{m} first primes. Transitions prime % 10 → next-prime % 10." Enum.map(prime(m), &rem(&1, 10)) |> Enum.chunk(2,1) |> Enum.reduce(Map.new, fn [a,b],acc -> Map.update(acc, {a,b}, 1, &(&1+1)) end) |> Enum.sort |> Enum.each(fn {{a,b},v} -> ...
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 ...
#F.23
F#
  // Prime Conspiracy. Nigel Galloway: March 27th., 2018 primes|>Seq.take 10000|>Seq.map(fun n->n%10)|>Seq.pairwise|>Seq.countBy id|>Seq.groupBy(fun((n,_),_)->n)|>Seq.sortBy(fst) |>Seq.iter(fun(_,n)->Seq.sortBy(fun((_,n),_)->n) n|>Seq.iter(fun((n,g),z)->printfn "%d -> %d ocurred %3d times" n g z))  
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 ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program primeDecomp64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantes...
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...
#C.2B.2B
C++
#include <vector> #include <iostream> #include <algorithm>   std::vector<int> properDivisors ( int number ) { std::vector<int> divisors ; for ( int i = 1 ; i < number / 2 + 1 ; i++ ) if ( number % i == 0 ) divisors.push_back( i ) ; return divisors ; }   int main( ) { std::vector<int> divisors ; u...
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 invol...
#Common_Lisp
Common Lisp
(defvar *probabilities* '((aleph 1/5) (beth 1/6) (gimel 1/7) (daleth 1/8) (he 1/9) (waw 1/10) (zayin 1/11) ...
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 betw...
#Perl
Perl
use List::Util qw(sum uniq); use ntheory qw(nth_prime);   my $max = 99; my %tree;   sub allocate { my($n, $i, $sum,, $prod) = @_; $i //= 0; $sum //= 0; $prod //= 1;   for my $k (0..$max) { next if $k < $i; my $p = nth_prime($k+1); if (($sum + $p) <= $max) { allocate($n, $...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#CoffeeScript
CoffeeScript
  PriorityQueue = -> # Use closure style for object creation (so no "new" required). # Private variables are toward top. h = []   better = (a, b) -> h[a].priority < h[b].priority   swap = (a, b) -> [h[a], h[b]] = [h[b], h[a]]   sift_down = -> max = h.length n = 0 while n < max c1 =...
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 ...
#Icon_and_Unicon
Icon and Unicon
link graphics   record circle(x,y,r) global scale,xoffset,yoffset,yadjust   procedure main()   WOpen("size=400,400") | stop("Unable to open Window") scale := 28 xoffset := WAttrib("width") / 2 yoffset := ( yadjust := WAttrib("height")) / 2     WC(c1 := circle(0,0,1),"black") WC(c2 := circle(4,0,1),"black") WC(c3 := cir...
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 A...
#OCaml
OCaml
let () = print_endline Sys.executable_name; print_endline Sys.argv.(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 A...
#Octave
Octave
function main() program = program_name(); printf("Program: %s", program); endfunction   main();
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Smalltalk
Smalltalk
 
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Wren
Wren
import "/big" for BigInt import "/math" for Int import "/fmt" for Fmt   var vecprod = Fn.new { |primes| var le = primes.count if (le == 0) return BigInt.one var s = List.filled(le, null) for (i in 0...le) s[i] = BigInt.new(primes[i]) while (le > 1) { var c = (le/2).floor for(i in 0.....
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Ol
Ol
  ; triples generator based on Euclid's formula, creates lazy list (define (euclid-formula max) (let loop ((a 3) (b 4) (c 5) (tail #null)) (if (<= (+ a b c) max) (cons (tuple a b c) (lambda () (let ((d (- b)) (z (- a))) (loop (+ a d d c c) (+ a a d c c) (+ a a d d c c c) (lambd...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
If[problem, Abort[]];
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...
#MATLAB
MATLAB
if condition return end
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) A:=GSL.Matrix(3,3).set(12.0, -51.0, 4.0, 6.0, 167.0, -68.0, 4.0, 24.0, -41.0); Q,R:=A.QRDecomp(); println("Q:\n",Q.format()); println("R:\n",R.format()); println("Q*R:\n",(Q*R).format());
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
#C.2B.2B
C++
#include <iomanip> #include <iostream>   int factorial_mod(int n, int p) { int f = 1; for (; n > 0 && f != 0; --n) f = (f * n) % p; return f; }   bool is_prime(int p) { return p > 1 && factorial_mod(p - 1, p) == p - 1; }   int main() { std::cout << " n | prime?\n------------\n"; std::co...
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Wren
Wren
/* windows.wren */   class Windows { static message { "Using Windows" } static lineSeparator { "\\r\\n" } }
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#XPL0
XPL0
string 0; \makes all following strings in the code zero-terminated string 1; \(or any non-zero argument) reverts to MSB termination
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 ...
#Factor
Factor
USING: assocs formatting grouping kernel math math.primes math.statistics sequences sorting ; IN: rosetta-code.prime-conspiracy   : transitions ( n -- alist ) nprimes [ 10 mod ] map 2 clump histogram >alist natural-sort ;   : t-values ( transition -- i j count freq ) first2 [ first2 ] dip dup 10000. / ;   : pri...
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 ...
#Fortran
Fortran
PROGRAM INHERIT !Last digit persistence in successive prime numbers. USE PRIMEBAG !Inherit this also. INTEGER MBASE,P0,NHIC !Problem bounds. PARAMETER (MBASE = 13, P0 = 2, NHIC = 100000000) !This should do. INTEGER N(0:MBASE - 1,0:MBASE - 1,2:MBASE) !The counts. A triangular shape would be...
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 ...
#ABAP
ABAP
class ZMLA_ROSETTA definition public create public .   public section.   types: enumber TYPE N LENGTH 60, listof_enumber TYPE TABLE OF enumber .   class-methods FACTORS importing value(N) type ENUMBER exporting value(ORET) type LISTOF_ENUMBER . ...
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 ...
#11l
11l
F is_prime(n) I n < 2 R 0B L(i) 2..Int(sqrt(n)) I n % i == 0 R 0B R 1B
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 ...
#11l
11l
F bisect_right(a, x) V lo = 0 V hi = a.len L lo < hi V mid = (lo + hi) I/ 2 I x < a[mid] hi = mid E lo = mid + 1 R lo   V _cin = [0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01] V _cout = [0.10, 0.18...
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...
#Ceylon
Ceylon
shared void run() {   function divisors(Integer int) => if(int <= 1) then {} else (1..int / 2).filter((Integer element) => element.divides(int));   for(i in 1..10) { print("``i`` => ``divisors(i)``"); }   value start = 1; value end = 20k;   value mostDivisors = map {for(i in start..end) i->divis...
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 invol...
#D
D
void main() { import std.stdio, std.random, std.string, std.range;   enum int nTrials = 1_000_000; const items = "aleph beth gimel daleth he waw zayin heth".split; const pr = [1/5., 1/6., 1/7., 1/8., 1/9., 1/10., 1/11., 1759/27720.];   double[pr.length] counts = 0.0; foreach (immutable _; 0 .. nTrials) ...
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 betw...
#Phix
Phix
with javascript_semantics constant maxSum = 99 function stringify(sequence s) s = deep_copy(s) for i=1 to length(s) do s[i] = sprintf("%d",s[i]) end for return s end function procedure main() atom t0 = time() integer p sequence descendants = repeat({},maxSum+1), anc...
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 insert...
#Common_Lisp
Common Lisp
  ;priority-queue's are implemented with association lists (defun make-pq (alist) (sort (copy-alist alist) (lambda (a b) (< (car a) (car b))))) ; ;Will change the state of pq ; (define-modify-macro insert-pq (pair) (lambda (pq pair) (sort-alist (cons pair pq))))   (define-modify-macro remove-pq-a...
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 ...
#J
J
require 'math/misc/amoeba'   NB.*apollonius v solves Apollonius problems NB. y is Cx0 Cy0 R0, Cx1 Cy1 R1,: Cx2 Cy2 R2 NB. x are radius scale factors to control which circles are included NB. in the common tangent circle. 1 to surround, _1 to exclude. NB. returns Cxs Cys Rs apollonius =: verb define"1 _ 1 apollon...
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 A...
#Ol
Ol
  (print (car *vm-args*))  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Order
Order
__FILE__
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#zkl
zkl
sieve:=Import("sieve.zkl",False,False,False).postponed_sieve; primes:=Utils.Generator(sieve).walk(0d10); // first 10 primes foreach n in (10) { primes[0,n].reduce('*,1):println("primorial(%d)=%d".fmt(n,_)); }   var [const] BN=Import("zklBigNum"); primes:=Utils.Generator(sieve).walk(0d1_000_000); foreach n in ([1..6...
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,...
#PARI.2FGP
PARI/GP
do(lim)={ my(prim,total,P); lim\=1; for(m=2,sqrtint(lim\2), forstep(n=1+m%2,min(sqrtint(lim-m^2),m-1),2, P=2*m*(m+n); if(gcd(m,n)==1 && P<=lim, prim++; total+=lim\P ) ) ); [prim,total] }; do(100)
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...
#Maxima
Maxima
/* Basically, it's simply quit() */   block([ans], loop, if (ans: read("Really quit ? (y, n)")) = 'y then quit() elseif ans = 'n then (print("Nice choice!"), 'done) else (print("I dont' understand..."), go(loop)));
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...
#.D0.9C.D0.9A-61.2F52
МК-61/52
ИП0 x=0 04 С/П ...
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
#CLU
CLU
% Wilson primality test wilson = proc (n: int) returns (bool) if n<2 then return (false) end fac_mod: int := 1 for i: int in int$from_to(2, n-1) do fac_mod := fac_mod * i // n end return (fac_mod + 1 = n) end wilson   % Print primes up to 100 using Wilson's theorem start_up = proc () ...
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
#Common_Lisp
Common Lisp
  (defun factorial (n) (if (< n 2) 1 (* n (factorial (1- n)))) )     (defun primep (n) "Primality test using Wilson's Theorem" (unless (zerop n) (zerop (mod (1+ (factorial (1- n))) n)) ))  
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 ...
#FreeBASIC
FreeBASIC
' version 13-04-2017 ' updated 09-08-2018 Using bit-sieve of odd numbers ' compile with: fbc -s console ' compile with: fbc -s console -Wc -O2 ->more than 2x faster(20.2-> 8,7s)   const max = 2040*1000*1000 ' enough for 100,000,000 primes const max2 = (max -1) \ 2 Dim As uByte _bit(7) Dim shared As uByte sieve(max...
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 ...
#ACL2
ACL2
(include-book "arithmetic-3/top" :dir :system)   (defun prime-factors-r (n i) (declare (xargs :mode :program)) (cond ((or (zp n) (zp (- n i)) (zp i) (< i 2) (< n 2)) (list n)) ((= (mod n i) 0) (cons i (prime-factors-r (floor n i) 2))) (t (prime-factors-r n (1+ i)))))   (defun...
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 ...
#360_Assembly
360 Assembly
* Primality by trial division 26/03/2017 PRIMEDIV CSECT USING PRIMEDIV,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ...
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 ...
#Action.21
Action!
DEFINE COUNT="20" BYTE ARRAY levels=[6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 101] BYTE ARRAY values=[10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100]   PROC PrintValue(BYTE v) PrintB(v/100) Put('.) v=v MOD 100 PrintB(v/10) v=v MOD 10 PrintB(v) RETURN   BYTE FUNC Map(BYTE v) BYTE...
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 ...
#Ada
Ada
  type Price is delta 0.01 digits 3 range 0.0..1.0; function Scale (Value : Price) return Price is X : constant array (1..19) of Price := ( 0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96 ); Y : constant array (1....
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...
#Clojure
Clojure
(ns properdivisors (:gen-class))   (defn proper-divisors [n] " Proper divisors of n" (if (= n 1) [] (filter #(= 0 (rem n %)) (range 1 n))))   ;; Property divisors of numbers 1 to 20,000 inclusive (def data (for [n (range 1 (inc 20000))] [n (proper-divisors n)]))   ;; Find Max (defn maximal-key [...
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 invol...
#E
E
pragma.syntax("0.9")
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 invol...
#Elixir
Elixir
defmodule Probabilistic do @tries 1000000 @probs [aleph: 1/5, beth: 1/6, gimel: 1/7, daleth: 1/8, he: 1/9, waw: 1/10, zayin: 1/11, heth: 1759/27720]   def test do trials = for _ <- 1..@tries, do: get_choice(@probs, :rand.unifo...
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 betw...
#Python
Python
from __future__ import print_function from itertools import takewhile   maxsum = 99   def get_primes(max): if max < 2: return [] lprimes = [2] for x in range(3, max + 1, 2): for p in lprimes: if x % p == 0: break else: lprimes.append(x) ret...
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 insert...
#Component_Pascal
Component Pascal
  MODULE PQueues; IMPORT StdLog,Boxes;   TYPE Rank* = POINTER TO RECORD p-: LONGINT; (* Priority *) value-: Boxes.Object END;   PQueue* = POINTER TO RECORD a: POINTER TO ARRAY OF Rank; size-: LONGINT; END;   PROCEDURE NewRank*(p: LONGINT; v: Boxes.Object): Rank; VAR r: Rank; BEGIN ...
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 ...
#Java
Java
public class Circle { public double[] center; public double radius; public Circle(double[] center, double radius) { this.center = center; this.radius = radius; } public String toString() { return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1], radius); } }   public class Apollon...
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 A...
#PARI.2FGP
PARI/GP
program ScriptName; var prog : String; begin prog := ParamStr(0); write('Program: '); writeln(prog) end.
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Pascal
Pascal
program ScriptName; var prog : String; begin prog := ParamStr(0); write('Program: '); writeln(prog) end.
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Pascal
Pascal
Program PythagoreanTriples (output);   var total, prim, maxPeri: int64;   procedure newTri(s0, s1, s2: int64); var p: int64; begin p := s0 + s1 + s2; if p <= maxPeri then begin inc(prim); total := total + maxPeri div p; newTri( s0 + 2*(-s1+s2), 2*( s0+s2) - s1, 2*( s0-s1+s2) + ...
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...
#Nanoquery
Nanoquery
exit exit(0)
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Neko
Neko
/* Program termination, in Neko */   var sys_exit = $loader.loadprim("std@sys_exit", 1)   var return_code = 42 if true sys_exit(return_code)   $print("Control flow does not make it this far")
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
#Cowgol
Cowgol
include "cowgol.coh";   # Wilson primality test sub wilson(n: uint32): (out: uint8) is out := 0; if n >= 2 then var facmod: uint32 := 1; var ct := n - 1; while ct > 0 loop facmod := (facmod * ct) % n; ct := ct - 1; end loop; if facmod + 1 == n then...
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
#D
D
import std.bigint; import std.stdio;   BigInt fact(long n) { BigInt f = 1; for (int i = 2; i <= n; i++) { f *= i; } return f; }   bool isPrime(long p) { if (p <= 1) { return false; } return (fact(p - 1) + 1) % p == 0; }   void main() { writeln("Primes less than 100 testin...
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 ...
#Go
Go
package main   import ( "fmt" "sort" )   func sieve(limit uint64) []bool { limit++ // True denotes composite, false denotes prime. // We don't bother filling in the even composites. c := make([]bool, limit) c[0] = true c[1] = true p := uint64(3) // Start from 3. for { p2 := p * p if p2 >= limit { break...
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 ...
#Ada
Ada
generic type Number is private; Zero : Number; One  : Number; Two  : Number; with function "+" (X, Y : Number) return Number is <>; with function "*" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Numbe...
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 b...
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   INT ARRAY SinTab=[ 0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83 88 92 96 100 104 108 112 116 120 124 128 132 136 139 143 147 150 154 158 161 165 168 171 175 178 181 184 187 190 193 196 199 202 204 207 210 212 215 217 219 222 224 226 228 230 232 234 236 237 239 241 242 2...
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 ...
#68000_Assembly
68000 Assembly
isPrime: ; REG USAGE: ; D0 = input (unsigned 32-bit integer) ; D1 = temp storage for D0 ; D2 = candidates for possible factors ; D3 = temp storage for quotient/remainder ; D4 = total count of proper divisors.   MOVEM.L D1-D4,-(SP) ;push data regs except D0 MOVE.L #0,D1 MOVEM.L D1,D2-D4 ;clear regs D1 thru ...
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 ...
#ALGOL_68
ALGOL 68
main: ( # Just get a random price between 0 and 1 # # srand(time(NIL)); # REAL price := random; REAL tops := 0.06; REAL std val := 0.10;   # Conditionals are a little odd here "(price-0.001 < tops AND price+0.001 > tops)" is to check if they are equal. Stupid C floats, right?  :) # ...
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...
#Common_Lisp
Common Lisp
(defun proper-divisors-recursive (product &optional (results '(1))) "(int,list)->list::Function to find all proper divisors of a +ve integer."   (defun smallest-divisor (x) "int->int::Find the smallest divisor of an integer > 1." (if (evenp x) 2 (do ((lim (truncate (sqrt x))) ...
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 invol...
#Erlang
Erlang
  -module(probabilistic_choice).   -export([test/0]).   -define(TRIES, 1000000).   test() -> Probs = [{aleph,1/5}, {beth,1/6}, {gimel,1/7}, {daleth,1/8}, {he,1/9}, {waw,1/10}, {zayin,1/11}, {heth,1759/27720}], random:seed(now()), Trials = [get_choice(Probs,random:uniform()) || _ <- list...
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 betw...
#Racket
Racket
#lang racket   (define-syntax-rule (define/mem (name args ...) body ...) (begin (define cache (make-hash)) (define (name args ...) (hash-ref! cache (list args ...) (lambda () body ...)))))   (define (take-last x n) (drop x (- (length x) n)))   (define (borders x) (if (> (length x) 5) (append (ta...
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 betw...
#Raku
Raku
my $max = 99; my @primes = (2 .. $max).grep: *.is-prime; my %tree; (1..$max).map: { %tree{$_}<ancestor> = (); %tree{$_}<descendants> = {}; };     sub allocate ($n, $i = 0, $sum = 0, $prod = 1) { return if $n < 4; for @primes.kv -> $k, $p { next if $k < $i; if ($sum + $p) <= $n { ...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#D
D
import std.stdio, std.container, std.array, std.typecons;   void main() { alias tuple T; auto heap = heapify([T(3, "Clear drains"), T(4, "Feed cat"), T(5, "Make tea"), T(1, "Solve RC tasks"), T(2, "Tax return")])...
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 ...
#jq
jq
def circle: {"x": .[0], "y": .[1], "r": .[2]};   # Find the interior or exterior Apollonius circle of three circles: # ap(circle, circle, circle, boolean) # Specify s as true for interior; false for exterior def ap(c1; c2; c3; s): def sign: if s then -. else . end; (c1.x * c1.x) as $x1sq | (c1.y * c1.y) as $y...
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 A...
#Perl
Perl
#!/usr/bin/env perl   use strict; use warnings;   sub main { my $program = $0; print "Program: $program\n"; }   unless(caller) { main; }
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Phix
Phix
with javascript_semantics string cl2 = command_line()[2] printf(1,"%s\n",cl2) -- full path printf(1,"%s\n",get_file_name(cl2)) -- eg test.exw or test.exe or test.htm printf(1,"%s\n",get_file_base(cl2)) -- eg test
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,...
#Perl
Perl
sub gcd { my ($n, $m) = @_; while($n){ my $t = $n; $n = $m % $n; $m = $t; } return $m; }   sub tripel { my $pmax = shift; my $prim = 0; my $count = 0; my $nmax = sqrt($pmax)/2; for( my $n=1; $n<=$nmax; $n++ ) { for( my $m=$n+1; (my $p = 2*$m*($m+$n))...
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Nemerle
Nemerle
using System.Environment ... when (problem) Exit(1) ...
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   extremePrejudice = (1 == 1) if extremePrejudice then do exit extremePrejudice end   return  
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
#EDSAC_order_code
EDSAC order code
  [Primes by Wilson's Theoem, for Rosetta Code.] [EDSAC program, Initial Orders 2.] T51K P64F [address for G parameter: low-level subroutines] T47K P130F [M parameter: main routine + high-level subroutine]   [======== M parameter: Main routine + high-level subroutine ============] E...