task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Haskell
Haskell
import Data.List (group, sort) import Text.Printf (printf) import Data.Numbers.Primes (primes)   freq :: [(Int, Int)] -> Float freq xs = realToFrac (length xs) / 100   line :: [(Int, Int)] -> IO () line t@((n1, n2):xs) = printf "%d -> %d count: %5d frequency: %2.2f %%\n" n1 n2 (length t) (freq t)   main :: IO () main ...
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 ...
#ALGOL_68
ALGOL 68
#IF long int possible THEN #   MODE LINT = LONG INT; LINT lmax int = long max int; OP LLENG = (INT i)LINT: LENG i, LSHORTEN = (LINT i)INT: SHORTEN i;   #ELSE   MODE LINT = INT; LINT lmax int = max int; OP LLENG = (INT i)LINT: i, LSHORTEN = (LINT i)INT: i;   FI#   OP LLONG = (INT i)LINT: LLENG i;   MODE YIELDLINT ...
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...
#AutoHotkey
AutoHotkey
If !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp }   OnExit, Exit gdip1()   incr := 0 π := 3.141592653589793 loop { incr := Mod(incr + 0.05, 360) x1 := Width/2 y1 := Height/2 length := 5 angle := incr ...
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 ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program testPrime64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
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 ...
#AppleScript
AppleScript
-- This handler just returns the standardised real value. It's up to external processes to format it for display.   on standardisePrice(input) set integerPart to input div 1.0 set fractionalPart to input mod 1.0   if (fractionalPart is 0.0) then return input as real else if (fractionalPart < 0.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...
#Component_Pascal
Component Pascal
  MODULE RosettaProperDivisor; IMPORT StdLog;   PROCEDURE Pd*(n: LONGINT;OUT r: ARRAY OF LONGINT):LONGINT; VAR i,j: LONGINT; BEGIN i := 1;j := 0; IF n > 1 THEN WHILE (i < n) DO IF (n MOD i) = 0 THEN IF (j < LEN(r)) THEN r[j] := i END; INC(j) END; INC(i) END; END; RETURN j END Pd;   PROCEDURE Do*...
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...
#ERRE
ERRE
PROGRAM PROB_CHOICE   DIM ITEM$[7],PROB[7],CNT[7]   BEGIN ITEM$[]=("aleph","beth","gimel","daleth","he","waw","zayin","heth")   PROB[0]=1/5.0 PROB[1]=1/6.0 PROB[2]=1/7.0 PROB[3]=1/8.0 PROB[4]=1/9.0 PROB[5]=1/10.0 PROB[6]=1/11.0 PROB[7]=1759/27720 SUM=0 FOR I%=0 TO UBOUND(PROB,1) DO SUM=SUM...
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...
#Euphoria
Euphoria
constant MAX = #3FFFFFFF constant times = 1e6 atom d,e sequence Mapps Mapps = { { "aleph", 1/5, 0}, { "beth", 1/6, 0}, { "gimel", 1/7, 0}, { "daleth", 1/8, 0}, { "he", 1/9, 0}, { "waw", 1/10, 0}, { "zayin", 1/11, 0}, { "heth", ...
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...
#Sidef
Sidef
var maxsum = 99 var primes = maxsum.primes   var descendants = (maxsum+1).of { [] } var ancestors = (maxsum+1).of { [] }   for p in (primes) { descendants[p] << p for s in (1 .. descendants.end-p) { descendants[s + p] << descendants[s].map {|q| p*q }... } }   for p in (primes + [4]) { descenda...
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...
#Delphi
Delphi
program Priority_queue;   {$APPTYPE CONSOLE}   uses System.SysUtils, Boost.Generics.Collection;   var Queue: TPriorityQueue<String>;   begin Queue := TPriorityQueue<String>.Create(['Clear drains', 'Feed cat', 'Make tea', 'Solve RC tasks', 'Tax return'], [3, 4, 5, 1, 2]);   while not Queue.IsEmpty do wit...
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 ...
#Julia
Julia
using Printf   module ApolloniusProblems   using Polynomials export Circle   struct Point{T<:Real} x::T y::T end   xcoord(p::Point) = p.x ycoord(p::Point) = p.y   struct Circle{T<:Real} c::Point{T} r::T end Circle(x::T, y::T, r::T) where T<:Real = Circle(Point(x, y), r)   radius(c::Circle) = c.r center(...
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 ...
#Kotlin
Kotlin
// version 1.1.3   data class Circle(val x: Double, val y: Double, val r: Double)   val Double.sq get() = this * this   fun solveApollonius(c1: Circle, c2: Circle, c3: Circle, s1: Int, s2: Int, s3: Int): Circle { val (x1, y1, r1) = c1 val (x2, y2, r2) = c2 val (x3, y3, r3) = c3   va...
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...
#Phixmonti
Phixmonti
argument 1 get ?
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#PHP
PHP
<?php $program = $_SERVER["SCRIPT_NAME"]; echo "Program: $program\n"; ?>
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Phix
Phix
with javascript_semantics atom total, prim, maxPeri = 10 procedure tri(atom s0, s1, s2) atom p = s0 + s1 + s2 if p<=maxPeri then prim += 1 total += floor(maxPeri/p) tri( s0+2*(-s1+s2), 2*( s0+s2)-s1, 2*( s0-s1+s2)+s2); tri( s0+2*( s1+s2), 2*( s0+s2)+s1, 2*( s0+s1+s2)+s2); t...
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...
#Nim
Nim
if problem1: quit QuitFailure   if problem2: quit "There is a problem", QuitFailure
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Oberon-2
Oberon-2
  IF problem THEN HALT(1) END  
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Erlang
Erlang
  #! /usr/bin/escript   isprime(N) when N < 2 -> false; isprime(N) when N band 1 =:= 0 -> N =:= 2; isprime(N) -> fac_mod(N - 1, N) =:= N - 1.   fac_mod(N, M) -> fac_mod(N, M, 1). fac_mod(1, _, A) -> A; fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).   main(_) -> io:format("The first few primes (via Wilson's theor...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#F.23
F#
  // Wilsons theorem. Nigel Galloway: August 11th., 2020 let wP(n,g)=(n+1I)%g=0I let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n" fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#J
J
/:~ (~.,. ' ',. ":@(%/&1 999999)@(#/.~)) 2 (,'->',])&":/\ 10|p:i.1e6 1->1 42853 0.042853 1->3 77475 0.0774751 1->7 79453 0.0794531 1->9 50153 0.0501531 2->3 1 1e_6 3->1 58255 0.0582551 3->3 39668 0.039668 3->5 1 1e_6 3->7 72827 0.0728271 3->9 79358 0.0793581 5->7 1 1e_6 7->1 64230 0.0642...
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 ...
#Java
Java
public class PrimeConspiracy {   public static void main(String[] args) { final int limit = 1000_000; final int sieveLimit = 15_500_000;   int[][] buckets = new int[10][10]; int prevDigit = 2; boolean[] notPrime = sieve(sieveLimit);   for (int n = 3, primeCount = 1; p...
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#ALGOL-M
ALGOL-M
  BEGIN   INTEGER I, K, NFOUND; INTEGER ARRAY FACTORS[1:16];   COMMENT COMPUTE P MOD Q; INTEGER FUNCTION MOD (P, Q); INTEGER P, Q; BEGIN MOD := P - Q * (P / Q); END;   COMMENT FIND THE PRIME FACTORS OF N AND STORE IN THE EXTERNAL ARRAY "FACTORS", RETURNING THE NUMBER FOUND. IF N IS PRIME, IT WILL BE STORED A...
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...
#C
C
  #include<graphics.h> #include<math.h>   #define factor M_PI/180 #define LAG 1000   void polySpiral(int windowWidth,int windowHeight){ int incr = 0, angle, i, length; double x,y,x1,y1;   while(1){ incr = (incr + 5)%360;   x = windowWidth/2; y = windowHeight/2;   length = 5; angle = incr;   for(i=1;i<=1...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#11l
11l
F list_powerset(lst) V result = [[Int]()] L(x) lst result.extend(result.map(subset -> subset [+] [@x])) R result   print(list_powerset([1, 2, 3]))
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#ABAP
ABAP
class ZMLA_ROSETTA definition public create public .   public section.   types: enumber TYPE N LENGTH 60 . types: listof_enumber TYPE TABLE OF enumber .   class-methods IS_PRIME importing value(N) type ENUMBER returning value(OFLAG) type ABAP_BOOL . class-metho...
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 ...
#Arturo
Arturo
pricePoints: [ 0.06 0.10 0.11 0.18 0.16 0.26 0.21 0.32 0.26 0.38 0.31 0.44 0.36 0.50 0.41 0.54 0.46 0.58 0.51 0.62 0.56 0.66 0.61 0.70 0.66 0.74 0.71 0.78 0.76 0.82 0.81 0.86 0.86 0.90 0.91 0.94 0.96 0.98 1.01 ...
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...
#D
D
void main() /*@safe*/ { import std.stdio, std.algorithm, std.range, std.typecons;   immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ => iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x);   iota(1, 11).map!properDivs.writeln; iota(1, 20_001).map!(n => tuple(properDivs(n)....
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...
#Factor
Factor
USING: arrays assocs combinators.random io kernel macros math math.statistics prettyprint quotations sequences sorting formatting ; IN: rosettacode.proba   CONSTANT: data { { "aleph" 1/5.0 } { "beth" 1/6.0 } { "gimel" 1/7.0 } { "daleth" 1/8.0 } { "he" 1/9.0 } { "waw" 1/10.0 } ...
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...
#Fermat
Fermat
  trials:=1000000;   Array probs[8]; {store the probabilities} [probs]:=[<i=1,8> 1/(i+4)]; probs[8]:=1-Sigma<i=1,7>[probs[i,1]];   Func Round( a, b ) = (2*a+b)\(2*b).; {rounds a fraction with numerator a and denominator b}  ; {to the nearest integer (posit...
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...
#Simula
Simula
COMMENT cim --memory-pool-size=512 allocate-descendants-to-their-ancestors.sim ; BEGIN     COMMENT ABSTRACT FRAMEWORK CLASSES ;   CLASS ITEM; BEGIN END ITEM;   CLASS ITEMLIST; BEGIN   CLASS ITEMARRAY(N); INTEGER N; BEGIN REF(ITEM) ARRAY DATA(0:N-1); END ITEMARRAY;   ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Math   Module Module1 Const MAXPRIME = 99 ' upper bound for the prime factors Const MAXPARENT = 99 ' greatest parent number   Const NBRCHILDREN = 547100 ' max number of children (total descendants)   Public Primes...
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...
#EchoLisp
EchoLisp
  (lib 'tree) (define tasks (make-bin-tree 3 "Clear drains")) (bin-tree-insert tasks 2 "Tax return") (bin-tree-insert tasks 5 "Make tea") (bin-tree-insert tasks 1 "Solve RC tasks") (bin-tree-insert tasks 4 "Feed 🐡")   (bin-tree-pop-first tasks) → (1 . "Solve RC tasks") (bin-tree-pop-first tasks) → (2 . "Tax return") (...
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 ...
#Lasso
Lasso
define solveApollonius(c1, c2, c3, s1, s2, s3) => { local( x1 = decimal(#c1->get(1)), y1 = decimal(#c1->get(2)), r1 = decimal(#c1->get(3)) ) local( x2 = decimal(#c2->get(1)), y2 = decimal(#c2->get(2)), r2 = decimal(#c2->get(3)) ) local( x3 = decimal(#c3->get(1)), y3 = decimal(#c3->get(2)), ...
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 ...
#Liberty_BASIC
Liberty BASIC
  circle1$ =" 0.000, 0.000, 1.000" circle2$ =" 4.000, 0.000, 1.000" circle3$ =" 2.000, 4.000, 2.000"   print " x_pos y_pos radius" print circle1$ print circle2$ print circle3$ print print ApolloniusSolver$( circle1$, circle2$, circle3$, 1, 1, 1) print ApolloniusSolver$( circle1$, ci...
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...
#PicoLisp
PicoLisp
: (cmd) -> "/usr/bin/picolisp"
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#PowerBASIC
PowerBASIC
#INCLUDE "Win32API.inc" '[...] DIM fullpath AS ASCIIZ * 260, appname AS STRING GetModuleFileNameA 0, fullpath, 260 IF INSTR(fullpath, "\") THEN appname = MID$(fullpath, INSTR(-1, fullpath, "\") + 1) ELSE appname = fullpath END IF
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#PHP
PHP
<?php   function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); }   $pytha = 0; $prim = 0; $max_p = 100;   for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($...
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...
#Objeck
Objeck
if(problem) { Runtime->Exit(1); };
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#OCaml
OCaml
if problem then exit integerErrorCode; (* conventionally, error code 0 is the code for "OK", while anything else is an actual problem *)
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Factor
Factor
USING: formatting grouping io kernel lists lists.lazy math math.factorials math.functions prettyprint sequences ;   : wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ; : prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ; : primes ( -- list ) 1 lfrom [ prime? ] lfilter ;   "n prime?\n--- -----" print { 2 3...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Fermat
Fermat
Func Wilson(n) = if ((n-1)!+1)|n = 0 then 1 else 0 fi.;
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Julia
Julia
using Printf, Primes using DataStructures   function counttransitions(upto::Integer) cnt = counter(Pair{Int,Int}) tot = 0 prv, nxt = 2, 3 while nxt ≤ upto push!(cnt, prv % 10 => nxt % 10) prv = nxt nxt = nextprime(nxt + 1) tot += 1 end return sort(Dict(cnt)), tot ...
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 ...
#Kotlin
Kotlin
// version 1.1.2 // compiled with flag -Xcoroutines=enable to suppress 'experimental' warning   import kotlin.coroutines.experimental.*   typealias Transition = Pair<Int, Int>   fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d : In...
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 ...
#Applesoft_BASIC
Applesoft BASIC
9040 PF(0) = 0 : SC = 0 9050 FOR CA = 2 TO INT( SQR(I)) 9060 IF I = 1 THEN RETURN 9070 IF INT(I / CA) * CA = I THEN GOSUB 9200 : GOTO 9060 9080 CA = CA + SC : SC = 1 9090 NEXT CA 9100 IF I = 1 THEN RETURN 9110 CA = I   9200 PF(0) = PF(0) + 1 9210 PF(PF(0)) = CA 9220 I = I / CA 9230 RETURN
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading;   namespace Polyspiral { public partial class Form1 : Form { private double inc;   public Form1() { Width = Height = 640; StartPosition ...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#ABAP
ABAP
  report z_powerset.   interface set. methods: add_element importing element_to_be_added type any returning value(new_set) type ref to set,   remove_element importing element_to_be_removed type any returning value(new_set) type ref to set,   ...
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 ...
#ACL2
ACL2
(defun is-prime-r (x i) (declare (xargs :measure (nfix (- x i)))) (if (zp (- (- x i) 1)) t (and (/= (mod x i) 0) (is-prime-r x (1+ i)))))   (defun is-prime (x) (or (= x 2) (is-prime-r x 2)))
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#AutoHotkey
AutoHotkey
; Submitted by MasterFocus --- http://tiny.cc/iTunis   Loop { InputBox, OutputVar, Price Fraction Example, Insert the value to be rounded.`n* [ 0 < value < 1 ]`n* Press ESC or Cancel to exit, , 200, 150 If ErrorLevel Break MsgBox % "Input: " OutputVar "`nResult: " PriceFraction( OutputVar ) }   ;-------------...
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...
#Delphi
Delphi
  program ProperDivisors;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, System.Generics.Collections;   type TProperDivisors = TArray<Integer>;   function GetProperDivisors(const value: Integer): TProperDivisors; var i, count: Integer; begin count := 0;   for i := 1 to value div 2 do begin ...
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...
#Forth
Forth
include random.fs   \ common factors of desired probabilities (1/5 .. 1/11) 2 2 * 2 * 3 * 3 * 5 * 7 * 11 * constant denom \ 27720   \ represent each probability as the numerator with 27720 as the denominator : ,numerators ( max min -- ) do denom i / , loop ;   \ final item is 27720 - sum(probs) : ,remainder ( deno...
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...
#Wren
Wren
import "/math" for Int import "/sort" for Sort import "/fmt" for Fmt   var maxSum = 99   var descendants = List.filled(maxSum + 1, null) var ancestors = List.filled(maxSum + 1, null) for (i in 0..maxSum) { descendants[i] = [] ancestors[i] = [] } var primes = Int.primeSieve(maxSum) for (p in primes) { de...
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...
#Elixir
Elixir
defmodule Priority do def create, do: :gb_trees.empty   def insert( element, priority, queue ), do: :gb_trees.enter( priority, element, queue )   def peek( queue ) do {_priority, element, _new_queue} = :gb_trees.take_smallest( queue ) element end   def task do items = [{3, "Clear drains"}, {4, "Fe...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Apolonius[a1_,b1_,c1_,a2_,b2_,c2_,a3_,b3_,c3_,S1_,S2_ ,S3_ ]:= Module[{x1=a1,y1=b1,r1=c1,x2=a2,y2=b2,r2=c2,x3=a3,y3=b3,r3=c3,s1=S1,s2=S2,s3=S3}, v11 = 2*x2 - 2*x1; v12 = 2*y2 - 2*y1; v13 = x1^2 - x2^2 + y1^2 - y2^2 - r1^2 + r2^2; v14 = 2*s2*r2 - 2*s1*r1;   v21 = 2*x3-2*x2 ; v22 = 2*y3 - 2*y2; v23 = x2^2 - x3^2 + y2^2 -...
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 ...
#MUMPS
MUMPS
APOLLONIUS(CIR1,CIR2,CIR3,S1,S2,S3)  ;Circles are passed in as strings with three parts with a "^" separator in the order x^y^r  ;The three circles are CIR1, CIR2, and CIR3  ;The S1, S2, and S3 parameters determine if the solution will be internally or externally  ;tangent to the circle. (+1 external, -1 internal)  ;CI...
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...
#PowerShell
PowerShell
  # write this in file <program.ps1> $MyInvocation.MyCommand.Name # launch with <.\program>  
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Prolog
Prolog
% SWI-Prolog version 8.0.0 for i686-linux. % This will find itself, and return the knowledge base it is in. file_name(F) :- true , M = user % M is the module . , P = file_name(_) % P is the predicate . , source_file(M:P, F) % F is the file . , \+ predicate_property(M:P, imported_from(_...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Picat
Picat
main :- garbage_collect(300_000_000), Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000], member(Max, Data), count_triples(Max, Total, Prim), printf("upto %d, there are %d Pythagorean triples (%d primitive.)%n", Max, Total, Prim), fail, nl.   count_triples(Max, Total, Prims) :- Ps ...
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...
#Oforth
Oforth
import: os   some_condition ifTrue: [ 0 OS.exit ]
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Ol
Ol
  (shutdown 0) ; it can be any exit code instead of provided 0  
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Forth
Forth
  : fac-mod ( n m -- r ) >r 1 swap begin dup 0> while dup rot * r@ mod swap 1- repeat drop rdrop ;   : ?prime ( n -- f ) dup 1- tuck swap fac-mod = ;   : .primes ( n -- ) cr 2 ?do i ?prime if i . then loop ;  
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#FreeBASIC
FreeBASIC
function wilson_prime( n as uinteger ) as boolean dim as uinteger fct=1, i for i = 2 to n-1 'because (a mod n)*b = (ab mod n) 'it is not necessary to calculate the entire factorial fct = (fct * i) mod n next i if fct = n-1 then return true else return false end function   for i...
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 ...
#Lua
Lua
-- Return boolean indicating whether or not n is prime function isPrime (n) if n <= 1 then return false end if n <= 3 then return true end if n % 2 == 0 or n % 3 == 0 then return false end local i = 5 while i * i <= n do if n % i == 0 or n % (i + 2) == 0 then return false end i = i +...
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 ...
#Arturo
Arturo
decompose: function [num][ facts: to [:string] factors.prime num print [ pad.right (to :string num) ++ " = " ++ join.with:" x " facts 30 "{"++ (join.with:", " unique facts) ++ "}" ] ]   loop 2..40 => decompose
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#C.2B.2B
C++
  #include <windows.h> #include <sstream> #include <ctime>   const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s ...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#11l
11l
F average(arr) R sum(arr) / Float(arr.len)   F poly_regression(x, y) V xm = average(x) V ym = average(y) V x2m = average(x.map(i -> i * i)) V x3m = average(x.map(i -> i ^ 3)) V x4m = average(x.map(i -> i ^ 4)) V xym = average(zip(x, y).map((i, j) -> i * j)) V x2ym = average(zip(x, y).map((i, j)...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Ada
Ada
  with Ada.Text_IO, Ada.Command_Line; use Ada.Text_IO, Ada.Command_Line;   procedure powerset is begin for set in 0..2**Argument_Count-1 loop Put ("{"); declare k : natural := set; first : boolean := true; begin for i in 1..Argument_Count loop if k mod 2 = 1 then Put ((if first then "" else ...
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 ...
#Action.21
Action!
BYTE FUNC IsPrime(CARD a) CARD i   IF a<=1 THEN RETURN (0) FI   FOR i=2 TO a/2 DO IF a MOD i=0 THEN RETURN (0) FI OD RETURN (1)   PROC Test(CARD a) IF IsPrime(a) THEN PrintF("%I is prime%E",a) ELSE PrintF("%I is not prime%E",a) FI RETURN   PROC Main() Test(13) Test(997) ...
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 ...
#AWK
AWK
  BEGIN { O = ".06 .11 .16 .21 .26 .31 .36 .41 .46 .51 .56 .61 .66 .71 .76 .81 .86 .91 .96 1.01" N = ".10 .18 .26 .32 .38 .44 .50 .54 .58 .62 .66 .70 .74 .78 .82 .86 .90 .94 .98 1.00" fields = split(O,Oarr," ") # original values split(N,Narr," ") # replacement values for (i=-.01; i<=1.02; i+=.01) { ...
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...
#Dyalect
Dyalect
func properDivs(n) { if n == 1 { yield break } for x in 1..<n { if n % x == 0 { yield x } } }   for i in 1..10 { print("\(i): \(properDivs(i).ToArray())") }   var (num, max) = (0,0)   for i in 1..20000 { let count = properDivs(i).Length() if count > max { ...
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...
#Fortran
Fortran
PROGRAM PROBS   IMPLICIT NONE   INTEGER, PARAMETER :: trials = 1000000 INTEGER :: i, j, probcount(8) = 0 REAL :: expected(8), mapping(8), rnum CHARACTER(6) :: items(8) = (/ "aleph ", "beth ", "gimel ", "daleth", "he ", "waw ", "zayin ", "heth " /)   expected(1:7) = (/ (1.0/i, i=5,11) /) expected(8)...
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...
#zkl
zkl
const maxsum=99;   primes:=Utils.Generator(Import("sieve.zkl").postponed_sieve) .pump(List,'wrap(p){ (p<=maxsum) and p or Void.Stop });   descendants,ancestors:=List()*(maxsum + 1), List()*(maxsum + 1);   foreach p in (primes){ descendants[p].insert(0,p); foreach s in ([1..descendants.len() - p - 1]){ ...
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...
#Erlang
Erlang
  -module( priority_queue ).   -export( [create/0, insert/3, peek/1, task/0, top/1] ).   create() -> gb_trees:empty().   insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).   peek( Queue ) -> {_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ), Element.   task() -> Ite...
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 ...
#Nim
Nim
import math   type Circle = tuple[x, y, r: float]   proc solveApollonius(c1, c2, c3: Circle; s1, s2, s3: float): Circle = let v11 = 2*c2.x - 2*c1.x v12 = 2*c2.y - 2*c1.y v13 = c1.x*c1.x - c2.x*c2.x + c1.y*c1.y - c2.y*c2.y - c1.r*c1.r + c2.r*c2.r v14 = 2*s2*c2.r - 2*s1*c1.r   v21 = 2*c3.x - 2*c2.x ...
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...
#PureBasic
PureBasic
If OpenConsole() PrintN(ProgramFilename())   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Python
Python
#!/usr/bin/env python   import sys   def main(): program = sys.argv[0] print("Program: %s" % program)   if __name__ == "__main__": main()
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#PicoLisp
PicoLisp
(for (Max 10 (>= 100000000 Max) (* Max 10)) (let (Total 0 Prim 0 In (3 4 5)) (recur (In) (let P (apply + In) (when (>= Max P) (inc 'Prim) (inc 'Total (/ Max P)) (for Row (quote (( 1 -2 2) ( 2 -1 2) ( 2 ...
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...
#Oz
Oz
if Problem then {Application.exit 0} end
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#PARI.2FGP
PARI/GP
if(stuff, quit)
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#F.C5.8Drmul.C3.A6
Fōrmulæ
# find primes using Wilson's theorem: # p is prime if ( ( p - 1 )! + 1 ) mod p = 0   isWilsonPrime := function( p ) local fModP, i; fModP := 1; for i in [ 2 .. p - 1 ] do fModP := fModP * i; fModP := fModP mod p; od; return fModP = p - 1; end; # isWilsonPrime   prime := []; for i in [ -4 .. 100 ] do ...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#GAP
GAP
# find primes using Wilson's theorem: # p is prime if ( ( p - 1 )! + 1 ) mod p = 0   isWilsonPrime := function( p ) local fModP, i; fModP := 1; for i in [ 2 .. p - 1 ] do fModP := fModP * i; fModP := fModP mod p; od; return fModP = p - 1; end; # isWilsonPrime   prime := []; for i in [ -4 .. 100 ] do ...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
  StringForm["`` count: `` frequency: ``", Rule@@ #[[1]], StringPadLeft[ToString@ #[[2]], 8], PercentForm[N@ #[[2]]/(10^8 -1)]]& /@ Sort[Tally[Partition[Mod[Prime[Range[10^8]], 10], 2, 1]]] // Column  
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Nim
Nim
  # Prime conspiracy.   from algorithm import sorted from math import sqrt from sequtils import toSeq from strformat import fmt import tables   const N = 1_020_000_000.int # Size of sieve of Eratosthenes.   proc newSieve(): seq[bool] = ## Create a sieve with only odd values. ## Index "i" in sieve represents val...
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 ...
#AutoHotkey
AutoHotkey
MsgBox % factor(8388607) ; 47 * 178481   factor(n) { if (n = 1) return f = 2 while (f <= n) { if (Mod(n, f) = 0) { next := factor(n / f) return, % f "`n" next } f++ } }
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#Ceylon
Ceylon
import javafx.application { Application } import javafx.stage { Stage } import javafx.animation { AnimationTimer } import ceylon.numeric.float { remainder, cos, sin, toRadians } import javafx.scene.layout { BorderPane } import javafx.scene.canvas { Canvas } import javafx.scene { ...
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...
#FreeBASIC
FreeBASIC
#include "fbgfx.bi" #if __FB_LANG__ = "fb" Using FB '' Scan code constants are stored in the FB namespace in lang FB #endif #define pi 4 * Atn(1) #define Deg2Rad pi/180   Dim As Integer w = 900, h = w Screenres w, h, 8 Windowtitle "Polyspiral"   Dim As Integer incr = 0, angulo, longitud, x1, y1, x2, y2, N Do ...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#Ada
Ada
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;   function Fit (X, Y : Real_Vector; N : Positive) return Real_Vector is A : Real_Matrix (0..N, X'Range); -- The plane begin for I in A'Range (2) loop for J in A'Range (1) loop A (J, I) := X (I)**J; end loop; end loop; return...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#ALGOL_68
ALGOL 68
MODE MEMBER = INT;   PROC power set = ([]MEMBER s)[][]MEMBER:( [2**UPB s]FLEX[1:0]MEMBER r; INT upb r := 0; r[upb r +:= 1] := []MEMBER(()); FOR i TO UPB s DO MEMBER e = s[i]; FOR j TO upb r DO [UPB r[j] + 1]MEMBER x; x[:UPB x-1] := r[j]; x[UPB x] := e; # append to the end of x # ...
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 ...
#ActionScript
ActionScript
function isPrime(n:int):Boolean { if(n < 2) return false; if(n == 2) return true; if((n & 1) == 0) return false; for(var i:int = 3; i <= Math.sqrt(n); i+= 2) if(n % i == 0) return false; return true; }
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#BASIC
BASIC
DECLARE FUNCTION PriceFraction! (price AS SINGLE)   RANDOMIZE TIMER DIM x AS SINGLE x = RND PRINT x, PriceFraction(x)   FUNCTION PriceFraction! (price AS SINGLE) 'returns price unchanged if invalid value SELECT CASE price CASE IS < 0! PriceFraction! = price CASE IS < .06 ...
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...
#EchoLisp
EchoLisp
  (lib 'list) ;; list-delete   ;; let n = product p_i^a_i , p_i prime ;; number of divisors = product (a_i + 1) - 1 (define (numdivs n) (1- (apply * (map (lambda(g) (1+ (length g))) (group (prime-factors n))))))   (remember 'numdivs)   ;; prime powers ;; input : a list g of grouped prime factors ( 3 3 3 ..) ;; retu...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim letters (0 To 7) As String = {"aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"} Dim actual (0 To 7) As Integer '' all zero by default Dim probs (0 To 7) As Double = {1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0} Dim cumProbs (0 To 7) As Double   cumProbs(0) = probs(0) ...
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...
#F.23
F#
[<RequireQualifiedAccess>] module PriorityQ =   // type 'a treeElement = Element of uint32 * 'a type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end   type 'a tree = Node of uint32 * 'a treeElement * 'a tree list   type 'a heap = 'a tree list   [<CompilationRepresentation(CompilationRe...
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 ...
#OCaml
OCaml
type point = { x:float; y:float } type circle = { center: point; radius: float; }   let new_circle ~x ~y ~r = { center = { x=x; y=y }; radius = r }   let print_circle ~c = Printf.printf "Circle(x=%.2f, y=%.2f, r=%.2f)\n" c.center.x c.center.y c.radius   let defxyr c = (c.center.x, c.center.y, c....
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...
#R
R
#!/usr/bin/env Rscript   getProgram <- function(args) { sub("--file=", "", args[grep("--file=", args)]) }   args <- commandArgs(trailingOnly = FALSE) program <- getProgram(args)   cat("Program: ", program, "\n")   q("no")
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#PL.2FI
PL/I
*process source attributes xref or(!); /********************************************************************* * REXX pgm counts number of Pythagorean triples * that exist given a max perimeter of N, * and also counts how many of them are primatives. * 05.05.2013 Walter Pachl translated from REXX version 2 ****...
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...
#Pascal
Pascal
if true then begin halt end
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Perl
Perl
if ($problem) { exit integerErrorCode; # conventionally, error code 0 is the code for "OK" # (you can also omit the argument in this case) # while anything else is an actual problem }
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Go
Go
package main   import ( "fmt" "math/big" )   var ( zero = big.NewInt(0) one = big.NewInt(1) prev = big.NewInt(factorial(20)) )   // Only usable for n <= 20. func factorial(n int64) int64 { res := int64(1) for k := n; k > 1; k-- { res *= k } return res }   // If memo == true,...
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 ...
#PARI.2FGP
PARI/GP
  conspiracy(maxx)={ print("primes considered= ",maxx); x=matrix(9,9);cnt=0;p=2;q=2%10; while(cnt<=maxx, cnt+=1; m=q; p=nextprime(p+1); q= p%10; x[m,q]+=1); print (2," to ",3, " count: ",x[2,3]," freq ", 100./cnt,"  %" ); forstep(i=1,9,2, forstep(j=1,9,2, if( x[i,j]<1,continue); print (i," to ",j, " count: ",x[i,j],...
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 ...
#AWK
AWK
# Usage: awk -f primefac.awk function pfac(n, r, f){ r = ""; f = 2 while (f <= n) { while(!(n % f)) { n = n / f r = r " " f } f = f + 2 - (f == 2) } return r }   # For each line of input, print the prime factors. { print pfac($1) }