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/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
... | #11l | 11l | F popcount(n)
R bin(n).count(‘1’)
print((0.<30).map(i -> popcount(Int64(3) ^ i)))
[Int] evil, odious
V i = 0
L evil.len < 30 | odious.len < 30
V p = popcount(i)
I (p % 2) != 0
odious.append(i)
E
evil.append(i)
i++
print(evil[0.<30])
print(odious[0.<30]) |
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... | #11l | 11l | F degree(&poly)
L !poly.empty & poly.last == 0
poly.pop()
R poly.len - 1
F poly_div(&n, &D)
V dD = degree(&D)
V dN = degree(&n)
I dD < 0
exit(1)
[Float] q
I dN >= dD
q = [0.0] * dN
L dN >= dD
V d = [0.0] * (dN - dD) [+] D
V mult = n.last / Float(d.last)
... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Polymorphic_Copy is
package Base is
type T is tagged null record;
type T_ptr is access all T'Class;
function Name (X : T) return String;
end Base;
use Base;
package body Base is
function Name (X : T) return String is
begin
... |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ |
## plotpoly.gp 1/10/17 aev
## Plotting a polyspiral and writing to the png-file.
## Note: assign variables: rng, d, clr, filename and ttl (before using load command).
## Direction d (-1 clockwise / 1 counter-clockwise)
reset
set terminal png font arial 12 size 640,640
ofn=filename.".png"
set output ofn
unset border;... |
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... | #ALGOL_68 | ALGOL 68 | MODE FIELD = REAL;
MODE
VEC = [0]FIELD,
MAT = [0,0]FIELD;
PROC VOID raise index error := VOID: (
print(("stop", new line));
stop
);
COMMENT from http://rosettacode.org/wiki/Matrix_Transpose#ALGOL_68 END COMMENT
OP ZIP = ([,]FIELD in)[,]FIELD:(
[2 LWB in:2 UPB in,1 LWB in:1UPB in]FIELD out;
FOR i FROM ... |
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... | #APL | APL | ps←(↓∘⍉(2/⍨≢)⊤(⍳2*≢))(/¨)⊂ |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Ada | Ada | function Is_Prime(Item : Positive) return Boolean is
Test : Natural;
begin
if Item = 1 then
return False;
elsif Item = 2 then
return True;
elsif Item mod 2 = 0 then
return False;
else
Test := 3;
while Test <= Integer(Sqrt(Float(Item))) loop
if Item mod Test = 0 then... |
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 ... | #BASIC256 | BASIC256 | arraybase 1
dim byValue = {10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100}
dim byLimit = {6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96}
for byCount = 1 to 100
for byCheck = 0 to byLimit[?]
if byCount < byLimit[byCheck] then exit for
next byCheck
... |
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... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Test the feature proper_divisors.
local
list: LINKED_LIST [INTEGER]
count, number: INTEGER
do
across
1 |..| 10 as c
loop
list := proper_divisors (c.item)
io.put_string (c.item.out + ": ")
across
list as l
loop
io.p... |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is invol... | #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
type mapping struct {
item string
pr float64
}
func main() {
// input mapping
m := []mapping{
{"aleph", 1 / 5.},
{"beth", 1 / 6.},
{"gimel", 1 / 7.},
{"daleth", 1 / 8.},
{"he", 1 / 9.},
{... |
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... | #Factor | Factor | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi |
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 ... | #Perl | Perl | use utf8;
use Math::Cartesian::Product;
package Circle;
sub new {
my ($class, $args) = @_;
my $self = {
x => $args->{x},
y => $args->{y},
r => $args->{r},
};
bless $self, $class;
}
sub show {
my ($self, $args) = @_;
sprintf "x =%7.3f y =%7.3f r =%7.3f\n", $args->{... |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Racket | Racket | #!/usr/bin/env racket
#lang racket
(define (program) (find-system-path 'run-file))
(module+ main (printf "Program: ~a\n" (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... | #Raku | Raku | say $*PROGRAM-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,... | #PowerShell | PowerShell |
function triples($p) {
if($p -gt 4) {
# ai + bi + ci = pi <= p
# ai < bi < ci --> 3ai < pi <= p and ai + 2bi < pi <= p
$pa = [Math]::Floor($p/3)
1..$pa | foreach {
$ai = $_
$pb = [Math]::Floor(($p-$ai)/2)
($ai+1)..$pb | foreach {
... |
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... | #Phix | Phix | if error_code!=NO_ERROR then
abort(0)
end 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... | #Phixmonti | Phixmonti | if 1 quit endif |
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
| #Haskell | Haskell | import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
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 ... | #Pascal | Pascal |
program primCons;
{$IFNDEF FPC}
{$APPTYPE CONSOLE}
{$ENDIF}
const
PrimeLimit = 2038074748 DIV 2;
type
tLimit = 0..PrimeLimit;
tCntTransition = array[0..9,0..9] of NativeInt;
tCntTransRec = record
CTR_CntTrans:tCntTransition;
CTR_primCnt,
CTR_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 ... | #Batch_file | Batch file |
@echo off
::usage: cmd /k primefactor.cmd number
setlocal enabledelayedexpansion
set /a compo=%1
if "%compo%"=="" goto:eof
set list=%compo%= (
set /a div=2 & call :loopdiv
set /a div=3 & call :loopdiv
set /a div=5,inc=2
:looptest
call :loopdiv
set /a div+=inc,inc=6-inc,div2=div*div
if %div2% lss %compo% goto l... |
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
... | #360_Assembly | 360 Assembly | * Population count 09/05/2019
POPCNT CSECT
USING POPCNT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Long_Division is
package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
use Int_IO;
type Degrees is range -1 .. Integer'Last;
subtype Valid_Degrees is Degrees range 0 .. Degrees'Last;
type Polynom is array (Valid_Degrees range <>) of Integer;
functio... |
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... | #Aikido | Aikido |
class T {
public function print {
println ("class T")
}
}
class S extends T {
public function print {
println ("class S")
}
}
var t = new T()
var s = new S()
println ("before copy")
t.print()
s.print()
var tcopy = clone (t, false)
var scopy = clone (s, false)
println ("after copy... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
# Algol 68 doesn't have classes and inheritence as such, however structures #
# can contain procedures and different instances of a structure can have #
# different versons of the procedure #
# this allows us to simulate inheritence by creating structure i... |
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... | #Gnuplot | Gnuplot |
## plotpoly.gp 1/10/17 aev
## Plotting a polyspiral and writing to the png-file.
## Note: assign variables: rng, d, clr, filename and ttl (before using load command).
## Direction d (-1 clockwise / 1 counter-clockwise)
reset
set terminal png font arial 12 size 640,640
ofn=filename.".png"
set output ofn
unset border;... |
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... | #Go | Go | $ convert polyspiral.gif -coalesce polyspiral2.gif
$ eog polyspiral2.gif
|
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... | #AutoHotkey | AutoHotkey |
regression(xa,ya){
n := xa.Count()
xm := ym := x2m := x3m := x4m := xym := x2ym := 0
loop % n {
i := A_Index
xm := xm + xa[i]
ym := ym + ya[i]
x2m := x2m + xa[i] * xa[i]
x3m := x3m + xa[i] * xa[i] * xa[i]
x4m := x4m + xa[i] * xa[i] * xa[i] * xa[i]
xym := xym + xa[i] * ya[i]
x2ym := x2ym + xa[i] *... |
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... | #AppleScript | AppleScript | -- POWER SET -----------------------------------------------------------------
-- powerset :: [a] -> [[a]]
on powerset(xs)
script subSet
on |λ|(acc, x)
script cons
on |λ|(y)
{x} & y
end |λ|
end script
acc & map(cons,... |
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
... | #ALGOL_68 | ALGOL 68 | COMMENT
This routine is used in more than one place, and is essentially a
template that can by used for many different types, eg INT, LONG INT...
USAGE
MODE ISPRIMEINT = INT, LONG INT, etc
PR READ "prelude/is_prime.a68" PR
END COMMENT
|
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 ... | #BBC_BASIC | BBC BASIC | PRINT FNpricefraction(0.5)
END
DEF FNpricefraction(p)
IF p < 0.06 THEN = 0.10
IF p < 0.11 THEN = 0.18
IF p < 0.16 THEN = 0.26
IF p < 0.21 THEN = 0.32
IF p < 0.26 THEN = 0.38
IF p < 0.31 THEN = 0.44
IF p < 0.36 THEN = 0.50
IF p < 0.41 THEN = 0.54
... |
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 ... | #Beads | Beads | beads 1 program 'Price fraction'
record a_table
value
rescaled
const table : array of a_table = [<
value, rescaled
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.... |
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... | #Elixir | Elixir | defmodule Proper do
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
defp divisors(k,_n,q) when k>q, do: []
defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q)
defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)]
defp divisors(k,n,q) ... |
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... | #Haskell | Haskell | import System.Random (newStdGen, randomRs)
dataBinCounts :: [Float] -> [Float] -> [Int]
dataBinCounts thresholds range =
let sampleSize = length range
xs = ((-) sampleSize . length . flip filter range . (<)) <$> thresholds
in zipWith (-) (xs ++ [sampleSize]) (0 : xs)
main :: IO ()
main = do
g <- newStdG... |
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... | #Fortran | Fortran | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
... |
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 ... | #Phix | Phix | function Apollonius(sequence calc, circles)
integer {s1,s2,s3} = calc
atom {x1,y1,r1} = circles[1],
{x2,y2,r2} = circles[2],
{x3,y3,r3} = circles[3],
v11 = 2*x2 - 2*x1,
v12 = 2*y2 - 2*y1,
v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2,
v14 =... |
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... | #Raven | Raven | ARGS list " " join "%s\n" print |
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... | #REXX | REXX | /* Rexx */
Parse source . . pgmPath
Say pgmPath
|
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,... | #Prolog | Prolog |
show :-
Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000],
forall(
member(Max, Data),
(count_triples(Max, Total, Prim),
format("upto ~D, there are ~D Pythagorean triples (~D primitive.)~n", [Max, Total, Prim]))).
div(A, B, C) :- C is A div B.
count_triples(M... |
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... | #PHP | PHP | if (problem)
exit(1); |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Picat | Picat |
% ...
if problem then
halt
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
| #J | J |
wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
|
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
| #Java | Java |
import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", 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 ... | #Perl | Perl | use ntheory qw/forprimes nth_prime/;
my $upto = 1_000_000;
my %freq;
my($this_digit,$last_digit)=(2,0);
forprimes {
($last_digit,$this_digit) = ($this_digit, $_ % 10);
$freq{$last_digit . $this_digit}++;
} 3,nth_prime($upto);
print "$upto first primes. Transitions prime % 10 → next-prime % 10.\n";
printf "%s... |
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 ... | #Befunge | Befunge | & 211p > : 1 - #v_ 25*, @ > 11g:. / v
> : 11g %!|
> 11g 1+ 11p v
^ < |
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 |... | #6502_Assembly | 6502 Assembly | LDA $19 ;load the value at memory address $19 into the accumulator
LDA #$19 ;load the value hexadecimal 19 (decimal 25) into the accumulator |
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
... | #8080_Assembly | 8080 Assembly | org 100h
mvi e,30 ; 3^0 to 3^29 inclusive
powers: push d ; Keep counter
;;; Calculate Hamming weight of pow3
lxi b,6 ; C = 6 bytes, B = counter
lxi h,pow3
ham48: mov a,m ; Get byte
ana a ; Clear carry
hambt: ral ; Rotate into carry
jnc $+4 ; Increment counter if carry set
inr b
ana a ; Done yet?
jnz hambt ; ... |
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... | #APL | APL | div←{
{
q r d←⍵
(≢d) > n←≢r : q r
c ← (⊃⌽r) ÷ ⊃⌽d
∇ (c,q) ((¯1↓r) - c × ¯1↓(-n)↑d) d
} ⍬ ⍺ ⍵
}
|
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... | #BBC_BASIC | BBC BASIC | INSTALL @lib$ + "CLASSLIB"
REM Create parent class T:
DIM classT{array#(0), setval, retval}
DEF classT.setval (n%,v) classT.array#(n%) = v : ENDPROC
DEF classT.retval (n%) = classT.array#(n%)
PROC_class(classT{})
REM Create class S derived from T, known only at run-time:
... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct object *BaseObj;
typedef struct sclass *Class;
typedef void (*CloneFctn)(BaseObj s, BaseObj clo);
typedef const char * (*SpeakFctn)(BaseObj s);
typedef void (*DestroyFctn)(BaseObj s);
typedef struct sclass {
size_t csize; /* size of the ... |
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... | #Haskell | Haskell | {-# LANGUAGE OverloadedStrings #-}
import Reflex
import Reflex.Dom
import Reflex.Dom.Time
import Data.Text (Text, pack)
import Data.Map (Map, fromList)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.Trans (liftIO)
type Point = (Float,Float)
type Segment = (Point,Point)
main = mainWidget $ 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... | #AWK | AWK |
BEGIN{
i = 0;
xa[i] = 0; i++;
xa[i] = 1; i++;
xa[i] = 2; i++;
xa[i] = 3; i++;
xa[i] = 4; i++;
xa[i] = 5; i++;
xa[i] = 6; i++;
xa[i] = 7; i++;
xa[i] = 8; i++;
xa[i] = 9; i++;
xa[i] = 10; i++;
i = 0;
ya[i] = 1; i++;
ya[i] = 6; i++;
ya[i] = 17; i++;
ya[i] = 34; i++;
ya[i] ... |
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... | #Arturo | Arturo | print powerset [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
... | #ALGOL-M | ALGOL-M |
BEGIN
% RETURN P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% RETURN INTEGER SQUARE ROOT OF N %
INTEGER FUNCTION ISQRT(N);
INTEGER N;
BEGIN
INTEGER R1, R2;
R1 := N;
R2 := 1;
WHILE R1 > R2 DO
BEGIN
R1 := (R1+R2) / 2;
R2 := N / R1;
END;
ISQRT... |
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 ... | #Bracmat | Bracmat | ( ( convert
=
. ("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")
... |
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... | #Erlang | Erlang | -module(properdivs).
-export([divs/1,sumdivs/1,longest/1]).
divs(0) -> [];
divs(1) -> [];
divs(N) -> lists:sort([1] ++ divisors(2,N,math:sqrt(N))).
divisors(K,_N,Q) when K > Q -> [];
divisors(K,N,Q) when N rem K =/= 0 ->
divisors(K+1,N,Q);
divisors(K,N,Q) when K * K == N ->
[K] ++ divisors(K+1,N,Q);
divi... |
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... | #HicEst | HicEst | REAL :: trials=1E6, n=8, map(n), limit(n), expected(n), outcome(n)
expected = 1 / ($ + 4)
expected(n) = 1 - SUM(expected) + expected(n)
map = expected
map = map($) + map($-1)
DO i = 1, trials
random = RAN(1)
limit = random > map
item = INDEX(limit, 0)
outcome(item) = outcome(item) + 1
ENDDO
outcome = ... |
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... | #FreeBASIC | FreeBASIC | Type Tupla
Prioridad As Integer
Tarea As String
End Type
Dim Shared As Tupla a()
Dim Shared As Integer n 'número de eltos. en la matriz, el último elto. es n-1
Function Izda(i As Integer) As Integer
Izda = 2 * i + 1
End Function
Function Dcha(i As Integer) As Integer
Dcha = 2 * i + 2
End Function
... |
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 ... | #PL.2FI | PL/I | Apollonius: procedure options (main); /* 29 October 2013 */
define structure
1 circle,
2 x float (15),
2 y float (15),
2 radius float (15);
declare (c1 , c2, c3, result) type (circle);
c1.x = 0; c1.y = 0; c1.radius = 1;
c2.x = 4; c2.y = 0; c2.radius = 1;
c3.x = 2; c3.y = 4; c3... |
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 ... | #PowerShell | PowerShell |
function Measure-Apollonius
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[int]$Counter,
[double]$x1,
[double]$y1,
[double]$r1,
[double]$x2,
[double]$y2,
[double]$r2,
[double]$x3,
[double]$y3,
[double]$r3
... |
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... | #Ring | Ring |
see "Active Source File Name : " + filename() + nl
|
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... | #Ruby | Ruby | #!/usr/bin/env ruby
puts "Path: #{$PROGRAM_NAME}" # or puts "Path: #{$0}"
puts "Name: #{File.basename $0}" |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime,... | #PureBasic | PureBasic |
Procedure.i ConsoleWrite(t.s) ; compile using /CONSOLE option
OpenConsole()
PrintN (t.s)
CloseConsole()
ProcedureReturn 1
EndProcedure
Procedure.i StdOut(t.s) ; compile using /CONSOLE option
OpenConsole()
Print(t.s)
CloseConsole()
ProcedureReturn 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... | #PicoLisp | PicoLisp | (push '*Bye '(prinl "Goodbye world!"))
(bye) |
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... | #PL.2FI | PL/I | STOP; /* terminates the entire program */
/* PL/I does any required cleanup, such as closing files. */ |
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
| #jq | jq | ## Compute (n - 1)! mod m.
def facmod($n; $m):
reduce range(2; $n+1) as $k (1; (. * $k) % $m);
def isPrime: .>1 and (facmod(. - 1; .) + 1) % . == 0;
"Prime numbers between 2 and 100:",
[range(2;101) | select (isPrime)],
# Notice that `infinite` can be used as the second argument of `range`:
"First 10 primes aft... |
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
| #Julia | Julia | iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimes... |
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 ... | #Phix | Phix | with javascript_semantics
sequence p10k = get_primes(-10_000),
transitions = repeat(repeat(0,9),9)
integer l = length(p10k), last = p10k[1], curr
for i=2 to l do
curr = remainder(p10k[i],10)
transitions[last][curr] += 1
last = curr
end for
for i=1 to 9 do
for j=1 to 9 do
atom tij = transitions... |
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 ... | #BQN | BQN | Factor ← { 𝕊n:
# Prime sieve
primes ← ↕0
Sieve ← { p 𝕊 a‿b:
p(⍋↑⊣)↩√b ⋄ l←b-a
E ← {↕∘⌈⌾(((𝕩|-a)+𝕩×⊢)⁼)l} # Indices of multiples of 𝕩
a + / (1⥊˜l) E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p # Primes in segment [a,b)
}
# Factor by trial division
r ← ↕0 # Result list
Try ← {
... |
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 |... | #8086_Assembly | 8086 Assembly | .model small
.stack 1024
.data ; data segment begins here
UserRam byte 256 dup (0) ; the next 256 bytes have a value of zero. The address of the 0th of these bytes can be referenced as "UserRam"
tempByte equ UserRam ;this variable's address is the same as that of the 0th byte of UserRam
tempWor... |
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
... | #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
org 100h
section .text
;;; Calculate hamming weights of 3^0 to 3^29.
;;; 3^29 needs a 48-bit representation, which
;;; we'll put in BP:SI:DI.
xor bp,bp ; BP:SI:DI = 1
xor si,si
xor di,di
inc di
mov cx,30
;;; Calculate pop count of BP:SI:DI
pow3s: push bp ; Keep state
push si
push di
xo... |
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... | #BBC_BASIC | BBC BASIC | DIM N%(3) : N%() = -42, 0, -12, 1
DIM D%(3) : D%() = -3, 1, 0, 0
DIM q%(3), r%(3)
PROC_poly_long_div(N%(), D%(), q%(), r%())
PRINT "Quotient = "; FNcoeff(q%(2)) "x^2" FNcoeff(q%(1)) "x" FNcoeff(q%(0))
PRINT "Remainder = " ; r%(0)
END
DEF PROC_poly_long_div(N%(), D%()... |
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... | #C.23 | C# | using System;
class T
{
public virtual string Name()
{
return "T";
}
public virtual T Clone()
{
return new T();
}
}
class S : T
{
public override string Name()
{
return "S";
}
public override T Clone()
{
return new S();
}
}
class ... |
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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "PolySp.bas"
110 OPTION ANGLE DEGREES
120 LET CH=2
130 SET VIDEO X 40:SET VIDEO Y 27:SET VIDEO MODE 1:SET VIDEO COLOR 0
140 OPEN #1:"video:"
150 OPEN #2:"video:"
160 WHEN EXCEPTION USE POSERROR
170 FOR ANG=40 TO 150 STEP 2
180 IF CH=2 THEN
190 LET CH=1
200 ELSE
210 LET CH=2
220 END... |
http://rosettacode.org/wiki/Polyspiral | Polyspiral | A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b... | #J | J | require 'gl2 trig media/imagekit'
coinsert 'jgl2'
DT =: %30 NB. seconds
ANGLE =: 0.025p1 NB. radians
DIRECTION=: 0 NB. radians
POLY=: noun define
pc poly;pn "Poly Spiral";
minwh 320 320; cc isi isigraph;
)
poly_run=: verb define
wd POLY,'pshow'
wd 'timer ',":DT * 1000
)
poly_cl... |
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... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"ARRAYLIB"
Max% = 10000
DIM vector(5), matrix(5,5)
DIM x(Max%), x2(Max%), x3(Max%), x4(Max%), x5(Max%)
DIM x6(Max%), x7(Max%), x8(Max%), x9(Max%), x10(Max%)
DIM y(Max%), xy(Max%), x2y(Max%), x3y(Max%), x4y(Max%), x5y(Max%)
npts% = 11
x() = 0, 1, 2, 3,... |
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... | #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
//
(* ****** ****** *)
//
extern
fun
Power_set(xs: list0(int)): void
//
(* ****** ****** *)
// Helper: fast power fu... |
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
... | #ALGOL_W | ALGOL W | % returns true if n is prime, false otherwise %
% uses trial division %
logical procedure isPrime ( integer value n ) ;
if n < 3 or not odd( n ) then n = 2
else begin
% odd number > 2 %
integer f, rootN;
logical havePrime;
f := 3;
rootN ... |
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 ... | #C | C | #include<stdio.h>
double table[][2] = {
{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... | #F.23 | F# |
// the simple function with the answer
let propDivs n = [1..n/2] |> List.filter (fun x->n % x = 0)
// to cache the result length; helpful for a long search
let propDivDat n = propDivs n |> fun xs -> n, xs.Length, xs
// UI: always the longest and messiest
let show (n,count,divs) =
let showCount = count |> functi... |
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... | #Icon_and_Unicon | Icon and Unicon |
record Item(value, probability)
procedure find_item (items, v)
sum := 0.0
every item := !items do {
if v < sum+item.probability
then return item.value
else sum +:= item.probability
}
fail # v exceeded 1.0
end
# -- helper procedures
# count the number of occurrences of i in list l,
# assumi... |
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... | #FunL | FunL | import util.ordering
native scala.collection.mutable.PriorityQueue
data Task( priority, description )
def comparator( Task(a, _), Task(b, _) )
| a > b = -1
| a < b = 1
| otherwise = 0
q = PriorityQueue( ordering(comparator) )
q.enqueue(
Task(3, 'Clear drains'),
Task(4, 'Feed cat'),
Task(5,... |
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 ... | #PureBasic | PureBasic | Structure Circle
XPos.f
YPos.f
Radius.f
EndStructure
Procedure ApolloniusSolver(*c1.Circle,*c2.Circle,*c3.Circle, s1, s2, s3)
Define.f ; This tells the compiler that all non-specified new variables
; should be of float type (.f).
x1=*c1\XPos: y1=*c1\YPos: r1=*c1\Radius
x2=*c2\XPos: y2=*c2\... |
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... | #Rust | Rust | fn main() {
println!("Program: {}", std::env::args().next().unwrap());
} |
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... | #SAC | SAC | use StdIO: all;
use Array: all;
use String: { string };
use CommandLine: all;
int main() {
program = argv(0);
printf("Program: %s\n", program);
return(0);
} |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime,... | #Python | Python | from fractions import gcd
def pt1(maxperimeter=100):
'''
# Naive method
'''
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+... |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Pop11 | Pop11 | if condition then
sysexit();
endif; |
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... | #PostScript | PostScript | condition {stop} if |
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem | Primality by Wilson's theorem | Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
| #Lua | Lua | -- primality by Wilson's theorem
function isWilsonPrime( n )
local fmodp = 1
for i = 2, n - 1 do
fmodp = fmodp * i
fmodp = fmodp % n
end
return fmodp == n - 1
end
for n = -1, 100 do
if isWilsonPrime( n ) then
io.write( " " .. n )
end
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[WilsonPrimeQ]
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ] |
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 ... | #Picat | Picat | go =>
N = 15_485_863, % 1_000_000 primes
Primes = {P mod 10 : P in primes(N)},
Len = Primes.len,
A = new_array(10,10), bind_vars(A,0),
foreach(I in 2..Len)
P1 = 1 + Primes[I-1], % adjust for 1-based
P2 = 1 + Primes[I],
A[P1,P2] := A[P1,P2] + 1
end,
foreach(I in 0..9, J in 0..9, V = A[I+1,J+1],... |
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 ... | #PicoLisp | PicoLisp |
(load "pluser/sieve.l") # See the task "Sieve of Eratosthanes"
(setq NthPrime '(
( 10 . 29)
( 100 . 541)
( 1000 . 7919)
( 10000 . 104729)
( 100000 . 1299709)
(1000000 . 15485863)))
(de conspiracy (Power)
(let (Upto (cdr (assoc (... |
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 ... | #Burlesque | Burlesque |
blsq ) 12fC
{2 2 3}
|
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 |... | #68000_Assembly | 68000 Assembly | myVar equ $100000 ; a section of user ram given a label
myData: ; a data table given a label
dc.b $80,$81,$82,$83 |
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 |... | #Ada | Ada | type Int_Access is access Integer;
Int_Acc : Int_Access := new Integer'(5); |
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
| #ActionScript | ActionScript | package
{
public class Point
{
protected var _x:Number;
protected var _y:Number;
public function Point(x:Number = 0, y:Number = 0)
{
_x = x;
_y = y;
}
public function getX():Number
{
return _x;
}
pu... |
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
... | #Ada | Ada | with Interfaces;
package Population_Count is
subtype Num is Interfaces.Unsigned_64;
function Pop_Count(N: Num) return Natural;
end Population_Count; |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <gsl/gsl_vector.h>
#define MAX(A,B) (((A)>(B))?(A):(B))
void reoshift(gsl_vector *v, int h)
{
if ( h > 0 ) {
gsl_vector *temp = gsl_vector_alloc(v->size);
gsl_vector_view p = gsl_vector_subvector(v, 0, v->size - h);
... |
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... | #C.2B.2B | C++ | #include <iostream>
class T
{
public:
virtual void identify() { std::cout << "I am a genuine T" << std::endl; }
virtual T* clone() { return new T(*this); }
virtual ~T() {}
};
class S: public T
{
public:
virtual void identify() { std::cout << "I am an S" << std::endl; }
virtual S* clone() { return new S(*t... |
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... | #Java | Java | import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PolySpiral extends JPanel {
double inc = 0;
public PolySpiral() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
new Timer(40, (ActionEvent e) -> {
inc = (in... |
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... | #C | C | #ifndef _POLIFITGSL_H
#define _POLIFITGSL_H
#include <gsl/gsl_multifit.h>
#include <stdbool.h>
#include <math.h>
bool polynomialfit(int obs, int degree,
double *dx, double *dy, double *store); /* n, p */
#endif |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.