task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { ITERATIONS = 1000000 delete symbMap delete probMap delete counts initData();   for (i = 0; i < ITERATIONS; i++) { distribute(rand()) } showDistributions()   exit }   function distribute(rnd, cnt, symNum, sym, symPrb) { cnt = length(symbMap) ...
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...
#Go
Go
package main   import ( "fmt" "sort" )   func getPrimes(max int) []int { if max < 2 { return []int{} } lprimes := []int{2} outer: for x := 3; x <= max; x += 2 { for _, p := range lprimes { if x%p == 0 { continue outer } } lp...
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...
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion   call :push 10 "item ten" call :push 2 "item two" call :push 100 "item one hundred" call :push 5 "item five"   call :pop & echo !order! !item! call :pop & echo !order! !item! call :pop & echo !order! !item! call :pop & echo !order! !item! call :pop & echo !order! !item!...
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 ...
#F.23
F#
type point = { x:float; y:float } type circle = { center: point; radius: float; }   let new_circle x y r = { center = { x=x; y=y }; radius = r }   let print_circle c = printfn "Circle(x=%.2f, y=%.2f, r=%.2f)" c.center.x c.center.y c.radius   let xyr c = c.center.x, c.center.y, c.radius   let solve_apollonius...
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...
#Make
Make
NAME=$(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))   all: @echo $(NAME)  
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#PicoLisp
PicoLisp
  (de prime? (N Lst) (let S (sqrt N) (for D Lst (T (> D S) T) (T (=0 (% N D)) NIL) ) ) )   (de take (N) (let I 1 (make (link 2) (do (dec N) (until (prime? (inc 'I 2) (made))) (link I) ) ) ) )   # This is a simple approach to calculate primori...
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,...
#MATLAB_.2F_Octave
MATLAB / Octave
N= 100; a = 1:N; b = a(ones(N,1),:).^2; b = b+b'; b = sqrt(b); [y,x]=find(b==fix(b)); % test % here some alternative tests % b = b.^(1/k); [y,x]=find(b==fix(b)); % test 2 % [y,x]=find(b==(fix(b.^(1/k)).^k));  % test 3 % b=b.^(1/k); [y,x]=find(abs(b - round(b)) <= 4*eps*b);   z = sqrt(x.^2+y.^2); ...
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...
#JavaScript
JavaScript
if (some_condition) quit();
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#jq
jq
$ jq -n '"Hello", if 1 then error else 2 end' "Hello"
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#SPAD
SPAD
signature RADCATFIELD = sig type real val zero : real val one : real val + : real * real -> real val - : real * real -> real val * : real * real -> real val / : real * real -> real val sign : real -> real val sqrt : real -> real end   functor QR(F: RADCATFIELD) = struct structure A = struct local open Array in fun ...
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem...
#Raku
Raku
my @count = 0, 0, 1; my $lock = Lock.new; put (1,2);   for 3..17 -> $n { my @even = (2..^$n).grep: * %% 2; my @odd = (3..^$n).grep: so * % 2; @even.permutations.race.map: -> @e { quietly next if @e[0] == 8|14; my $nope = 0; for @odd.permutations -> @o { quietly next unle...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#8086_Assembly
8086 Assembly
cpu 8086 org 100h section .text jmp demo ;;; Wilson primality test of CX. ;;; Zero flag set if CX prime. Destroys AX, BX, DX. wilson: xor ax,ax ; AX will hold intermediate fac-mod value inc ax mov bx,cx ; BX = factorial loop counter dec bx .loop: mul bx ; DX:AX = AX*BX div cx ; modulus goes in DX mov ax,d...
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...
#8086_Assembly
8086 Assembly
#!/usr/local/bin/a68g --script #   PRAGMAT portcheck PRAGMAT PR portcheck PR   BEGIN PR heap=256M PR # algol68g pragma # ~ END;   PROC (REAL)REAL s = sin();   SKIP
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Ada
Ada
#!/usr/local/bin/a68g --script #   PRAGMAT portcheck PRAGMAT PR portcheck PR   BEGIN PR heap=256M PR # algol68g pragma # ~ END;   PROC (REAL)REAL s = sin();   SKIP
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   PRAGMAT portcheck PRAGMAT PR portcheck PR   BEGIN PR heap=256M PR # algol68g pragma # ~ END;   PROC (REAL)REAL s = sin();   SKIP
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#BASIC
BASIC
10 TRON: REM activate system trace pragma 20 TROFF: REM deactivate system trace pragma
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#C
C
#include <assert.h> #include <stdbool.h> #include <stdio.h>   typedef unsigned char byte;   struct Transition { byte a, b; unsigned int c; } transitions[100];   void init() { int i, j; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { int idx = i * 10 + j; transitions...
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...
#AWK
AWK
  # syntax: GAWK -f PROPER_DIVISORS.AWK BEGIN { show = 0 # show divisors: 0=no, 1=yes print(" N cnt DIVISORS") for (i=1; i<=20000; i++) { divisors(i) if (i <= 10 || i == 100) { # including 100 as it was an example in task description printf("%5d  %3d  %s\n",i,Dcnt,Dstr) } ...
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...
#BASIC256
BASIC256
dim letters$ = {"aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"} dim actual(8) fill 0 ## all zero by default dim probs = {1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 0} dim cumProbs(8)   cumProbs[0] = probs[0] for i = 1 to 6 cumProbs[i] = cumProbs[i - 1] + probs[i] next i cumProbs[7] = 1.0 prob...
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...
#Haskell
Haskell
{-# LANGUAGE DeriveFunctor #-} import Data.Numbers.Primes (isPrime) import Data.List   ------------------------------------------------------------ -- memoization utilities   type Memo2 a = Memo (Memo a)   data Memo a = Node a (Memo a) (Memo a) deriving Functor   memo :: Integral a => Memo p -> a -> p memo (Node a l ...
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...
#C
C
#include <stdio.h> #include <stdlib.h>   typedef struct { int priority; char *data; } node_t;   typedef struct { node_t *nodes; int len; int size; } heap_t;   void push (heap_t *h, int priority, char *data) { if (h->len + 1 >= h->size) { h->size = h->size ? h->size * 2 : 4; h->no...
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 ...
#Fortran
Fortran
program Apollonius implicit none   integer, parameter :: dp = selected_real_kind(15)   type circle real(dp) :: x real(dp) :: y real(dp) :: radius end type   type(circle) :: c1 , c2, c3, r   c1 = circle(0.0, 0.0, 1.0) c2 = circle(4.0, 0.0, 1.0) c3 = circle(2.0, 4.0, 2.0)   write(*, "(a,3f12...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
#!/usr/bin/env MathKernel -script ScriptName[] = Piecewise[ { {"Interpreted", Position[$CommandLine, "-script", 1] == {}} }, $CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]] ] Program = ScriptName[]; Print["Program: " <> Program]
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Mercury
Mercury
:- module program_name. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation.   main(!IO) :-  % The first argument is used as the program name if it is not otherwise  % available. (We could also have used the predicate io.progname_base/4  % if we did not want path prec...
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×...
#Python
Python
from pyprimes import nprimes from functools import reduce     primelist = list(nprimes(1000001)) # [2, 3, 5, ...]   def primorial(n): return reduce(int.__mul__, primelist[:n], 1)   if __name__ == '__main__': print('First ten primorals:', [primorial(n) for n in range(10)]) for e in range(7): n = 1...
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Racket
Racket
#lang racket   (require (except-in math/number-theory nth-prime))   (define-syntax-rule (define/cache (name arg) body ...) (begin (define cache (make-hash)) (define (name arg) (hash-ref! cache arg (lambda () body ...)))))   (define (num-length n)  ;warning: this defines (num-length 0) as 0 (if (zero?...
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,...
#Mercury
Mercury
  :- module comprehension. :- interface. :- import_module io. :- import_module int.   :- type triple ---> triple(int, int, int).   :- pred pythTrip(int::in,triple::out) is nondet. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module solutions.   pythTrip(Limit,triple(X,Y,Z)) :- nondet_int_in_r...
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...
#Jsish
Jsish
assert(0 == 1);   if (problem) exit(1);
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Julia
Julia
  quit() # terminates program normally, with its child processes. See also exit(0).  
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#Standard_ML
Standard ML
signature RADCATFIELD = sig type real val zero : real val one : real val + : real * real -> real val - : real * real -> real val * : real * real -> real val / : real * real -> real val sign : real -> real val sqrt : real -> real end   functor QR(F: RADCATFIELD) = struct structure A = struct local open Array in fun ...
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem...
#Rust
Rust
fn is_prime(n: u32) -> bool { assert!(n < 64); ((1u64 << n) & 0x28208a20a08a28ac) != 0 }   fn prime_triangle_row(a: &mut [u32]) -> bool { if a.len() == 2 { return is_prime(a[0] + a[1]); } for i in (1..a.len() - 1).step_by(2) { if is_prime(a[0] + a[i]) { a.swap(i, 1); ...
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem...
#Swift
Swift
import Foundation   func isPrime(_ n: Int) -> Bool { guard n > 0 && n < 64 else { return false } return ((UInt64(1) << n) & 0x28208a20a08a28ac) != 0 }   func primeTriangleRow(_ a: inout [Int], start: Int, length: Int) -> Bool { if length == 2 { return isPrime(a[start] + a[start + 1]) ...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Ada
Ada
-- -- Determine primality using Wilon's theorem. -- Uses the approach from Algol W -- allowing large primes without the use of big numbers. -- with Ada.Text_IO; use Ada.Text_IO;   procedure Main is type u_64 is mod 2**64; package u_64_io is new modular_io (u_64); use u_64_io;   function Is_Prime (n : u_64)...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#ALGOL_68
ALGOL 68
BEGIN # find primes using Wilson's theorem: # # p is prime if ( ( p - 1 )! + 1 ) mod p = 0 #   # returns true if p is a prime by Wilson's theorem, false otherwise # # computes the factorial mod p at each stage, so as to # # al...
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...
#C
C
  /*Almost every C program has the below line, the #include preprocessor directive is used to instruct the compiler which files to load before compiling the program.   All preprocessor commands begin with # */ #include<stdio.h>   /*The #define preprocessor directive is often used to create abbreviations for code seg...
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...
#Common_Lisp
Common Lisp
? *features* (:EASYGUI :ASDF2 :ASDF :HEMLOCK :APPLE-OBJC-2.0 :APPLE-OBJC :PRIMARY-CLASSES :COMMON-LISP :OPENMCL :CCL :CCL-1.2 :CCL-1.3 :CCL-1.4 :CCL-1.5 :CCL-1.6 :CCL-1.7 :CCL-1.8 :CLOZURE :CLOZURE-COMMON-LISP :ANSI-CL :UNIX :OPENMCL-UNICODE-STRINGS :OPENMCL-NATIVE-THREADS :OPENMCL-PARTIAL-MOP :MCL-COMMON-MOP-SUBSET :O...
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...
#D
D
-compile( [compressed, {inline,[pi/0]}] ).
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Erlang
Erlang
-compile( [compressed, {inline,[pi/0]}] ).
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Factor
Factor
// +build <expression>
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#C.23
C#
using System;   namespace PrimeConspiracy { class Program { static void Main(string[] args) { const int limit = 1_000_000; const int sieveLimit = 15_500_000;   int[,] buckets = new int[10, 10]; int prevDigit = 2; bool[] notPrime = Sieve(sieveLimit)...
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...
#BASIC
BASIC
FUNCTION CountProperDivisors (number) IF number < 2 THEN CountProperDivisors = 0 count = 0 FOR i = 1 TO number \ 2 IF number MOD i = 0 THEN count = count + 1 NEXT i CountProperDivisors = count END FUNCTION   SUB ListProperDivisors (limit) IF limit < 1 THEN EXIT SUB FOR i = 1 TO limit...
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...
#BBC_BASIC
BBC BASIC
DIM item$(7), prob(7), cnt%(7) item$() = "aleph","beth","gimel","daleth","he","waw","zayin","heth" prob() = 1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720 IF ABS(SUM(prob())-1) > 1E-6 ERROR 100, "Probabilities don't sum to 1"   FOR trial% = 1 TO 1E6 r = RND(1) ...
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...
#C
C
#include <stdio.h> #include <stdlib.h>   /* pick a random index from 0 to n-1, according to probablities listed in p[] which is assumed to have a sum of 1. The values in the probablity list matters up to the point where the sum goes over 1 */ int rand_idx(double *p, int n) { double s = rand() / (RAND_MAX + 1.0);...
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...
#J
J
require'strings files'   family=:3 :0 M. if. 2>y do. i.0 NB. no primes less than 2 else. p=. i.&.(p:inv) y (y#~1 p:y),~.;p (* family)&.>y-p end. )   familytree=: +/@q:^:a: ::(''"_)   descendants=: family -. ] ancestors=: 1 }. familytree level=: #@ancestors"0   taskfmt=:'None'"_^:(0=#)@rplc&(' ';', '...
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...
#C.23
C#
using System; using System.Collections.Generic;   namespace PriorityQueueExample { class Program { static void Main(string[] args) { // Starting with .NET 6.0 preview 2 (released March 11th, 2021), there's a built-in priority queue var p = new PriorityQueue<string, int>(); p.Enqueue("Clear drains", 3); ...
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 ...
#FreeBASIC
FreeBASIC
  Dim As String circle1 = " 0.000, 0.000, 1.000" Dim As String circle2 = " 4.000, 0.000, 1.000" Dim As String circle3 = " 2.000, 4.000, 2.000"   Sub ApolloniusSolver(c1 As String, c2 As String, c3 As String, s1 As Single, s2 As Single, s3 As Single) Dim As Single x1, x2, x3, y1, y2, y3, r1, r2, r3 Dim ...
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...
#Mozart.2FOz
Mozart/Oz
all: test   test: scriptname ./scriptname   scriptname: scriptname.oz ozc -x scriptname.oz   clean: -rm scriptname -rm *.exe
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Nanoquery
Nanoquery
println args[1]
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Raku
Raku
use Math::Primesieve;   my $sieve = Math::Primesieve.new; my @primes = $sieve.primes(10_000_000);   sub primorial($n) { [*] @primes[^$n] }   say "First ten primorials: {(primorial $_ for ^10)}"; say "primorial(10^$_) has {primorial(10**$_).chars} digits" for 1..5;
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#REXX
REXX
/*REXX program computes some primorial numbers for low numbers, and for various 10^n.*/ parse arg N H . /*get optional arguments: N, L, H */ if N=='' | N==',' then N= 10 /*Not specified? Then use the default.*/ if H=='' | H==',' then H= 100000 ...
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,...
#Modula-3
Modula-3
MODULE PyTriple64 EXPORTS Main;   IMPORT IO, Fmt;   VAR tcnt, pcnt, max, i: INTEGER;   PROCEDURE NewTriangle(a, b, c: INTEGER; VAR tcount, pcount: INTEGER) = VAR perim := a + b + c; BEGIN IF perim <= max THEN pcount := pcount + 1; tcount := tcount + max DIV perim; NewTriangle(a-2*b+2*c, ...
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...
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { val problem = true if (problem) System.exit(1) // non-zero code passed to OS to indicate a problem println("Program terminating normally") // this line will not be executed }
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Lasso
Lasso
#!/usr/bin/lasso9 //[   handle => { stdoutnl('The end is here') }   stdoutnl('Starting execution')   abort   stdoutnl('Ending execution')
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#Stata
Stata
mata : qrd(a=(12,-51,4\6,167,-68\-4,24,-41),q=.,r=.)   : a 1 2 3 +-------------------+ 1 | 12 -51 4 | 2 | 6 167 -68 | 3 | -4 24 -41 | +-------------------+   : q 1 2 3 +----------------------------------------------+...
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem...
#Visual_Basic_.NET
Visual Basic .NET
Option Strict On Option Explicit On   Imports System.IO   ''' <summary>Find solutions to the "Prime Triangle" - a triangle of numbers that sum to primes.</summary> Module vMain   Public Const maxNumber As Integer = 20 ' Largest number we will consider. Dim prime(2 * maxNumber) As Boolean ' prime sieve.   ...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#ALGOL_W
ALGOL W
begin  % find primes using Wilson's theorem:  %  % p is prime if ( ( p - 1 )! + 1 ) mod p = 0  %    % returns true if n is a prime by Wilson's theorem, false otherwise %  % computes the factorial mod p at each stage, so as to  %  % al...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#APL
APL
wilson ← {⍵<2:0 ⋄ (⍵-1)=(⍵|×)/⍳⍵-1}
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Go
Go
// +build <expression>
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Icon_and_Unicon
Icon and Unicon
&trace # controls execution tracing &error # controls error handling
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#J
J
9!:1 random seed (incomplete specification of state -- see 9!:45) 9!:3 default display for non-nouns 9!:7 box drawing characters 9!:9 error messages 9!:11 print precision 9!:17 centering (or not) when box contents are smaller than boxes 9!:19 comparison tolerance 9!:21 memory limit 9!:25 security level 9!:27 text of i...
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...
#Julia
Julia
x = rand(100, 100) y = rand(100, 100)   @inbounds begin for i = 1:100 for j = 1:100 x[i, j] *= y[i, j] y[i, j] += x[i, j] end end end  
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Kotlin
Kotlin
// version 1.0.6   @Suppress("UNUSED_VARIABLE")   fun main(args: Array<String>) { val s = "To be suppressed" }
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Lua
Lua
ffi = require("ffi") ffi.cdef[[ #pragma pack(1) typedef struct { char c; int i; } foo; #pragma pack(4) typedef struct { char c; int i; } bar; ]] print(ffi.sizeof(ffi.new("foo"))) print(ffi.sizeof(ffi.new("bar")))
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#C.2B.2B
C++
#include <vector> #include <iostream> #include <cmath> #include <utility> #include <map> #include <iomanip>   bool isPrime( int i ) { int stop = std::sqrt( static_cast<double>( i ) ) ; for ( int d = 2 ; d <= stop ; d++ ) if ( i % d == 0 ) return false ; return true ; }   class Compare { public : Com...
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...
#BaCon
BaCon
  FUNCTION ProperDivisor(nr, show)   LOCAL probe, total   FOR probe = 1 TO nr-1 IF MOD(nr, probe) = 0 THEN IF show THEN PRINT " ", probe; INCR total END IF NEXT   RETURN total   END FUNCTION   FOR x = 1 TO 10 PRINT x, ":"; IF ProperDivisor(x, 1) = 0 THEN P...
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...
#C.23
C#
  using System;   class Program { static long TRIALS = 1000000L; private class Expv { public string name; public int probcount; public double expect; public double mapping;   public Expv(string name, int probcount, double expect, double mapping) { ...
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...
#Java
Java
import java.io.*; import java.util.*;   public class PrimeDescendants { public static void main(String[] args) { try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) { printPrimeDesc(writer, 100); } catch (IOException ex) { ex.printStackTrace(); ...
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...
#C.2B.2B
C++
#include <iostream> #include <string> #include <queue> #include <utility>   int main() { std::priority_queue<std::pair<int, std::string> > pq; pq.push(std::make_pair(3, "Clear drains")); pq.push(std::make_pair(4, "Feed cat")); pq.push(std::make_pair(5, "Make tea")); pq.push(std::make_pair(1, "Solve RC tasks")...
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 ...
#FutureBasic
FutureBasic
Problem of Apollonius   include "NSLog.incl"   begin record Circle CGPoint center double radius CFStringRef locator end record   local fn CircleToString( c as Circle ) as CFStringRef end fn = fn StringWithFormat( @"%@ Circle( x = %0.3f, y = %0.3f, radius = %0.3f )", c.locator, c.center.x, c.center.y, c.radius ...
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...
#Nemerle
Nemerle
using System.Environment; ... def program_name = GetCommandLineArgs()[0]; ...
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   package org.rosettacode.samples   say 'Source: ' source say 'Program:' System.getProperty('sun.java.command') return  
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Ring
Ring
  # Project: Primorial numbers load "bignumber.ring" decimals(0) num = 0 prim = 0 limit = 10000000 see "working..." + nl see "wait for done..." + nl while num < 100001 prim = prim + 1 prime = [] primorial(prim) end see "done..." + nl   func primorial(pr) n = 1 n2 = 0 flag = 1 while...
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×...
#Ruby
Ruby
require 'prime'   def primorial_number(n) pgen = Prime.each (1..n).inject(1){|p,_| p*pgen.next} end   puts "First ten primorials: #{(0..9).map{|n| primorial_number(n)}}"   (1..5).each do |n| puts "primorial(10**#{n}) has #{primorial_number(10**n).to_s.size} digits" end
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Nanoquery
Nanoquery
import math   // a function to check if three numbers are a valid triple def is_triple(a, b, c) if not (a < b) and (b < c) return false end   return (a^2 + b^2) = c^2 end   // a function to check if the numbers are coprime def is_coprime(a, b, c) global math return (math.gcd(a, b)=1) && (mat...
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...
#Liberty_BASIC
Liberty BASIC
if 2 =2 then end
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#Tcl
Tcl
package require Tcl 8.5 namespace path {::tcl::mathfunc ::tcl::mathop} proc sign x {expr {$x == 0 ? 0 : $x < 0 ? -1 : 1}} proc norm vec { set s 0 foreach x $vec {set s [expr {$s + $x**2}]} return [sqrt $s] } proc unitvec n { set v [lrepeat $n 0.0] lset v 0 1.0 return $v } proc I n { set m [l...
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem...
#Wren
Wren
import "./fmt" for Fmt   var canFollow = [] var arrang = [] var bFirst = true   var pmap = {} for (i in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]) { pmap[i] = true }   var ptrs ptrs = Fn.new { |res, n, done| var ad = arrang[done-1] if (n - done <= 1) { if (canFollow[ad-1][n-1]) { if (...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#AppleScript
AppleScript
on isPrime(n) if (n < 2) then return false set f to n - 1 repeat with i from (n - 2) to 2 by -1 set f to f * i mod n end repeat   return ((f + 1) mod n = 0) end isPrime   local output, n set output to {} repeat with n from 0 to 500 if (isPrime(n)) then set end of output to n end repeat o...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Arturo
Arturo
factorial: function [x]-> product 1..x   wprime?: function [n][ if n < 2 -> return false zero? mod add factorial sub n 1 1 n ]   print "Primes below 20 via Wilson's theorem:" print select 1..20 => wprime?
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
{.checks: off, optimization: speed.} # Checks are deactivated and code is generated for speed.   # Define a type Color as pure which implies that value names are declared in their own scope # and may/should be accessed with their type qualifier (as Color.Red). type Color {.pure.} = enum Red, Green, Blue   # Declare ...
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...
#NetRexx
NetRexx
{.checks: off, optimization: speed.} # Checks are deactivated and code is generated for speed.   # Define a type Color as pure which implies that value names are declared in their own scope # and may/should be accessed with their type qualifier (as Color.Red). type Color {.pure.} = enum Red, Green, Blue   # Declare ...
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...
#Nim
Nim
{.checks: off, optimization: speed.} # Checks are deactivated and code is generated for speed.   # Define a type Color as pure which implies that value names are declared in their own scope # and may/should be accessed with their type qualifier (as Color.Red). type Color {.pure.} = enum Red, Green, Blue   # Declare ...
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...
#Perl
Perl
use warnings; # use warnings pragma module use strict; # use strict pragma module
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Phix
Phix
requires(JS) --requires(WINDOWS) -- (one of only, or --requires(LINUX) -- a special combo) requires("1.0.2") requires(32) -- or 64
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#PicoLisp
PicoLisp
declare (t(100),i) fixed binary; i=101; t(i)=0;
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#D
D
import std.algorithm; import std.range; import std.stdio; import std.typecons;   alias Transition = Tuple!(int, int);   bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; ...
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 ...
#11l
11l
F decompose(BigInt number) [BigInt] result V n = number BigInt i = 2 L n % i == 0 result.append(i) n I/= i i = 3 L n >= i * i L n % i == 0 result.append(i) n I/= i i += 2 I n != 1 result.append(n) R result   L(i) 2..9 print(decompose(i)) print(d...
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
C
  #include <stdio.h> #include <stdbool.h>   int proper_divisors(const int n, bool print_flag) { int count = 0;   for (int i = 1; i < n; ++i) { if (n % i == 0) { count++; if (print_flag) printf("%d ", i); } }   if (print_flag) printf("\n"); ...
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...
#C.2B.2B
C++
#include <cstdlib> #include <iostream> #include <vector> #include <utility> #include <algorithm> #include <ctime> #include <iomanip>   int main( ) { typedef std::vector<std::pair<std::string, double> >::const_iterator SPI ; typedef std::vector<std::pair<std::string , double> > ProbType ; ProbType probabilities...
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...
#Julia
Julia
using Primes   function ancestraldecendants(maxsum) aprimes = primes(maxsum) descendants = [Vector{Int}() for _ in 1:maxsum + 1] ancestors = [Vector{Int}() for _ in 1:maxsum + 1] for p in aprimes push!(descendants[p + 1], p) foreach(s -> append!(descendants[s + p], [p * pr for pr in desc...
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...
#Kotlin
Kotlin
// version 1.1.2   const val MAXSUM = 99   fun getPrimes(max: Int): List<Int> { if (max < 2) return emptyList<Int>() val lprimes = mutableListOf(2) outer@ for (x in 3..max step 2) { for (p in lprimes) if (x % p == 0) continue@outer lprimes.add(x) } return lprimes }   fun main(args: A...
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...
#Clojure
Clojure
user=> (use 'clojure.data.priority-map)   ; priority-map can be used as a priority queue user=> (def p (priority-map "Clear drains" 3, "Feed cat" 4, "Make tea" 5, "Solve RC tasks" 1)) #'user/p user=> p {"Solve RC tasks" 1, "Clear drains" 3, "Feed cat" 4, "Make tea" 5}   ; You can use assoc or conj to add items user=> (...
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 ...
#Go
Go
package main   import ( "fmt" "math" )   type circle struct { x, y, r float64 }   func main() { c1 := circle{0, 0, 1} c2 := circle{4, 0, 1} c3 := circle{2, 4, 2} fmt.Println(ap(c1, c2, c3, true)) fmt.Println(ap(c1, c2, c3, false)) }   func ap(c1, c2, c3 circle, s bool) circle { x1sq ...
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...
#newLISP
newLISP
#!/usr/bin/env newlisp   (let ((program (main-args 1))) (println (format "Program: %s" program)) (exit))
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Nim
Nim
import os echo getAppFilename() # Prints the full path of the executed file echo paramStr(0) # Prints argv[0]
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Rust
Rust
  extern crate primal; extern crate rayon; extern crate rug;   use rayon::prelude::*; use rug::Integer;   fn partial(p1 : usize, p2 : usize) -> String { let mut aux = Integer::from(1); let (_, hi) = primal::estimate_nth_prime(p2 as u64); let sieve = primal::Sieve::new(hi as usize); let prime1 = sieve.nt...
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×...
#Scala
Scala
import spire.math.SafeLong import spire.implicits._   import scala.collection.parallel.immutable.ParVector   object Primorial { def main(args: Array[String]): Unit = { println( s"""|First 10 Primorials: |${LazyList.range(0, 10).map(n => f"$n: ${primorial(n).toBigInt}%,d").mkString("\n")} ...
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,...
#Nim
Nim
const u = [[ 1, -2, 2, 2, -1, 2, 2, -2, 3], [ 1, 2, 2, 2, 1, 2, 2, 2, 3], [-1, 2, 2, -2, 1, 2, -2, 2, 3]]   var total, prim = 0 maxPeri = 10   proc newTri(ins: array[0..2, int]) = var p = ins[0] + ins[1] + ins[2] if p > maxPeri: return inc(prim) total += maxPeri div ...
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...
#Logo
Logo
bye  ; exits to shell   throw "toplevel  ; exits to interactive prompt   pause  ; escapes to interactive prompt for debugging continue  ; resumes after a PAUSE
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Lua
Lua
if some_condition then os.exit( number ) end