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/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
#PL.2FI
PL/I
/* primality by Wilson's theorem */ wilson: procedure options( main ); declare n binary(15)fixed;   isWilsonPrime: procedure( n )returns( bit(1) ); declare n binary(15)fixed; declare ( fmodp, i ) binary(15)fixed; fmodp = 1; do i = 2 to n - 1; fmodp = mod( fmodp * i, n )...
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Racket
Racket
#lang racket   (require math/number-theory)   (define limit 1000000)   (define table (for/fold ([table (hash)] [prev 2] #:result table) ([p (in-list (next-primes 2 (sub1 limit)))]) (define p-mod (modulo p 10)) (values (hash-update table (cons prev p-mod) add1 0) p-mod)))   (define (pair<? p q) (or...
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 ...
#Raku
Raku
use Math::Primesieve;   my %conspiracy; my $upto = 1_000_000; my $sieve = Math::Primesieve.new; my @primes = $sieve.n-primes($upto+1);   @primes[^($upto+1)].reduce: -> $a, $b { my $d = $b % 10; %conspiracy{"$a → $d count:"}++; $d; }   say "$_ \tfrequency: {($_.value/$upto*100).round(.01)} %" for %conspiracy...
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 ...
#Clojure
Clojure
;;; No stack consuming algorithm (defn factors "Return a list of factors of N." ([n] (factors n 2 ())) ([n k acc] (if (= 1 n) acc (if (= 0 (rem n k)) (recur (quot n k) k (cons k acc)) (recur n (inc k) acc)))))
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.2B.2B
C++
int* pointer2(&var);
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#COBOL
COBOL
01 ptr USAGE POINTER TO Some-Type. 01 prog-ptr USAGE PROGRAM-POINTER "some-program". *> TO is optional
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Common_Lisp
Common Lisp
void main() { // Take the address of 'var' and placing it in a pointer: int var; int* ptr = &var;   // Take the pointer to the first item of an array: int[10] data; auto p2 = data.ptr;     // Depending on variable type, D will automatically pass either // by value or reference. // By...
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#ALGOL_68
ALGOL 68
#!/usr/bin/algol68g-full --script # # -*- coding: utf-8 -*- #   PR READ "prelude/errata.a68" PR; PR READ "prelude/exception.a68" PR; PR READ "prelude/math_lib.a68" PR;   CO REQUIRED BY "prelude/graph_2d.a68" CO MODE GREAL= REAL; # single precision # FORMAT greal repr = $g(-3,0)$; PR READ "prelude/graph_2d.a68" PR; ...
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#BASIC
BASIC
INSTALL @lib$ + "CLASSLIB"   REM Create parent class with void 'doprint' method: DIM PrintableShape{doprint} PROC_class(PrintableShape{})   REM Create derived class for Point: DIM Point{x#, y#, setxy, retx, rety, @constructor, @@destructor} PROC_inherit(Point{}, PrintableShape{...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#C.23
C#
using System; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class PokerHandAnalyzer { private enum Hand { Invalid, High_Card, One_Pair, Two_Pair, Three_Of_A_Kind, Straight, Flush, Full_House, Four_Of_A_Kind, Straight_Flush, Five_Of_A_Kind }   private ...
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#AppleScript
AppleScript
--------------------- POPULATION COUNT ---------------------   -- populationCount :: Int -> Int on populationCount(n) -- The number of non-zero bits in the binary -- representation of the integer n.   script go on |λ|(x) if 0 < x then Just({x mod 2, x div 2}) ...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Common_Lisp
Common Lisp
(defun add (p1 p2) (do ((sum '())) ((and (endp p1) (endp p2)) (nreverse sum)) (let ((pd1 (if (endp p1) -1 (caar p1))) (pd2 (if (endp p2) -1 (caar p2)))) (multiple-value-bind (c1 c2) (cond ((> pd1 pd2) (values (cdr (pop p1)) 0)) ((< pd1 pd2) (values 0 (cdr (pop p2)))...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Elena
Elena
import extensions;   class T { Name = "T";   T clone() = new T(); }   class S : T { Name = "S";   T clone() = new S(); }   public program() { T original := new S(); T clone := original.clone();   console.printLine(original.Name); console.printLine(clone.Name) }
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#F.23
F#
type T() = // expose protected MemberwiseClone method (and downcast the result) member x.Clone() = x.MemberwiseClone() :?> T // virtual method Print with default implementation abstract Print : unit -> unit default x.Print() = printfn "I'm a T!"   type S() = inherit T() override x.Print() = printfn "I'm a...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Factor
Factor
USING: classes kernel prettyprint serialize ; TUPLE: A ; TUPLE: C < A ; : serial-clone ( obj -- obj' ) object>bytes bytes>object ;   C new [ clone ] [ serial-clone ] bi [ class . ] bi@
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...
#Nim
Nim
# Pendulum simulation.   import math, random   import gintro/[gobject, gdk, gtk, gio, glib, cairo]   const Width = 500 Height = 500 DrawIters = 72 Red = [float 1, 0, 0] Green = [float 0, 1, 0] Blue = [float 0, 0, 1] Black = [float 0, 0, 0] White = [float 255, 255, 255] Gold = [float 255, 215, 0] Col...
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...
#PARI.2FGP
PARI/GP
  \\ Plot the line from x1,y1 to x2,y2. plotline(x1,y1,x2,y2,w=0)={plotmove(w, x1,y1);plotrline(w,x2-x1,y2-y1);} \\ Convert degrees to radians. rad2(degs)={return(degs*Pi/180.0)} \\ Convert Polar coordinates to Cartesian. cartes2(r,a,rndf=0)={my(v,x,y); x=r*cos(a); y=r*sin(a); if(rndf==0, return([x,y]), return(round(...
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...
#D
D
import std.algorithm; import std.range; import std.stdio;   auto average(R)(R r) { auto t = r.fold!("a+b", "a+1")(0, 0); return cast(double) t[0] / t[1]; }   void polyRegression(int[] x, int[] y) { auto n = x.length; auto r = iota(0, n).array; auto xm = x.average(); auto ym = y.average(); au...
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...
#Bracmat
Bracmat
( ( powerset = done todo first .  !arg:(?done.?todo) & (  !todo:%?first ?todo & (powerset$(!done !first.!todo),powerset$(!done.!todo)) | !done ) ) & out$(powerset$(.1 2 3 4)) );
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...
#Burlesque
Burlesque
  blsq ) {1 2 3 4}R@ {{} {1} {2} {1 2} {3} {1 3} {2 3} {1 2 3} {4} {1 4} {2 4} {1 2 4} {3 4} {1 3 4} {2 3 4} {1 2 3 4}}  
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 ...
#AWK
AWK
$ awk 'func prime(n){for(d=2;d<=sqrt(n);d++)if(!(n%d)){return 0};return 1}{print prime($1)}'
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 ...
#D
D
import std.stdio, std.range;   double priceRounder(in double price) pure nothrow in { assert(price >= 0 && price <= 1.0); } body { static immutable cin = [.06, .11, .16, .21, .26, .31, .36, .41, .46, .51, .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.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...
#FreeBASIC
FreeBASIC
  ' FreeBASIC v1.05.0 win64   Sub ListProperDivisors(limit As Integer) If limit < 1 Then Return For i As Integer = 1 To limit Print Using "##"; i; Print " ->"; If i = 1 Then Print " (None)" Continue For End if For j As Integer = 1 To i \ 2 If i Mod j = 0 Then Print " ...
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...
#Liberty_BASIC
Liberty BASIC
  names$="aleph beth gimel daleth he waw zayin heth" dim sum(8) dim counter(8)   s = 0 for i = 1 to 7 s = s+1/(i+4) sum(i)=s next   N =1000000 ' number of throws   for i =1 to N rand =rnd( 1) for j = 1 to 7 if sum(j)> rand then exit for next counter(j)=counter(j)+1 next   print "Obs...
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...
#J
J
coclass 'priorityQueue'   PRI=: '' QUE=: ''   insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 )   topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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 ...
#Scala
Scala
object ApolloniusSolver extends App { case class Circle(x: Double, y: Double, r: Double) object Tangent extends Enumeration { type Tangent = Value val intern = Value(-1) val extern = Value(1) }   import Tangent._ import scala.Math._   val solveApollonius: (Circle, Circle, Circle, Triple[Tangent, Tangent,...
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...
#UNIX_Shell
UNIX Shell
#!/bin/sh   echo "Program: $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...
#Vala
Vala
  public static void main(string[] args){ string command_name = args[0];   stdout.printf("%s\n", command_name); }  
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,...
#Ruby
Ruby
class PythagoranTriplesCounter def initialize(limit) @limit = limit @total = 0 @primitives = 0 generate_triples(3, 4, 5) end attr_reader :total, :primitives   private def generate_triples(a, b, c) perim = a + b + c return if perim > @limit   @primitives += 1 @total += @limit / ...
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...
#Retro
Retro
problem? [ bye ] if
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...
#REXX
REXX
/*REXX program showing five ways to perform a REXX program termination. */   /*─────1st way────────────────────────────────────────────────────────*/ exit     /*─────2nd way────────────────────────────────────────────────────────*/ exit (expression) /*Note: the "expression" doesn't need parentheses*/ ...
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
#PL.2FM
PL/M
100H: /* FIND PRIMES USING WILSON'S THEOREM: */ /* P IS PRIME IF ( ( P - 1 )! + 1 ) MOD P = 0 */   DECLARE FALSE LITERALLY '0';   BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */ DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END BDOS; P...
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 ...
#REXX
REXX
/*REXX pgm shows a table of what last digit follows the previous last digit for N primes*/ parse arg N . /*N: the number of primes to be genned*/ if N=='' | N=="," then N= 1000000 /*Not specified? Then use the default.*/ Np= N+1; w= length(N-1) ...
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 ...
#Commodore_BASIC
Commodore BASIC
9000 REM ----- function generate 9010 REM in ... i ... number 9020 REM out ... pf() ... factors 9030 REM mod ... ca ... pf candidate 9040 pf(0)=0 : ca=2 : REM special case 9050 IF i=1 THEN RETURN 9060 IF INT(i/ca)*ca=i THEN GOSUB 9200 : GOTO 9050 9070 FOR ca=3 TO INT( SQR(i)) STEP 2 9080 IF i=1 THEN RETURN 9090 IF INT(...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#D
D
void main() { // Take the address of 'var' and placing it in a pointer: int var; int* ptr = &var;   // Take the pointer to the first item of an array: int[10] data; auto p2 = data.ptr;     // Depending on variable type, D will automatically pass either // by value or reference. // By...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Delphi
Delphi
pMyPointer : Pointer ;
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#AutoHotkey
AutoHotkey
#SingleInstance, Force #NoEnv SetBatchLines, -1 OnExit, Exit FileOut := A_Desktop "\MyNewFile.png" Font := "Arial" x := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y := [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] ; Uncomment if Gdip.ahk is not in your standard library ; #Include, Gdip.ahk if (!pToken := Gdip_Star...
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#BBC_BASIC
BBC BASIC
INSTALL @lib$ + "CLASSLIB"   REM Create parent class with void 'doprint' method: DIM PrintableShape{doprint} PROC_class(PrintableShape{})   REM Create derived class for Point: DIM Point{x#, y#, setxy, retx, rety, @constructor, @@destructor} PROC_inherit(Point{}, PrintableShape{...
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#C
C
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { Sy...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#C.2B.2B
C++
  #include <iostream> #include <sstream> #include <algorithm> #include <vector>   using namespace std;   class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end...
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Arturo
Arturo
popCount: function [num][ size select split to :string as.binary num 'x -> x="1" ]   print "population count for the first thirty powers of 3:" print map 0..29 => [popCount 3^&]   print "first thirty evil numbers" print take select 0..100 => [even? popCount &] 30   print "first thirty odious numbers" print take sel...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#D
D
import std.stdio, std.range, std.algorithm, std.typecons, std.conv;   Tuple!(double[], double[]) polyDiv(in double[] inN, in double[] inD) nothrow pure @safe { // Code smell: a function that does two things. static int trimAndDegree(T)(ref T[] poly) nothrow pure @safe @nogc { poly = poly.retro.find!q{ a...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Forth
Forth
include lib/memcell.4th include 4pp/lib/foos.4pp ( a1 -- a2) :token fork dup allocated dup (~~alloc) swap >r swap over r> smove ; \ allocate an empty object :: T() \ super class T class method: print ...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Fortran
Fortran
  !----------------------------------------------------------------------- !Module polymorphic_copy_example_module !----------------------------------------------------------------------- module polymorphic_copy_example_module implicit none private ! all by default public :: T,S   type, abstract :: T con...
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...
#Perl
Perl
  #!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Polyspiral use warnings; use Tk; use List::Util qw( min );   my $size = 500; my ($width, $height, $x, $y, $dist); my $angleinc = 0; my $active = 0; my $wait = 1000 / 30; my $radian = 90 / atan2 1, 0;   my $mw = MainWindow->new; $mw->title( 'Polyspiral' ); m...
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...
#Emacs_Lisp
Emacs Lisp
(let ((x '(0 1 2 3 4 5 6 7 8 9 10)) (y '(1 6 17 34 57 86 121 162 209 262 321))) (calc-eval "fit(a*x^2+b*x+c,[x],[a,b,c],[$1 $2])" nil (cons 'vec x) (cons 'vec y)))
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#C
C
#include <stdio.h>   struct node { char *s; struct node* prev; };   void powerset(char **v, int n, struct node *up) { struct node me;   if (!n) { putchar('['); while (up) { printf(" %s", up->s); up = up->prev; } puts(" ]"); } else { me.s = *v; me.prev = up; powerset(v + 1, n - 1, up); powerse...
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 ...
#B
B
isprime(n) { auto p; if(n<2) return(0); if(!(n%2)) return(n==2); p=3; while(n/p>p) { if(!(n%p)) return(0); p=p+2; } return(1); }
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 ...
#Delphi
Delphi
  class APPLICATION   create make   feature   make --Tests the price_adjusted feature. local i: REAL do create price_fraction.initialize from i := 5 until i = 100 loop io.put_string ("Given: ") io.put_real (i / 100) io.put_string ("%TAdjusted:") io.put_real (price_fracti...
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...
#Free_Pascal
Free Pascal
  Program ProperDivisors;   Uses fgl;   Type TIntegerList = Specialize TfpgList<longint>;   Var list : TintegerList;   Function GetProperDivisors(x : longint): longint; {this function will return the number of proper divisors and put them in the list}   Var i : longint; Begin list.clear; If x = 1 Then {by defau...
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...
#Lua
Lua
items = {} items["aleph"] = 1/5.0 items["beth"] = 1/6.0 items["gimel"] = 1/7.0 items["daleth"] = 1/8.0 items["he"] = 1/9.0 items["waw"] = 1/10.0 items["zayin"] = 1/11.0 items["heth"] = 1759/27720   num_trials = 1000000   samples = {} for item, _ in pairs( items ) do samples[item] = 0 end   math.random...
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...
#Java
Java
import java.util.PriorityQueue;   class Task implements Comparable<Task> { final int priority; final String name;   public Task(int p, String n) { priority = p; name = n; }   public String toString() { return priority + ", " + name; }   public int compareTo(Task other...
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 ...
#Sidef
Sidef
class Circle(x,y,r) { method to_s { "Circle(#{x}, #{y}, #{r})" } }   func solve_apollonius(c, s) {   var(c1, c2, c3) = c...; var(s1, s2, s3) = s...;   var 𝑣11 = (2*c2.x - 2*c1.x); var 𝑣12 = (2*c2.y - 2*c1.y); var 𝑣13 = (c1.x**2 - c2.x**2 + c1.y**2 - c2.y**2 - c1.r**2 + c2.r**2); var 𝑣14 ...
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...
#VBA
VBA
Debug.Print Application.Name
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...
#vbscript
vbscript
  Wscript.Echo "FullName:",Wscript.FullName Wscript.Echo "Name:",Wscript.Name Wscript.Echo "Path:",Wscript.Path Wscript.Echo "ScriptFullName:",Wscript.ScriptFullName Wscript.Echo "ScriptName:",Wscript.ScriptName  
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...
#Visual_Basic
Visual Basic
appname = App.EXEName 'appname = "MyVBapp"
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,...
#Rust
Rust
use std::thread;   fn f1 (a : u64, b : u64, c : u64, d : u64) -> u64 { let mut primitive_count = 0; for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c], [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter...
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...
#Ring
Ring
  for n = 1 to 10 see n + nl if n = 5 exit ok next  
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...
#Ruby
Ruby
if problem exit(1) end   # or if problem abort # equivalent to exit(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
#Polyglot:PL.2FI_and_PL.2FM
Polyglot:PL/I and PL/M
/* PRIMALITY BY WILSON'S THEOREM */ wilson_100H: procedure options (main);   /* PL/I DEFINITIONS */ %include 'pg.inc'; /* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /* DECLAR...
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
#Python
Python
from math import factorial   def is_wprime(n): return n == 2 or ( n > 1 and n % 2 != 0 and (factorial(n - 1) + 1) % n == 0 )   if __name__ == '__main__': c = int(input('Enter upper limit: ')) print(f'Primes under {c}:') print([n for n in range(c) if is_wprime(n)])
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Ruby
Ruby
require "prime"   def prime_conspiracy(m) conspiracy = Hash.new(0) Prime.take(m).map{|n| n%10}.each_cons(2){|a,b| conspiracy[[a,b]] += 1} puts "#{m} first primes. Transitions prime % 10 → next-prime % 10." conspiracy.sort.each do |(a,b),v| puts "%d → %d count:%10d frequency:%7.4f %" % [a, b, v, 100.0*v/m] ...
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 ...
#Rust
Rust
// main.rs mod bit_array; mod prime_sieve;   use prime_sieve::PrimeSieve;   // See https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number fn upper_bound_for_nth_prime(n: usize) -> usize { let x = n as f64; (x * (x.ln() + x.ln().ln())) as usize }   fn compute_transitions(limit...
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 ...
#Common_Lisp
Common Lisp
;;; Recursive algorithm (defun factor (n) "Return a list of factors of N." (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (+ d 1) (+ d 2)) do (cond ((> d max-d) (return (list n))) ; n is prime ((zerop (rem n d)) (return (cons d (factor (truncate n d)))))))))
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#E
E
var x := 0 def slot := &x # define "slot" to be x's slot x := 1 # direct assignment; value is now 1 slot.put(2) # via slot object; value is now 2
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#EchoLisp
EchoLisp
  (define B (box 42)) → B ;; box reference (unbox B) → 42 ;; box contents   ;; sets new value for box contents (define ( change-by-ref abox avalue) (set-box! abox avalue) )   (change-by-ref B 666) → #[box 666] (unbox B) → 666  
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Forth
Forth
variable myvar \ stores 1 cell fvariable myfvar \ stores 1 floating point number (often 8 bytes) 2variable my2var \ stores 2 cells
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#BBC_BASIC
BBC BASIC
DIM x(9), y(9) x() = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 y() = 2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0   ORIGIN 100,100 VDU 23,23,2;0;0;0; VDU 5   FOR x = 1 TO 9 GCOL 7 : LINE 100*x,720,100*x,0 GCOL 0 : PLOT 0,-10,-4 :...
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <plot.h>   #define NP 10 double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};   void minmax(double *x, double *y, double *minx, double *maxx, double *miny, double *maxy, ...
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#C.23
C#
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { Sy...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#Clojure
Clojure
(defn rank [card] (let [[fst _] card] (if (Character/isDigit fst) (Integer/valueOf (str fst)) ({\T 10, \J 11, \Q 12, \K 13, \A 14} fst))))   (defn suit [card] (let [[_ snd] card] (str snd)))   (defn n-of-a-kind [hand n] (not (empty? (filter #(= true %) (map #(>= % n) (vals (frequencies (map ra...
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#AutoHotkey
AutoHotkey
Loop, 30 Out1 .= PopCount(3 ** (A_Index - 1)) " " Loop, 60 i := A_Index - 1 , PopCount(i) & 0x1 ? Out3 .= i " " : Out2 .= i " " MsgBox, % "3^x:`t" Out1 "`nEvil:`t" Out2 "`nOdious:`t" Out3   PopCount(x) { ;https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation x -= (x >> 1) & 0x5555555555555555 , x :...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Delphi
Delphi
  program Polynomial_long_division;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type PPolySolution = ^TPolySolution;   TPolynomio = record private class function Degree(p: TPolynomio): Integer; static; class function ShiftRight(p: TPolynomio; places: Integer): TPolynomio; static; class function P...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Go
Go
package main   import ( "fmt" "reflect" )   // interface types provide polymorphism, but not inheritance. type i interface { identify() string }   // "base" type type t float64   // "derived" type. in Go terminology, it is simply a struct with an // anonymous field. fields and methods of anonymous fields ...
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...
#Phix
Phix
-- -- demo\rosetta\Polyspiral.exw -- =========================== -- -- Space toggles the timer, '+' increases speed (up to 100 FPS), '-' decreases speed -- 'M' toggles "mod360", which inverts the angle every 360/2PI or so, since sin/cos -- accept arguments in radians not degrees (and mod 2*PI changes nothing), produci...
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...
#Fortran
Fortran
module fitting contains   function polyfit(vx, vy, d) implicit none integer, intent(in) :: d integer, parameter :: dp = selected_real_kind(15, 307) real(dp), dimension(d+1) :: polyfit real(dp), dimension(:), intent(in) :: vx, vy   real(dp), ...
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...
#C.23
C#
  public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list) { return from m in Enumerable.Range(0, 1 << list.Count) select from i in Enumerable.Range(0, list.Count) where (m & (1 << i)) != 0 select list[i]; }   public void Pow...
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 ...
#BASIC
BASIC
FUNCTION prime% (n!) STATIC i AS INTEGER IF n = 2 THEN prime = 1 ELSEIF n <= 1 OR n MOD 2 = 0 THEN prime = 0 ELSE prime = 1 FOR i = 3 TO INT(SQR(n)) STEP 2 IF n MOD i = 0 THEN prime = 0 EXIT FUNCTION END IF NEXT i END IF END FUNCTION   ' Test and display primes ...
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 ...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make --Tests the price_adjusted feature. local i: REAL do create price_fraction.initialize from i := 5 until i = 100 loop io.put_string ("Given: ") io.put_real (i / 100) io.put_string ("%TAdjusted:") io.put_real (price_fracti...
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...
#Frink
Frink
  for n = 1 to 10 println["$n\t" + join[" ", properDivisors[n]]]   println[]   d = new dict for n = 1 to 20000 { c = length[properDivisors[n]] d.addToList[c, n] }   most = max[keys[d]] println[d@most + " have $most factors"]   properDivisors[n] := allFactors[n, true, false, true]  
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
choices={{"aleph", 1/5},{"beth", 1/6},{"gimel", 1/7},{"daleth", 1/8},{"he", 1/9},{"waw", 1/10},{"zayin", 1/11},{"heth", 1759/27720}}; data=RandomChoice[choices[[All,2]]->choices[[All,1]],10^6];
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...
#MATLAB
MATLAB
function probChoice choices = {'aleph' 'beth' 'gimel' 'daleth' 'he' 'waw' 'zayin' 'heth'}; w = [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720]; R = randsample(length(w), 1e6, true, w); T = tabulate(R); fprintf('Value\tCount\tPercent\tGoal\n') for k = 1:size(T, 1) fprintf('%6s\t%.f\t%.2f%%\t%....
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...
#jq
jq
# In the following, pq stands for "priority queue".   # Add an item with the given priority (an integer, # or a string representing an integer) # Input: a pq def pq_add(priority; item): (priority|tostring) as $p | if .priorities|index($p) then if (.[$p] | index(item)) then . else .[$p] += [item] end els...
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 ...
#Swift
Swift
import Foundation   struct Circle { let center:[Double]! let radius:Double!   init(center:[Double], radius:Double) { self.center = center self.radius = radius }   func toString() -> String { return "Circle[x=\(center[0]),y=\(center[1]),r=\(radius)]" } }   func solveApollo...
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 ...
#Tcl
Tcl
package require TclOO; # Just so we can make a circle class   oo::class create circle { variable X Y Radius constructor {x y radius} { namespace import ::tcl::mathfunc::double set X [double $x]; set Y [double $y]; set Radius [double $radius] } method values {} {list $X $Y $Radius} method format {}...
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...
#Wren
Wren
import "os" for Process   System.print("My name is %(Process.allArguments[1])")
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#x86_Assembly
x86 Assembly
FORMAT=-f elf RUN=./ BIN=scriptname OBJ=scriptname.o   all: test   test: $(BIN) $(RUN)$(BIN)   $(BIN): $(OBJ) ld -o $(BIN) $(OBJ)   $(OBJ): scriptname.asm nasm $(FORMAT) -o $(OBJ) scriptname.asm   clean: -rm $(BIN) -rm $(OBJ)
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,...
#Scala
Scala
object PythagoreanTriples extends App {   println(" Limit Primatives All")   for {e <- 2 to 7 limit = math.pow(10, e).longValue() } { var primCount, tripCount = 0   def parChild(a: BigInt, b: BigInt, c: BigInt): Unit = { val perim = a + b + c val (a2, b2, c2, c3) ...
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...
#Run_BASIC
Run BASIC
if whatever then 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...
#Rust
Rust
fn main() { println!("The program is running"); return; println!("This line won't be printed"); }
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
#Quackery
Quackery
[ 1 swap times [ i 1+ * ] ] is ! ( n --> n )   [ dup 2 < iff [ drop false ] done dup 1 - ! 1+ swap mod 0 = ] is prime ( n --> b )   say "Primes less than 500: " 500 times [ i^ prime if [ i^ echo sp ] ]
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
#Raku
Raku
sub postfix:<!> (Int $n) { (constant f = 1, |[\*] 1..*)[$n] }   sub is-wilson-prime (Int $p where * > 1) { (($p - 1)! + 1) %% $p }   # Pre initialize factorial routine (not thread safe) 9000!;   # Testing put ' p prime?'; printf("%4d  %s\n", $_, .&is-wilson-prime) for 2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237...
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 ...
#Scala
Scala
import scala.annotation.tailrec import scala.collection.mutable   object PrimeConspiracy extends App { val limit = 1000000 val sieveTop = 15485863/*one millionth prime*/ + 1 val buckets = Array.ofDim[Int](10, 10) var prevPrime = 2   def sieve(limit: Int) = { val composite = new mutable.BitSet(sieveTop) ...
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 ...
#D
D
import std.stdio, std.bigint, std.algorithm, std.traits, std.range;   Unqual!T[] decompose(T)(in T number) pure nothrow in { assert(number > 1); } body { typeof(return) result; Unqual!T n = number;   for (Unqual!T i = 2; n % i == 0; n /= i) result ~= i; for (Unqual!T i = 3; n >= i * i; i += ...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Fortran
Fortran
real, pointer :: pointertoreal
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type Cat name As String age As Integer End Type   Type CatInfoType As Sub (As Cat Ptr)   Sub printCatInfo(c As Cat Ptr) Print "Name "; c->name, "Age"; c-> age Print End Sub   ' create Cat object on heap and store a pointer to it Dim c As Cat Ptr = New Cat   ' set fields using the pointer and...
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <vector>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int HSTEP = 46, MWID = 40, M...
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#C.2B.2B
C++
#include <cstdio> #include <cstdlib>   class Point { protected: int x, y;   public: Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {} Point(const Point &p) : x(p.x), y(p.y) {} virtual ~Point() {} const Point& operator=(const Point &p) { if (this != &p) { x = p.x; y = p....
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#D
D
import std.stdio, std.string, std.algorithm, std.range;   string analyzeHand(in string inHand) pure /*nothrow @safe*/ { enum handLen = 5; static immutable face = "A23456789TJQK", suit = "SHCD"; static immutable errorMessage = "invalid hand.";   /*immutable*/ const hand = inHand.toUpper.split.sort().rele...
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#AWK
AWK
  # syntax: GAWK -f POPULATION_COUNT.AWK # converted from VBSCRIPT BEGIN { nmax = 30 b = 3 n = 0 bb = 1 for (i=1; i<=nmax; i++) { list = list pop_count(bb) " " bb *= b } printf("%s^n: %s\n",b,list) for (j=0; j<=1; j++) { c = (j == 0) ? "evil" : "odious" i = n = 0 ...