task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #Python | Python | #!/usr/bin/env python3
import numpy as np
def qr(A):
m, n = A.shape
Q = np.eye(m)
for i in range(n - (m == n)):
H = np.eye(m)
H[i:, i:] = make_householder(A[i:, i])
Q = np.dot(Q, H)
A = np.dot(H, A)
return Q, A
def make_householder(a):
v = a / (a[0] + np.copysig... |
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #C | C | #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool is_prime(unsigned int n) {
assert(n < 64);
static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,
0, 0,... |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5... | #Ada | Ada | generic
type Result_Type (<>) is limited private;
None: Result_Type;
with function One(X: Positive) return Result_Type;
with function Add(X, Y: Result_Type) return Result_Type
is <>;
package Generic_Divisors is
function Process
(N: Positive; First: Positive := 1) return Result_Type is
... |
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... | #11l | 11l | V items = [(3, ‘Clear drains’), (4, ‘Feed cat’), (5, ‘Make tea’), (1, ‘Solve RC tasks’), (2, ‘Tax return’)]
minheap:heapify(&items)
L !items.empty
print(minheap:pop(&items)) |
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 ... | #AutoHotkey | AutoHotkey | #NoEnv
#SingleInstance, Force
SetBatchLines, -1
; Uncomment if Gdip.ahk is not in your standard library
;#Include, Gdip.ahk
; Start gdi+
If !pToken := Gdip_Startup()
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, Exit
; I've added a simple ne... |
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... | #J | J | #!/usr/bin/env jconsole
program =: monad : 0
if. (#ARGV) > 1 do.
> 1 { ARGV
else.
'Interpreted'
end.
)
echo 'Program: ', program 0
exit '' |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Java | Java | public class ScriptName {
public static void main(String[] args) {
String program = System.getProperty("sun.java.command").split(" ")[0];
System.out.println("Program: " + program);
}
} |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #jq | jq | def primes:
2, range(3; infinite; 2) | select(is_prime);
# generate an infinite stream of primorials beginning with primorial(0)
def primorials:
0, foreach primes as $p (1; .*$p; .);
"The first ten primorial numbers are:",
limit(10; primorials),
"\nThe primorials with the given index have the lengths shown:",... |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Julia | Julia |
using Primes
primelist = primes(300000001) # primes to 30 million
primorial(n) = foldr(*, primelist[1:n], init=BigInt(1))
println("The first ten primorials are: $([primorial(n) for n in 1:10])")
for i in 1:6
n = 10^i
p = primorial(n)
plen = Int(floor(log10(p))) + 1
println("primorial($n) has l... |
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,... | #JavaScript | JavaScript | (() => {
"use strict";
// Arguments: predicate, maximum perimeter
// pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int
const pythTripleCount = p =>
maxPerim => {
const
xs = enumFromTo(1)(
Math.floor(maxPerim / 2)
);
... |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Fortran | Fortran | IF (condition) STOP [message]
! message is optional and is a character string.
! If present, the message is output to the standard output device. |
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... | #FreeBASIC | FreeBASIC | 'FB 1.05.0 Win64 'endprog.bas'
Dim isError As Boolean = True
If isError Then
End 1
End If
' The following code won't be executed
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #R | R | # R has QR decomposition built-in (using LAPACK or LINPACK)
a <- matrix(c(12, -51, 4, 6, 167, -68, -4, 24, -41), nrow=3, ncol=3, byrow=T)
d <- qr(a)
qr.Q(d)
qr.R(d)
# now fitting a polynomial
x <- 0:10
y <- 3*x^2 + 2*x + 1
# using QR decomposition directly
a <- cbind(1, x, x^2)
qr.coef(qr(a), y)
# using least s... |
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #C.2B.2B | C++ | #include <cassert>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
bool is_prime(unsigned int n) {
assert(n > 0 && n < 64);
return (1ULL << n) & 0x28208a20a08a28ac;
}
template <typename Iterator>
bool prime_triangle_row(Iterator begin, Iterator end) {
if (st... |
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... | #ALGOL_68 | ALGOL 68 | # MODE to hold an element of a list of proper divisors #
MODE DIVISORLIST = STRUCT( INT divisor, REF DIVISORLIST next );
# end of divisor list value #
REF DIVISORLIST nil divisor list = REF DIVISORLIST(NIL);
# resturns a DIVISORLIST containing the proper divisors of ... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program priorQueue64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesA... |
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 ... | #BASIC256 | BASIC256 |
circle1$ = " 0.000, 0.000, 1.000"
circle2$ = " 4.000, 0.000, 1.000"
circle3$ = " 2.000, 4.000, 2.000"
subroutine ApolloniusSolver(c1$, c2$, c3$, s1, s2, s3)
x1 = int(mid(c1$, 3, 1)): y1 = int(mid(c1$, 11, 1)): r1 = int(mid(c1$, 19, 1))
x2 = int(mid(c2$, 3, 1)): y2 = int(mid(c2$, 11, 1)): r2 = int(mid(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... | #JavaScript | JavaScript | function foo() {
return arguments.callee.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... | #Jsish | Jsish | #!/usr/bin/env jsish
/* Program name, in Jsish */
puts('Executable:', Info.executable());
puts('Argv0 :', Info.argv0()); |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Kotlin | Kotlin | // version 1.0.6
import java.math.BigInteger
const val LIMIT = 1000000 // expect a run time of about 20 minutes on a typical laptop
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
... |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime,... | #jq | jq | def gcd(a; b):
def _gcd:
if .[1] == 0 then .[0]
else [.[1], .[0] % .[1]] | _gcd
end;
[a,b] | _gcd ;
# Return: [total, primitives] for pythagorean triangles having
# perimeter no larger than peri.
# The following uses Euclid's formula with the convention: m > n.
def count(peri):
# The inner functio... |
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... | #Gambas | Gambas | Public Sub Form_Open()
Dim siCount As Short
Do
If siCount > 1000 Then Break
Inc siCount
Loop
Me.Close
End |
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #Racket | Racket |
> (require math)
> (matrix-qr (matrix [[12 -51 4]
[ 6 167 -68]
[-4 24 -41]]))
(array #[#[6/7 -69/175 -58/175] #[3/7 158/175 6/175] #[-2/7 6/35 -33/35]])
(array #[#[14 21 -14] #[0 175 -70] #[0 0 35]])
|
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #F.23 | F# |
// Prime triangle. Nigel Galloway: April 12th., 2022
let fN i (g,(e,l))=e|>Seq.map(fun n->let n=i n in (n::g,List.partition(i>>(=)n) l))
let rec fG n g=function 0->n|>Seq.map fst |x->fG(n|>Seq.collect(fN(if g then fst else snd)))(not g)(x-1)
let primeT row=fG [([1],([for g in {2..2..row-1} do if isPrime(g+1) then... |
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... | #ALGOL-M | ALGOL-M |
BEGIN
% COMPUTE P MOD Q %
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% COUNT, AND OPTIONALLY DISPLAY, PROPER DIVISORS OF N %
INTEGER FUNCTION DIVISORS(N, DISPLAY);
INTEGER N, DISPLAY;
BEGIN
INTEGER I, LIMIT, COUNT, START, DELTA;
IF MOD(N, 2) = 0 THEN
BEGIN
... |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is invol... | #Ada | Ada | with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Random_Distribution is
Trials : constant := 1_000_000;
type Outcome is (Aleph, Beth, Gimel, Daleth, He, Waw, Zayin, Heth);
Pr : constant array (Outcome) of Uniformly_Distributed :=
... |
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... | #Action.21 | Action! | SET EndProg=* |
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 ... | #BBC_BASIC | BBC BASIC | DIM Circle{x, y, r}
DIM Circles{(2)} = Circle{}
Circles{(0)}.x = 0 : Circles{(0)}.y = 0 : Circles{(0)}.r = 1
Circles{(1)}.x = 4 : Circles{(1)}.y = 0 : Circles{(1)}.r = 1
Circles{(2)}.x = 2 : Circles{(2)}.y = 4 : Circles{(2)}.r = 2
@% = &2030A
REM Solution for internal circle:... |
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 ... | #C | C | #include <stdio.h>
#include <tgmath.h>
#define VERBOSE 0
#define for3 for(int i = 0; i < 3; i++)
typedef complex double vec;
typedef struct { vec c; double r; } circ;
#define re(x) creal(x)
#define im(x) cimag(x)
#define cp(x) re(x), im(x)
#define CPLX "(%6.3f,%6.3f)"
#define CPLX3 CPLX" "CPLX" "CPLX
double cro... |
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... | #Julia | Julia |
prog = basename(Base.source_path())
println("This program file is \"", prog, "\".")
|
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... | #Kotlin | Kotlin | // version 1.0.6
// 'progname.kt' packaged as 'progname.jar'
fun main(args: Array<String>) {
println(System.getProperty("sun.java.command")) // may not exist on all JVMs
println(System.getProperty("java.vm.name"))
} |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Lingo | Lingo | -- libs
sieve = script("math.primes").new()
bigint = script("bigint").new()
cnt = 1000 * 100
primes = sieve.getNPrimes(cnt)
pr = 1
put "Primorial 0: " & pr
repeat with i = 1 to 9
pr = pr*primes[i]
put "Primorial " & i & ": " & pr
end repeat
pow10 = 10
repeat with i = 10 to cnt
pr = bigint.mul(pr, prim... |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Maple | Maple |
with(NumberTheory):
primorial := proc(n::integer)
local total := 1:
local count:
for count from 1 to n do
total *= ithprime(count):
end:
return total;
end proc:
primorialDigits := proc(n::integer)
local logSum := 0:
local count:
for count from 1 to n do
logSum += log10(ithprime(count)):
end:
return ... |
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,... | #Julia | Julia |
function primitiven{T<:Integer}(m::T)
1 < m || return T[]
m != 2 || return T[1]
!isprime(m) || return T[2:2:m-1]
rp = trues(m-1)
if isodd(m)
rp[1:2:m-1] = false
end
for p in keys(factor(m))
rp[p:p:m-1] = false
end
T[1:m-1][rp]
end
function pythagoreantripcount{T<:... |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Gema | Gema | Star Trek=@err{found a Star Trek reference\n}@abort |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Gnuplot | Gnuplot | problem=1
if (problem) {
exit gnuplot
} |
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #Raku | Raku | # sub householder translated from https://codereview.stackexchange.com/questions/120978/householder-transformation
use v6;
sub identity(Int:D $m --> Array of Array) {
my Array @M;
for 0 ..^ $m -> $i {
@M.push: [0 xx $m];
@M[$i; $i] = 1;
}
@M;
}
multi multiply(Array:D @A, @b where Arra... |
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #Go | Go | package main
import "fmt"
var canFollow [][]bool
var arrang []int
var bFirst = true
var pmap = make(map[int]bool)
func init() {
for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {
pmap[i] = true
}
}
func ptrs(res, n, done int) int {
ad := arrang[done-1]
if n-done <= 1... |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5... | #AppleScript | AppleScript | -- PROPER DIVISORS -----------------------------------------------------------
-- properDivisors :: Int -> [Int]
on properDivisors(n)
if n = 1 then
{1}
else
set realRoot to n ^ (1 / 2)
set intRoot to realRoot as integer
set blnPerfectSquare to intRoot = realRoot
-- is... |
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... | #ALGOL_68 | ALGOL 68 | INT trials = 1 000 000;
MODE LREAL = LONG REAL;
MODE ITEM = STRUCT(
STRING name,
INT prob count,
LREAL expect,
mapping
);
INT col width = 9;
FORMAT real repr = $g(-col width+1, 6)$,
item repr = $"Name: "g", Prob count: "g(0)", Expect: "f(real repr)", Mapping: ", f(real repr)l$;
[8]ITEM items ... |
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors | Primes - allocate descendants to their ancestors | The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers betw... | #11l | 11l | V maxsum = 99
F get_primes(max)
V lprimes = [2]
L(x) (3..max).step(2)
L(p) lprimes
I x % p == 0
L.break
L.was_no_break
lprimes.append(x)
R lprimes
V descendants = [[Int64]()] * (maxsum + 1)
V ancestors = [[Int64]()] * (maxsum + 1)
V primes = get_primes(maxsum)
... |
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... | #Ada | Ada | with Ada.Containers.Synchronized_Queue_Interfaces;
with Ada.Containers.Unbounded_Priority_Queues;
with Ada.Strings.Unbounded;
procedure Priority_Queues is
use Ada.Containers;
use Ada.Strings.Unbounded;
type Queue_Element is record
Priority : Natural;
Content : Unbounded_String;
end record;
... |
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 ... | #C.23 | C# |
using System;
namespace ApolloniusProblemCalc
{
class Program
{
static float rs = 0;
static float xs = 0;
static float ys = 0;
public static void Main(string[] args)
{
float gx1;
float gy1;
float gr1;
float gx2;
... |
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... | #langur | langur | writeln "script: ", _script
writeln "script args: ", _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... | #Lasso | Lasso | #!/usr/bin/lasso9
stdoutnl("Program: " + $argv->first) |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FoldList[Times, 1, Prime @ Range @ 9] |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Nickle | Nickle | library "prime_sieve.5c"
# For 1 million primes
# int val = 15485867;
int val = 1299743;
int start = millis();
int [*] primes = PrimeSieve::primes(val);
printf("%d primes (%d) in %dms\n", dim(primes), primes[dim(primes)-1], millis() - start);
int primorial(int n) {
if (n == 0) return 1;
if (n == 1) return 2... |
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,... | #Kotlin | Kotlin | // version 1.1.2
var total = 0L
var prim = 0L
var maxPeri = 0L
fun newTri(s0: Long, s1: Long, s2: Long) {
val p = s0 + s1 + s2
if (p <= maxPeri) {
prim++
total += maxPeri / p
newTri( s0 - 2 * s1 + 2 * s2, 2 * s0 - s1 + 2 * s2, 2 * s0 - 2 * s1 + 3 * s2)
newTri( s0 + 2 * s1 +... |
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... | #Go | Go | func main() {
if problem {
return
}
} |
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... | #Groovy | Groovy | if (problem) System.exit(intExitCode) |
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #Rascal | Rascal | import util::Math;
import Prelude;
import vis::Figure;
import vis::Render;
public rel[real,real,real] QRdecomposition(rel[real x, real y, real v] matrix){
//orthogonalcolumns
oc = domainR(matrix, {0.0});
for (x <- sort(toList(domain(matrix)-{0.0}))){
c = domainR(matrix, {x});
o = domainR(oc, {x-1});
for (n... |
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #J | J | is_prime=: 1&p:@(+/)
is_prime_triangle=: {{
NB. y is index into L and thus analogous to *a
p=. is_prime L{~y+0 1
if. N=y do. p return.end.
i=. Y=. y+1
if. p do. if. is_prime_triangle Y do. 1 return.end.end.
while. M>i=.i+2 do.
if. is_prime L{~y,i do.
L=: (L{~Y,i) (i,Y)} L
if. is_prime_tria... |
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... | #Arc | Arc |
;; Given num, return num and the list of its divisors
(= divisor (fn (num)
(= dlist '())
(when (is 1 num) (= dlist '(1 0)))
(when (is 2 num) (= dlist '(2 1)))
(unless (or (is 1 num) (is 2 num))
(up i 1 (+ 1 (/ num 2))
(if (is 0 (mod num i))
(push i dlist)))
(= dlist (cons num dlist))... |
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... | #AppleScript | AppleScript | use AppleScript version "2.5" -- Mac OS X 10.11 (El Capitan) or later.
use framework "Foundation"
use framework "GameplayKit"
on probabilisticChoices(mapping, picks)
script o
property mapping : {}
end script
-- Make versions of the mapping records with additional 'actual' properties …
set ma... |
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors | Primes - allocate descendants to their ancestors | The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers betw... | #AutoHotkey | AutoHotkey | #Warn
#SingleInstance force
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetBatchLines, -1
SetFormat, IntegerFast, D
MaxPrime = 99 ; upper bound for the prime factors
Ma... |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program priorqueue.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ NBMAXIELEMENTS, 100
/*******************************************/
/* Structures ... |
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 ... | #CoffeeScript | CoffeeScript |
class Circle
constructor: (@x, @y, @r) ->
apollonius = (c1, c2, c3, s1=1, s2=1, s3=1) ->
[x1, y1, r1] = [c1.x, c1.y, c1.r]
[x2, y2, r2] = [c2.x, c2.y, c2.r]
[x3, y3, r3] = [c3.x, c3.y, c3.r]
sq = (n) -> n*n
v11 = 2*x2 - 2*x1
v12 = 2*y2 - 2*y1
v13 = sq(x1) - sq(x2) + sq(y1) - sq(y2) - sq(r1) + sq... |
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... | #Liberty_BASIC | Liberty BASIC |
nSize = _MAX_PATH + 2
lpFilename$ = space$(nSize); chr$(0)
calldll #kernel32, "GetModuleFileNameA", _
hModule as ulong, _
lpFilename$ as ptr, _
nSize as ulong, _
result as ulong
lpFilename$ = left$(lpFilename$,result)
print "Path to LB exe"
print lpFilename$
prin... |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Nim | Nim | import times
let t0 = cpuTime()
####################################################################################################
# Build list of primes.
const
NPrimes = 1_000_000
N = 16 * NPrimes
var sieve: array[(N - 1) div 2 + 1, bool] # False (default) means prime.
for i, composite in sieve:
if... |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #PARI.2FGP | PARI/GP | nthprimorial(n)=prod(i=1,n,prime(i));
vector(10,i,nthprimorial(i-1))
vector(5,n,#Str(nthprimorial(10^n)))
#Str(nthprimorial(10^6)) |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime,... | #Lasso | Lasso | // Brute Force: Too slow for large numbers
define num_pythagorean_triples(max_perimeter::integer) => {
local(max_b) = (#max_perimeter / 3)*2
return (
with a in 1 to (#max_b - 1)
sum integer(
with b in (#a + 1) to #max_b
let c = math_sqrt(#a*#a + #b*#b)
where #c == integer(... |
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... | #GW-BASIC | GW-BASIC | 10 IF 1 THEN STOP |
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... | #Haskell | Haskell | import Control.Monad
import System.Exit
when problem do
exitWith ExitSuccess -- success
exitWith (ExitFailure integerErrorCode) -- some failure with code
exitSuccess -- success; in GHC 6.10+
exitFailure -- generic failure |
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #SAS | SAS | /* See http://support.sas.com/documentation/cdl/en/imlug/63541/HTML/default/viewer.htm#imlug_langref_sect229.htm */
proc iml;
a={12 -51 4,6 167 -68,-4 24 -41};
print(a);
call qr(q,r,p,d,a);
print(q);
print(r);
quit;
/*
a
12 -51 4
6 167 -68
... |
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #Java | Java | public class PrimeTriangle {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 2; i <= 20; ++i) {
int[] a = new int[i];
for (int j = 0; j < i; ++j)
a[j] = j + 1;
if (findRow(a, 0, i))
pri... |
http://rosettacode.org/wiki/Prime_conspiracy | Prime conspiracy | A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of ... | #11l | 11l | V limit = 1000000
V k = limit
V n = k * 17
V primes = [1B] * n
primes[0] = primes[1] = 0B
L(i) 2..Int(sqrt(n))
I !primes[i]
L.continue
L(j) (i * i .< n).step(i)
primes[j] = 0B
DefaultDict[(Int, Int), Int] trans_map
V prev = -1
L(i) 0 .< n
I primes[i]
I prev != -1
trans_map[(pre... |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program proFactor.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/****************************************... |
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... | #Arturo | Arturo | nofTrials: 10000
probabilities: #[
aleph: to :rational [1 5]
beth: to :rational [1 6]
gimel: to :rational [1 7]
daleth: to :rational [1 8]
he: to :rational [1 9]
waw: to :rational [1 10]
zayin: to :rational [1 11]
heth: to :rational [1759 27720]
]
samples: #[]
loop 1..nofTrials 'x [
... |
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors | Primes - allocate descendants to their ancestors | The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers betw... | #C | C | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXPRIME 99 // upper bound for the prime factors
#define MAXPARENT 99 // greatest parent number
#define NBRPRIMES 30 // max number of prime factors
#define NBRANCESTORS 10 // max number of parent's ancestors
FILE *... |
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... | #AutoHotkey | AutoHotkey | ;-----------------------------------
PQ_TopItem(Queue,Task:=""){ ; remove and return top priority item
TopPriority := PQ_TopPriority(Queue)
for T, P in Queue
if (P = TopPriority) && ((T=Task)||!Task)
return T , Queue.Remove(T)
return 0
}
;-----------------------------------
PQ_AddTask(Queue,Task,Priority){... |
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 ... | #D | D | import std.stdio, std.math;
immutable struct Circle { double x, y, r; }
enum Tangent { externally, internally }
/**
Solves the Problem of Apollonius (finding a circle tangent to three
other circles in the plane).
Params:
c1 = First circle of the problem.
c2 = Second circle of the problem.
c3 = Third circle ... |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Lingo | Lingo | put _player.applicationName
-- "lsw.exe"
put _movie.name
-- "lsw_win_d11.dir" |
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... | #LLVM | LLVM | $ make
llvm-as scriptname.ll
llc -disable-cfi scriptname.bc
gcc -o scriptname scriptname.s
./scriptname
Program: ./scriptname |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Pascal | Pascal | {$H+}
uses
sysutils,mp_types,mp_base,mp_prime,mp_numth;
var
x: mp_int;
t0,t1: TDateTime;
s: AnsiString;
var
i,cnt : NativeInt;
ctx :TPrimeContext;
begin
mp_init(x);
cnt := 1;
i := 2;
FindFirstPrime32(i,ctx);
i := 10;
t0 := time;
repeat
repeat
FindNextPrime32(ctx);
inc(cnt);
... |
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,... | #Liberty_BASIC | Liberty BASIC |
print time$()
for power =1 to 6
perimeterLimit =10^power
upperBound =int( 1 +perimeterLimit^0.5)
primitives =0
triples =0
extras =0 ' will count the in-range multiples of any primitive
for m =2 to upperBound
for n =1 +( m mod 2 =1) to m -1 step 2
... |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #HicEst | HicEst | ALARM( 999 ) |
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... | #Icon_and_Unicon | Icon and Unicon | exit(i) # terminates the program setting an exit code of i
stop(x1,x2,..) # terminates the program writing out x1,..; if any xi is a file writing switches to that file
runerr(i,x) # terminates the program with run time error 'i' for value 'x' |
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #Scala | Scala | import java.io.{PrintWriter, StringWriter}
import Jama.{Matrix, QRDecomposition}
object QRDecomposition extends App {
val matrix =
new Matrix(
Array[Array[Double]](Array(12, -51, 4),
Array(6, 167, -68),
Array(-4, 24, -41)))
val d = new QRDecomposition(matrix)
def toString(m: Matrix... |
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #Julia | Julia | using Combinatorics, Primes
function primetriangle(nrows::Integer)
nrows < 2 && error("number of rows requested must be > 1")
pmask, spinlock = primesmask(2 * (nrows + 1)), Threads.SpinLock()
counts, rowstrings = [1; zeros(Int, nrows - 1)], ["" for _ in 1:nrows]
for r in 2:nrows
@Threads.threa... |
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory 'is_prime';
use List::MoreUtils qw(zip slideatatime);
use Algorithm::Combinatorics qw(permutations);
say '1 2';
my @count = (0, 0, 1);
for my $n (3..17) {
my @even_nums = grep { 0 == $_ % 2 } 2..$n-1;
my @odd_nums = grep { 1 == $_ % 2 } 3..$n-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 ... | #ALGOL_68 | ALGOL 68 | # extend SET, CLEAR and ELEM to operate on rows of BITS #
OP SET = ( INT n, REF[]BITS b )REF[]BITS:
BEGIN
INT w = n OVER bits width;
b[ w ] := ( ( 1 + ( n MOD bits width ) ) SET b[ w ] );
b
END # SET # ;
OP CLEAR = ( INT n, REF[]BITS b )REF[]BITS:
BEGIN
INT w = n... |
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... | #Arturo | Arturo | properDivisors: function [x] ->
(factors x) -- x
loop 1..10 'x ->
print ["proper divisors of" x "=>" properDivisors x]
maxN: 0
maxProperDivisors: 0
loop 1..20000 'x [
pd: size properDivisors x
if maxProperDivisors < pd [
maxN: x
maxProperDivisors: pd
]
]
print ["The number wi... |
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... | #AutoHotkey | AutoHotkey | s1 := "aleph", p1 := 1/5.0 ; Input
s2 := "beth", p2 := 1/6.0
s3 := "gimel", p3 := 1/7.0
s4 := "daleth", p4 := 1/8.0
s5 := "he", p5 := 1/9.0
s6 := "waw", p6 := 1/10.0
s7 := "zayin", p7 := 1/11.0
s8 := "heth", p8 := 1-p1-p2-p3-p4-p5-p6-p7
n := 8, r0 := 0, r%n% := 1 ... |
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors | Primes - allocate descendants to their ancestors | The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers betw... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <vector>
typedef unsigned long long integer;
// returns all ancestors of n. n is not its own ancestor.
std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {
std::vector<integer> result;
for (integer a = ancestor[n]; a != 0 && ... |
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert... | #Axiom | Axiom | )abbrev Domain ORDKE OrderedKeyEntry
OrderedKeyEntry(Key:OrderedSet,Entry:SetCategory): Exports == Implementation where
Exports == OrderedSet with
construct: (Key,Entry) -> %
elt: (%,"key") -> Key
elt: (%,"entry") -> Entry
Implementation == add
Rep := Record(k:Key,e:Entry)
x,y: %
construct(a... |
http://rosettacode.org/wiki/Problem_of_Apollonius | Problem of Apollonius |
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the ... | #Dyalect | Dyalect | type Circle(Array center, Float radius) with Lookup
func Circle.ToString() =>
"Circle[x=\(this.center[0]),y=\(this.center[1]),r=\(this.radius)]"
func solveApollonius(Circle c1, Circle c2, Circle c3, Float s1, Float s2, Float s3) {
let x1 = c1.center[0]
let y1 = c1.center[1]
let r1 = c1.radius
let ... |
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 ... | #Elixir | Elixir | defmodule Circle do
def apollonius(c1, c2, c3, s1, s2, s3) do
{x1, y1, r1} = c1
{w12, w13, w14} = calc(c1, c2, s1, s2)
{u22, u23, u24} = calc(c2, c3, s2, s3)
{w22, w23, w24} = {u22 - w12, u23 - w13, u24 - w14}
p = -w23 / w22
q = w24 / w22
m = -w12 * p - w13
n = w14 - w12 * q
a ... |
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... | #Lua | Lua | #!/usr/bin/env lua
function main(arg)
local program = arg[0]
print("Program: " .. program)
end
if type(package.loaded[(...)]) ~= "userdata" then
main(arg)
else
module(..., package.seeall)
end |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Declare GetModuleFileName Lib "kernel32.GetModuleFileNameW" {Long hModule, &lpFileName$, Long nSize}
a$=string$(chr$(0), 260)
namelen=GetModuleFileName(0, &a$, 260)
a$=left$(a$, namelen)
\\ normally m2000.exe is the caller of m2000.dll, the activeX script language
... |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Perl | Perl | use ntheory qw(pn_primorial);
say "First ten primorials: ", join ", ", map { pn_primorial($_) } 0..9;
say "primorial(10^$_) has ".(length pn_primorial(10**$_))." digits" for 1..6; |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Phix | Phix | with javascript_semantics
include mpfr.e
function vecprod(sequence s)
if s={} then
s = {mpz_init(1)}
else
for i=1 to length(s) do
s[i] = mpz_init(s[i])
end for
while length(s)>1 do
for i=1 to floor(length(s)/2) do
mpz_mul(s[i],s[i],s[-i]... |
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,... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | pythag[n_]:=Block[{soln=Solve[{a^2+b^2==c^2,a+b+c<=n,0<a<b<c},{a,b,c},Integers]},{Length[soln],Count[GCD[a,b]/.soln,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... | #J | J | 2!:55^:] condition |
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... | #Java | Java | if(problem){
System.exit(integerErrorCode);
//conventionally, error code 0 is the code for "OK",
// while anything else is an actual problem
//optionally: Runtime.getRuntime().exit(integerErrorCode);
} |
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #SequenceL | SequenceL | import <Utilities/Math.sl>;
import <Utilities/Sequence.sl>;
import <Utilities/Conversion.sl>;
main :=
let
qrTest := [[12.0, -51.0, 4.0],
[ 6.0, 167.0, -68.0],
[-4.0, 24.0, -41.0]];
qrResult := qr(qrTest);
x := 1.0*(0 ... 10);
y := 1.0*[1... |
http://rosettacode.org/wiki/Prime_triangle | Prime triangle | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem... | #Phix | Phix | with javascript_semantics
atom t0 = time()
sequence can_follow, arrang
bool bFirst = true
function ptrs(integer res, n, done)
-- prime triangle recursive sub-procedure
-- on entry, arrang[done] is set and arrang[$]==n.
-- find something/everything that fits between them.
integer ad = arrang[done]
i... |
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
| #11l | 11l | F is_wprime(Int64 n)
R n > 1 & (n == 2 | (n % 2 & (factorial(n - 1) + 1) % n == 0))
V c = 20
print(‘Primes under #.:’.format(c), end' "\n ")
print((0 .< c).filter(n -> is_wprime(n))) |
http://rosettacode.org/wiki/Pragmatic_directives | Pragmatic directives | Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate... | #6502_Assembly | 6502 Assembly | NMOS_6502 equ 1
ifdef NMOS_6502
txa
pha
else
phx ;NMOS_6502 doesn't have this instruction.
endif ; every ifdef/ifndef needs an endif |
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 ... | #AppleScript | AppleScript | on isPrime(n)
if ((n < 4) or (n is 5)) then return (n > 1)
if ((n mod 2 = 0) or (n mod 3 = 0) or (n mod 5 = 0)) then return false
repeat with i from 7 to (n ^ 0.5) div 1 by 30
if ((n mod i = 0) or (n mod (i + 4) = 0) or (n mod (i + 6) = 0) or ¬
(n mod (i + 10) = 0) or (n mod (i + 12) = 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... | #AutoHotkey | AutoHotkey | proper_divisors(n) {
Array := []
if n = 1
return Array
Array[1] := true
x := Floor(Sqrt(n))
loop, % x+1
if !Mod(n, i:=A_Index+1) && (floor(n/i) < n)
Array[floor(n/i)] := true
Loop % n/x
if !Mod(n, i:=A_Index+1) && (i < n)
Array[i] := true
return Array
} |
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.