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 decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#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.copysign(np.linalg.norm(a), a[0]))
v[0] = 1
H = np.eye(a.shape[0])
H -= (2 / np.dot(v, v)) * np.dot(v[:, None], v[None, :])
return H
# task 1: show qr decomp of wp example
a = np.array(((
(12, -51, 4),
( 6, 167, -68),
(-4, 24, -41),
)))
q, r = qr(a)
print('q:\n', q.round(6))
print('r:\n', r.round(6))
# task 2: use qr decomp for polynomial regression example
def polyfit(x, y, n):
return lsqr(x[:, None]**np.arange(n + 1), y.T)
def lsqr(a, b):
q, r = qr(a)
_, n = r.shape
return np.linalg.solve(r[:n, :], np.dot(q.T, b)[:n])
x = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
y = np.array((1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321))
print('\npolyfit:\n', polyfit(x, y, 2))
|
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 arrangements of 1 to S meeting these requirements.
|
#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, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};
return isprime[n];
}
void swap(unsigned int* a, size_t i, size_t j) {
unsigned int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
bool prime_triangle_row(unsigned int* a, size_t length) {
if (length == 2)
return is_prime(a[0] + a[1]);
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
if (prime_triangle_row(a + 1, length - 1))
return true;
swap(a, i, 1);
}
}
return false;
}
int prime_triangle_count(unsigned int* a, size_t length) {
int count = 0;
if (length == 2) {
if (is_prime(a[0] + a[1]))
++count;
} else {
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
count += prime_triangle_count(a + 1, length - 1);
swap(a, i, 1);
}
}
}
return count;
}
void print(unsigned int* a, size_t length) {
if (length == 0)
return;
printf("%2u", a[0]);
for (size_t i = 1; i < length; ++i)
printf(" %2u", a[i]);
printf("\n");
}
int main() {
clock_t start = clock();
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (prime_triangle_row(a, n))
print(a, n);
}
printf("\n");
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (n > 2)
printf(" ");
printf("%d", prime_triangle_count(a, n));
}
printf("\n");
clock_t end = clock();
double duration = (end - start + 0.0) / CLOCKS_PER_SEC;
printf("\nElapsed time: %f seconds\n", duration);
return 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, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#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
(if First**2 > N or First = N then None
elsif (N mod First)=0 then
(if First = 1 or First*First = N
then Add(One(First), Process(N, First+1))
else Add(One(First),
Add(One((N/First)), Process(N, First+1))))
else Process(N, First+1));
end Generic_Divisors;
|
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 insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#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 example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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 new function here, just to ensure if anyone is having any problems then to make sure they are using the correct library version
If (Gdip_LibraryVersion() < 1.30)
{
MsgBox, 48, version error!, Please download the latest version of the gdi+ library
ExitApp
}
x1:=300,y1:=500,r1:=50,x2:=200,y2:=200,r2:=150,x3:=600,y3:=400,r3:=100,s1:=-1,s2:=-1,s3:=-1,xs:=0,ys:=0,rs:=0
, Apollonius(x1,y1,r1,x2,y2,r2,x3,y3,r3,s1,s2,s3,xs,ys,rs)
, Width:=max(x1+r1 "," x2+r2 "," x3+r3 "," xs+rs)*1.1
, Height:=max(y1+r1 "," y2+r2 "," y3+r3 "," ys+rs)*1.1
Gui, -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs
Gui, Show
hwnd1 := WinExist()
, hbm := CreateDIBSection(Width, Height)
, hdc := CreateCompatibleDC()
, obm := SelectObject(hdc, hbm)
, G := Gdip_GraphicsFromHDC(hdc)
, Gdip_SetSmoothingMode(G, 4)
, bWhite := Gdip_BrushCreateSolid(0xffffffff)
, Gdip_FillRectangle(G, bWhite, 0, 0, Width, Height)
, pRed := Gdip_CreatePen(0x88ff0000, 3)
, pGreen := Gdip_CreatePen(0x8800ff00, 3)
, pBlue := Gdip_CreatePen(0x880000ff, 3)
, pBlack := Gdip_CreatePen(0x88000000, 3)
, Gdip_DrawCircle(G, pRed, x1, y1, r1)
, Gdip_DrawCircle(G, pGreen, x2, y2, r2)
, Gdip_DrawCircle(G, pBlue, x3, y3, r3)
, Gdip_DrawCircle(G, pBlack, xs, ys, rs)
, Gdip_DeletePen(pRed)
, Gdip_DeletePen(pGreen)
, Gdip_DeletePen(pBlue)
, Gdip_DeletePen(pBlack)
, UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
Return
GuiEscape:
GuiClose:
Exit:
SelectObject(hdc, obm)
, DeleteObject(hbm)
, DeleteDC(hdc)
, Gdip_DeleteGraphics(G)
, Gdip_Shutdown(pToken)
ExitApp
Apollonius(x1=300,y1=500,r1=50,x2=200,y2=200,r2=150,x3=600,y3=400,r3=100,s1=1,s2=1,s3=1,ByRef xs=0, ByRef ys=0, ByRef rs=0) {
v11 := 2*x2 - 2*x1
v12 := 2*y2 - 2*y1
v13 := x1**2 - x2**2 + y1**2 - y2**2 - r1**2 + r2**2
v14 := 2*s2*r2 - 2*s1*r1
v21 := 2*x3 - 2*x2
v22 := 2*y3 - 2*y2
v23 := x2**2 - x3**2 + y2**2 - y3**2 - r2**2 + r3**2
v24 := 2*s3*r3 - 2*s2*r2
w12 := v12/v11
w13 := v13/v11
w14 := v14/v11
w22 := v22/v21 - w12
w23 := v23/v21 - w13
w24 := v24/v21 - w14
p := -w23/w22
q := w24/w22
m := -w12*p - w13
n := w14 - w12*q
a := n**2 + q**2 - 1
b := 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1
c := x1**2 + m**2 - 2*m*x1 + p**2 + y1**2 - 2*p*y1 - r1**2
d := b**2 - 4*a*c
rs := (-b - d**0.5)/(2*a)
xs := m + n*rs
ys := p + q*rs
}
; from http://rosettacode.org/wiki/Greatest_element_of_a_list#AutoHotkey
max(list) {
Loop Parse, list, `,
x := x < A_LoopField ? A_LoopField : x
Return x
}
; Gdip helper function
Gdip_DrawCircle(G, pPen, x, y, r) {
Return Gdip_DrawEllipse(G, pPen, x-r, y-r, r*2, r*2)
}
|
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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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:",
([10, 100, 1000, 10000, 100000] as $sample
| limit($sample|length;
foreach primes as $p ([0,1]; # [index, primorial]
.[0]+=1 | .[1] *= $p;
select(.[0]|IN($sample[])) | [.[0], (.[1]|tostring|length)] ) ))
|
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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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 length $plen digits in base 10.")
end
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#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)
);
return xs.flatMap(
x => xs.slice(x).flatMap(
y => xs.slice(y).flatMap(
z => ((x + y + z <= maxPerim) &&
((x * x) + (y * y) === z * z) &&
p(x, y, z)) ? [
[x, y, z]
] : []
)
)
).length;
};
// ---------------------- TEST -----------------------
const main = () => [10, 100, 1000]
.map(n => ({
maxPerimeter: n,
triples: pythTripleCount(() => true)(n),
primitives: pythTripleCount(
(x, y) => gcd(x)(y) === 1
)(n)
}));
// ---------------- GENERIC FUNCTIONS ----------------
// abs :: Num -> Num
const abs =
// Absolute value of a given number
// without the sign.
x => 0 > x ? (
-x
) : x;
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// gcd :: Integral a => a -> a -> a
const gcd = x =>
y => {
const zero = x.constructor(0);
const go = (a, b) =>
zero === b ? (
a
) : go(b, a % b);
return go(abs(x), abs(y));
};
// MAIN ---
return main();
})();
|
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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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 decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#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 squares
a <- cbind(x, x^2)
lsfit(a, y)$coefficients
# using a linear model
xx <- x*x
m <- lm(y ~ x + xx)
coef(m)
|
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 arrangements of 1 to S meeting these requirements.
|
#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 (std::distance(begin, end) == 2)
return is_prime(*begin + *(begin + 1));
for (auto i = begin + 1; i + 1 != end; ++i) {
if (is_prime(*begin + *i)) {
std::iter_swap(i, begin + 1);
if (prime_triangle_row(begin + 1, end))
return true;
std::iter_swap(i, begin + 1);
}
}
return false;
}
template <typename Iterator>
void prime_triangle_count(Iterator begin, Iterator end, int& count) {
if (std::distance(begin, end) == 2) {
if (is_prime(*begin + *(begin + 1)))
++count;
return;
}
for (auto i = begin + 1; i + 1 != end; ++i) {
if (is_prime(*begin + *i)) {
std::iter_swap(i, begin + 1);
prime_triangle_count(begin + 1, end, count);
std::iter_swap(i, begin + 1);
}
}
}
template <typename Iterator>
void print(Iterator begin, Iterator end) {
if (begin == end)
return;
auto i = begin;
std::cout << std::setw(2) << *i++;
for (; i != end; ++i)
std::cout << ' ' << std::setw(2) << *i;
std::cout << '\n';
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int n = 2; n < 21; ++n) {
std::vector<unsigned int> v(n);
std::iota(v.begin(), v.end(), 1);
if (prime_triangle_row(v.begin(), v.end()))
print(v.begin(), v.end());
}
std::cout << '\n';
for (unsigned int n = 2; n < 21; ++n) {
std::vector<unsigned int> v(n);
std::iota(v.begin(), v.end(), 1);
int count = 0;
prime_triangle_count(v.begin(), v.end(), count);
if (n > 2)
std::cout << ' ';
std::cout << count;
}
std::cout << '\n';
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\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, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#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 n #
# if n = 1, 0 or -1, we return no divisors #
PROC proper divisors = ( INT n )REF DIVISORLIST:
BEGIN
REF DIVISORLIST result := nil divisor list;
REF DIVISORLIST end list := result;
INT abs n = ABS n;
IF abs n > 1 THEN
# build the list of divisors backeards, so they are #
# returned in ascending order #
INT root n = ENTIER sqrt( abs n );
FOR d FROM root n BY -1 TO 2 DO
IF abs n MOD d = 0 THEN
# found another divisor #
result := HEAP DIVISORLIST
:= DIVISORLIST( d, result );
IF end list IS nil divisor list THEN
# first result #
end list := result
FI;
IF d * d /= n THEN
# add the other divisor to the end of #
# the list #
next OF end list := HEAP DIVISORLIST
:= DIVISORLIST( abs n OVER d, nil divisor list );
end list := next OF end list
FI
FI
OD;
# 1 is always a proper divisor of numbers > 1 #
result := HEAP DIVISORLIST
:= DIVISORLIST( 1, result )
FI;
result
END # proper divisors # ;
# returns the number of divisors in a DIVISORLIST #
PROC count divisors = ( REF DIVISORLIST list )INT:
BEGIN
INT result := 0;
REF DIVISORLIST divisors := list;
WHILE divisors ISNT nil divisor list DO
result +:= 1;
divisors := next OF divisors
OD;
result
END # count divisors # ;
# find the proper divisors of 1 : 10 #
FOR n TO 10 DO
REF DIVISORLIST divisors := proper divisors( n );
print( ( "Proper divisors of: ", whole( n, -2 ), ": " ) );
WHILE divisors ISNT nil divisor list DO
print( ( " ", whole( divisor OF divisors, 0 ) ) );
divisors := next OF divisors
OD;
print( ( newline ) )
OD;
# find the first/only number in 1 : 20 000 with the most divisors #
INT max number = 20 000;
INT max divisors := 0;
INT has max divisors := 0;
INT with max divisors := 0;
FOR d TO max number DO
INT divisor count = count divisors( proper divisors( d ) );
IF divisor count > max divisors THEN
# found a number with more divisors than the previous max #
max divisors := divisor count;
has max divisors := d;
with max divisors := 1
ELIF divisor count = max divisors THEN
# found another number with that many divisors #
with max divisors +:= 1
FI
OD;
print( ( whole( has max divisors, 0 )
, " is the "
, IF with max divisors < 2 THEN "only" ELSE "first" FI
, " number upto "
, whole( max number, 0 )
, " with "
, whole( max divisors, 0 )
, " divisors"
, newline
) )
|
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 insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#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 "../includeConstantesARM64.inc"
.equ NBMAXIELEMENTS, 100
/*******************************************/
/* Structures */
/********************************************/
/* example structure item */
.struct 0
item_priority: // priority
.struct item_priority + 8
item_address: // string address
.struct item_address + 8
item_fin:
/* example structure heap */
.struct 0
heap_size: // heap size
.struct heap_size + 8
heap_items: // structure of items
.struct heap_items + (item_fin * NBMAXIELEMENTS)
heap_fin:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEmpty: .asciz "Empty queue. \n"
szMessNotEmpty: .asciz "Not empty queue. \n"
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .asciz "Priority : @ : @ \n" // message result
szString1: .asciz "Clear drains"
szString2: .asciz "Feed cat"
szString3: .asciz "Make tea"
szString4: .asciz "Solve RC tasks"
szString5: .asciz "Tax return"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
sZoneConv: .skip 24
Queue1: .skip heap_fin // queue memory place
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrQueue1 // queue structure address
bl isEmpty
cbz x0,1f
ldr x0,qAdrszMessEmpty
bl affichageMess // display message empty
b 2f
1:
ldr x0,qAdrszMessNotEmpty
bl affichageMess // display message not empty
2:
// init item 1
ldr x0,qAdrQueue1 // queue structure address
mov x1,#3 // priority
ldr x2,qAdrszString1
bl pushQueue // add item in queue
cmp x0,#-1 // error ?
beq 99f
ldr x0,qAdrQueue1 // queue structure address
bl isEmpty
cbz x0,3f // not empty
ldr x0,qAdrszMessEmpty
bl affichageMess // display message empty
b 4f
3:
ldr x0,qAdrszMessNotEmpty
bl affichageMess // display message not empty
4:
// init item 2
ldr x0,qAdrQueue1 // queue structure address
mov x1,#4 // priority
ldr x2,qAdrszString2
bl pushQueue // add item in queue
cmp x0,#-1 // error ?
beq 99f
// init item 3
ldr x0,qAdrQueue1 // queue structure address
mov x1,#5 // priority
ldr x2,qAdrszString3
bl pushQueue // add item in queue
cmp x0,#-1 // error ?
beq 99f
// init item 4
ldr x0,qAdrQueue1 // queue structure address
mov x1,#1 // priority
ldr x2,qAdrszString4
bl pushQueue // add item in queue
cmp x0,#-1 // error ?
beq 99f
// init item 5
ldr x0,qAdrQueue1 // queue structure address
mov x1,#2 // priority
ldr x2,qAdrszString5
bl pushQueue // add item in queue
cmp x0,#-1 // error ?
beq 99f
5:
ldr x0,qAdrQueue1 // queue structure address
bl popQueue // return item
cmp x0,#-1 // end ?
beq 100f
mov x2,x1 // save string address
ldr x1,qAdrsZoneConv // conversion priority
bl conversion10 // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
mov x1,x2 // string address
bl strInsertAtCharInc
bl affichageMess // display message
b 5b // loop
99: // error
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrQueue1: .quad Queue1
qAdrszString1: .quad szString1
qAdrszString2: .quad szString2
qAdrszString3: .quad szString3
qAdrszString4: .quad szString4
qAdrszString5: .quad szString5
qAdrszMessError: .quad szMessError
qAdrszMessEmpty: .quad szMessEmpty
qAdrszMessNotEmpty: .quad szMessNotEmpty
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
//qAdrsMessPriority: .quad sMessPriority
qAdrsZoneConv: .quad sZoneConv
/******************************************************************/
/* test if queue empty */
/******************************************************************/
/* x0 contains the address of queue structure */
isEmpty:
stp x1,lr,[sp,-16]! // save registres
ldr x1,[x0,#heap_size] // heap size
cmp x1,#0
cset x0,eq
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* add item in queue */
/******************************************************************/
/* x0 contains the address of queue structure */
/* x1 contains the priority of item */
/* x2 contains the string address */
pushQueue:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
ldr x3,[x0,#heap_size] // heap size
cbnz x3,1f // heap empty ?
add x4,x0,#heap_items // address of item structure
str x1,[x4,#item_priority] // store in first item
str x2,[x4,#item_address]
mov x3,#1 // heap size
str x3,[x0,#heap_size] // new heap size
b 100f
1:
mov x4,x3 // maxi index
lsr x5,x4,#1 // current index = maxi / 2
mov x8,x1 // save priority
mov x9,x2 // save string address
2: // insertion loop
cmp x4,#0 // end loop ?
ble 3f
mov x6,#item_fin // item size
madd x6,x5,x6,x0 // item shift
add x6,x6,#heap_items // compute address item
ldr x7,[x6,#item_priority] // load priority
cmp x7,x8 // compare priority
ble 3f // <= end loop
mov x1,x4 // last index
mov x2,x5 // current index
bl exchange
mov x4,x5 // last index = current index
lsr x5,x5,#1 // current index / 2
b 2b
3: // store item at last index find
mov x6,#item_fin // item size
madd x6,x4,x6,x0 // item shift
add x6,x6,#heap_items // item address
str x8,[x6,#item_priority]
str x9,[x6,#item_address]
add x3,x3,#1 // increment heap size
cmp x3,#NBMAXIELEMENTS // maxi ?
bge 99f // yes -> error
str x3,[x0,#heap_size] // store new size
b 100f
99:
mov x0,#-1 // error
100:
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* swap two elements of table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first index */
/* x2 contains the second index */
exchange:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
add x5,x0,#heap_items // address items begin
mov x3,#item_fin // item size
madd x4,x1,x3,x5 // compute item 1 address
madd x6,x2,x3,x5 // compute item 2 address
ldr x5,[x4,#item_priority] // exchange
ldr x3,[x6,#item_priority]
str x3,[x4,#item_priority]
str x5,[x6,#item_priority]
ldr x5,[x4,#item_address]
ldr x3,[x6,#item_address]
str x5,[x6,#item_address]
str x3,[x4,#item_address]
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* move one element of table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the origin index */
/* x2 contains the destination index */
moveItem:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
add x5,x0,#heap_items // address items begin
mov x3,#item_fin // item size
madd x4,x1,x3,x5 // compute item 1 address
madd x6,x2,x3,x5 // compute item 2 address
ldr x5,[x4,#item_priority] // exchange
str x5,[x6,#item_priority]
ldr x5,[x4,#item_address]
str x5,[x6,#item_address]
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* pop queue */
/******************************************************************/
/* x0 contains the address of queue structure */
/* x0 return priority */
/* x1 return string address */
popQueue:
stp x10,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
mov x1,x0 // save address queue
bl isEmpty // control if empty queue
cmp x0,#1 // yes -> error
beq 99f
mov x0,x1 // restaur address queue
add x4,x0,#heap_items // address of item structure
ldr x8,[x4,#item_priority] // save priority first item
ldr x9,[x4,#item_address] // save address string first item
ldr x3,[x0,#heap_size] // heap size
sub x7,x3,#1 // last item
mov x1,x7
mov x2,#0 // first item
bl moveItem // move last item in first item
cmp x7,#1 // one only item ?
beq 10f // yes -> end
mov x4,#0 // first index
1:
cmp x4,x7 // = last index
bge 10f // yes -> end
mov x5,x7 // last index
cmp x4,#0 // init current index
mov x6,#1 // = 1
lsl x1,x4,#1 // else = first index * 2
csel x6,x6,x1,eq
cmp x6,x7 // current index > last index
bgt 2f // yes
// no compar priority current item last item
mov x1,#item_fin
madd x1,x6,x1,x0
add x1,x1,#heap_items // address of current item structure
ldr x1,[x1,#item_priority]
mov x10,#item_fin
madd x10,x5,x10,x0
add x10,x10,#heap_items // address of last item structure
ldr x10,[x10,#item_priority]
cmp x1,x10
csel x5,x6,x5,lt
2:
add x10,x6,#1 // increment current index
cmp x10,x7 // end ?
bgt 3f // yes
mov x1,#item_fin // no compare priority
madd x1,x10,x1,x0
add x1,x1,#heap_items // address of item structure
ldr x1,[x1,#item_priority]
mov x2,#item_fin
madd x2,x5,x2,x0
add x2,x2,#heap_items // address of item structure
ldr x2,[x2,#item_priority]
cmp x1,x2
csel x5,x10,x5,lt
3:
mov x1,x5 // move item
mov x2,x4
bl moveItem
mov x4,x5
b 1b // and loop
10:
sub x3,x3,#1
str x3,[x0,#heap_size] // new heap size
mov x0,x8 // return priority
mov x1,x9 // return string address
b 100f
99:
mov x0,#-1 // error
100:
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x10,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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 example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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$, 19, 1))
x3 = int(mid(c3$, 3, 1)): y3 = int(mid(c3$, 11, 1)): r3 = int(mid(c3$, 19, 1))
v11 = 2 * x2 - 2 * x1
v12 = 2 * y2 - 2* y1
v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2
v14 = 2 * s2 * r2 - 2 * s1 * r1
v21 = 2 * x3 - 2 * x2
v22 = 2 * y3 - 2 * y2
v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3
v24 = 2 * s3 * r3 - 2 * s2 * r2
w12 = v12 / v11
w13 = v13 / v11
w14 = v14 / v11
w22 = v22 / v21 - w12
w23 = v23 / v21 - w13
w24 = v24 / v21 - w14
P = 0 - w23 / w22
Q = w24 / w22
M = 0 - w12 * P - w13
N = w14 - w12 * Q
a = N * N + Q * Q - 1
b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1
c = x1 * x1 + M * M -2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1
D = b * b - 4 * a * c
Radius = (0 - b - sqr(D)) / (2 * a)
XPos = M + N * Radius
YPos = P + Q * Radius
print " "; XPos; ", " ; YPos; ", " ; Radius
end subroutine
print " x_pos y_pos radius"
print circle1$
print circle2$
print circle3$
print
print "R1: " : call ApolloniusSolver(circle1$, circle2$, circle3$, 1, 1, 1)
print "R2: " : call ApolloniusSolver(circle1$, circle2$, circle3$, -1, -1, -1)
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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun countDigits(bi: BigInteger): Int = bi.toString().length
fun main(args: Array<String>) {
println("Primorial(0) = 1")
println("Primorial(1) = 2")
var count = 1
var p = 3
var prod = BigInteger.valueOf(2)
var target = 10
while(true) {
if (isPrime(p)) {
count++
prod *= BigInteger.valueOf(p.toLong())
if (count < 10) {
println("Primorial($count) = $prod")
if (count == 9) println()
}
else if (count == target) {
println("Primorial($target) has ${countDigits(prod)} digits")
if (count == LIMIT) break
target *= 10
}
}
p += 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, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#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 function can be used to count for a given value of m:
def _count:
# state [n,m,p, [total, primitives]]
.[0] as $n | .[1] as $m | .[2] as $p
| if $n < $m and $p <= peri then
if (gcd($m;$n) == 1)
then .[3] | [ (.[0] + ((peri/$p)|floor) ), (.[1] + 1)]
else .[3]
end
| [$n+2, $m, $p+4*$m, .] | _count
else .
end;
# m^2 < m*(m+1) <= m*(m+n) = perimeter/2
reduce range(2; (peri/2) | sqrt + 1) as $m
( [1, 2, 12, [0,0]];
(($m % 2) + 1) as $n
| (2 * $m * ($m + $n) ) as $p # a+b+c for this (m,n)
| [$n, $m, $p, .[3]] | _count
) | .[3] ;
# '''Example''':
def pow(i): . as $in | reduce range(0; i) as $j (1; . * $in);
range(1; 9) | . as $i | 10|pow($i) as $i | "\($i): \(count($i) )"
|
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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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 decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#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 arrangements of 1 to S meeting these requirements.
|
#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 yield (1,g)],[for n in {3..2..row-1} do for g in {2..2..row-1} do if isPrime(n+g) then yield (n,g)]))] false (row-2)
|>Seq.filter(List.head>>(+)row>>isPrime)|>Seq.map(fun n->row::n|>List.rev)
{2..20}|>Seq.iter(fun n->(primeT>>Seq.head>>List.iter(printf "%3d"))n;printfn "");;
{2..20}|>Seq.iter(primeT>>Seq.length>>printf "%d "); printfn ""
|
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, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#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
START := 2;
DELTA := 1;
END
ELSE % ONLY NEED TO CHECK ODD DIVISORS %
BEGIN
START := 3;
DELTA := 2;
END;
% 1 IS A DIVISOR OF ANY NUMBER > 1 %
IF N > 1 THEN COUNT := 1 ELSE COUNT := 0;
IF (DISPLAY <> 0) AND (COUNT <> 0) THEN WRITEON(1);
% CHECK REMAINING POTENTIAL DIVISORS %
I := START;
LIMIT := N / START;
WHILE I <= LIMIT DO
BEGIN
IF MOD(N, I) = 0 THEN
BEGIN
IF DISPLAY <> 0 THEN WRITEON(I);
COUNT := COUNT + 1;
END;
I := I + DELTA;
IF COUNT = 1 THEN LIMIT := N / I;
END;
DIVISORS := COUNT;
END;
COMMENT MAIN PROGRAM BEGINS HERE;
INTEGER I, NDIV, TRUE, FALSE, HIGHDIV, HIGHNUM;
TRUE := -1;
FALSE := 0;
WRITE("PROPER DIVISORS OF FIRST TEN NUMBERS:");
FOR I := 1 STEP 1 UNTIL 10 DO
BEGIN
WRITE(I, " : ");
NDIV := DIVISORS(I, TRUE);
END;
WRITE("SEARCHING FOR NUMBER UP TO 10000 WITH MOST DIVISORS ...");
HIGHDIV := 1;
HIGHNUM := 1;
FOR I := 1 STEP 1 UNTIL 10000 DO
BEGIN
NDIV := DIVISORS(I, FALSE);
IF NDIV > HIGHDIV THEN
BEGIN
HIGHDIV := NDIV;
HIGHNUM := I;
END;
END;
WRITE("THE NUMBER IS:", HIGHNUM);
WRITE("IT HAS", HIGHDIV, " DIVISORS");
END
|
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 involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#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 :=
(1.0/5.0, 1.0/6.0, 1.0/7.0, 1.0/8.0, 1.0/9.0, 1.0/10.0, 1.0/11.0, 1.0);
Samples : array (Outcome) of Natural := (others => 0);
Value : Uniformly_Distributed;
Dice : Generator;
begin
for Try in 1..Trials loop
Value := Random (Dice);
for I in Pr'Range loop
if Value <= Pr (I) then
Samples (I) := Samples (I) + 1;
exit;
else
Value := Value - Pr (I);
end if;
end loop;
end loop;
-- Printing the results
for I in Pr'Range loop
Put (Outcome'Image (I) & Character'Val (9));
Put (Float'Image (Float (Samples (I)) / Float (Trials)) & Character'Val (9));
if I = Heth then
Put_Line (" rest");
else
Put_Line (Uniformly_Distributed'Image (Pr (I)));
end if;
end loop;
end Random_Distribution;
|
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 insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#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 example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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:
PROCapollonius(Circle{}, Circles{()}, -1, -1, -1)
PRINT "Internal: x = ";Circle.x ", y = ";Circle.y ", r = ";Circle.r
REM Solution for external circle:
PROCapollonius(Circle{}, Circles{()}, 1, 1, 1)
PRINT "External: x = ";Circle.x ", y = ";Circle.y ", r = ";Circle.r
END
DEF PROCapollonius(c{}, c{()}, s0, s1, s2)
LOCAL x0, x1, x2, y0, y1, y2, r0, r1, r2, a, b, c
LOCAL u(), v(), w() : DIM u(2), v(2), w(2)
x0 = c{(0)}.x : y0 = c{(0)}.y : r0 = c{(0)}.r
x1 = c{(1)}.x : y1 = c{(1)}.y : r1 = c{(1)}.r
x2 = c{(2)}.x : y2 = c{(2)}.y : r2 = c{(2)}.r
u() = 2*y1-2*y0, x0*x0-x1*x1+y0*y0-y1*y1-r0*r0+r1*r1, 2*s1*r1-2*s0*r0
v() = 2*y2-2*y1, x1*x1-x2*x2+y1*y1-y2*y2-r1*r1+r2*r2, 2*s2*r2-2*s1*r1
w() = u() / (2*x1 - 2*x0)
u() = v() / (2*x2 - 2*x1) - w()
u() /= u(0)
w(1) -= w(0)*u(1)
w(2) -= w(0)*u(2)
a = w(2)*w(2) + u(2)*u(2) - 1
b = -2*w(1)*w(2) - 2*w(2)*x1 - 2*u(1)*u(2) - 2*u(2)*y1 + 2*s1*r1
c = x1*x1 + w(1)*w(1) + 2*w(1)*x1 + u(1)*u(1) + y1*y1 + 2*u(1)*y1 - r1*r1
c.r = (-b - SQR(b^2 - 4*a*c)) / (2*a)
c.x = c.r * w(2) - w(1)
c.y = c.r * u(2) - u(1)
ENDPROC
|
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 example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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 cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }
double abs2(vec a) { return a * conj(a); }
int apollonius_in(circ aa[], int ss[], int flip, int divert)
{
vec n[3], x[3], t[3], a, b, center;
int s[3], iter = 0, res = 0;
double diff = 1, diff_old = -1, axb, d, r;
for3 {
s[i] = ss[i] ? 1 : -1;
x[i] = aa[i].c;
}
while (diff > 1e-20) {
a = x[0] - x[2], b = x[1] - x[2];
diff = 0;
axb = -cross(a, b);
d = sqrt(abs2(a) * abs2(b) * abs2(a - b));
if (VERBOSE) {
const char *z = 1 + "-0+";
printf("%c%c%c|%c%c|",
z[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);
printf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));
}
/* r and center represent an arc through points x[i]. Each step,
we'll deform this arc by pushing or pulling some point on it
towards the edge of each given circle. */
r = fabs(d / (2 * axb));
center = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];
/* maybe the "arc" is actually straight line; then we have two
choices in defining "push" and "pull", so try both */
if (!axb && flip != -1 && !divert) {
if (!d) { /* generally means circle centers overlap */
printf("Given conditions confused me.\n");
return 0;
}
if (VERBOSE) puts("\n[divert]");
divert = 1;
res = apollonius_in(aa, ss, -1, 1);
}
/* if straight line, push dir is its norm; else it's away from center */
for3 n[i] = axb ? aa[i].c - center : a * I * flip;
for3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];
/* diff: how much tangent points have moved since last iteration */
for3 diff += abs2(t[i] - x[i]), x[i] = t[i];
if (VERBOSE) printf(" %g\n", diff);
/* keep an eye on the total diff: failing to converge means no solution */
if (diff >= diff_old && diff_old >= 0)
if (iter++ > 20) return res;
diff_old = diff;
}
printf("found: ");
if (axb) printf("circle "CPLX", r = %f\n", cp(center), r);
else printf("line "CPLX3"\n", cp(x[0]), cp(x[1]), cp(x[2]));
return res + 1;
}
int apollonius(circ aa[])
{
int s[3], i, sum = 0;
for (i = 0; i < 8; i++) {
s[0] = i & 1, s[1] = i & 2, s[2] = i & 4;
/* internal or external results of a zero-radius circle are the same */
if (s[0] && !aa[0].r) continue;
if (s[1] && !aa[1].r) continue;
if (s[2] && !aa[2].r) continue;
sum += apollonius_in(aa, s, 1, 0);
}
return sum;
}
int main()
{
circ a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};
circ b[3] = {{-3, 2}, {0, 1}, {3, 2}};
circ c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};
//circ c[3] = {{0, 1}, {0, 2}, {0, 3}}; <-- a fun one
puts("set 1"); apollonius(a);
puts("set 2"); apollonius(b);
puts("set 3"); apollonius(c);
}
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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, primes[i])
if i mod pow10=0 then
put "Primorial " & i & " has length: " & pr.length
pow10 = pow10 * 10
end if
end repeat
|
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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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 ceil(logSum);
end proc:
print("The first 10 primorial numbers");
for count from 0 to 9 do
cat("primorial(", count, ") = ", primorial(count))
end;
for expon from 1 to 5 do
cat("primorial(", 10^expon, ") has ", primorialDigits(10^expon), " digits");
end;
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#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<:Integer}(plim::T)
primcnt = 0
fullcnt = 0
11 < plim || return (primcnt, fullcnt)
for m in 2:plim
p = 2m^2
p+2m <= plim || break
for n in primitiven(m)
q = p + 2m*n
q <= plim || break
primcnt += 1
fullcnt += div(plim, q)
end
end
return (primcnt, fullcnt)
end
println("Counting Pythagorian Triplets within perimeter limits:")
println(" Limit All Primitive")
for om in 1:10
(pcnt, fcnt) = pythagoreantripcount(10^om)
println(@sprintf " 10^%02d %11d %9d" om fcnt pcnt)
end
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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 decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#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 Array:D --> Array) {
my @c;
for ^@A X ^@b -> ($i, $j) {
@c[$i] += @A[$i; $j] * @b[$j];
}
@c;
}
multi multiply(Array:D @A, Array:D @B --> Array of Array) {
my Array @C;
for ^@A X ^@B[0] -> ($i, $j) {
@C[$i; $j] += @A[$i; $_] * @B[$_; $j] for ^@B;
}
@C;
}
sub transpose(Array:D @M --> Array of Array) {
my ($rows, $cols) = (@M.elems, @M[0].elems);
my Array @T;
for ^$cols X ^$rows -> ($j, $i) {
@T[$j; $i] = @M[$i; $j];
}
@T;
}
####################################################
# NOTE: @A gets overwritten and becomes @R, only need
# to return @Q.
####################################################
sub householder(Array:D @A --> Array) {
my Int ($m, $n) = (@A.elems, @A[0].elems);
my @v = 0 xx $m;
my Array @Q = identity($m);
for 0 ..^ $n -> $k {
my Real $sum = 0;
my Real $A0 = @A[$k; $k];
my Int $sign = $A0 < 0 ?? -1 !! 1;
for $k ..^ $m -> $i {
$sum += @A[$i; $k] * @A[$i; $k];
}
my Real $sqr_sum = $sign * sqrt($sum);
my Real $tmp = sqrt(2 * ($sum + $A0 * $sqr_sum));
@v[$k] = ($sqr_sum + $A0) / $tmp;
for ($k + 1) ..^ $m -> $i {
@v[$i] = @A[$i; $k] / $tmp;
}
for 0 ..^ $n -> $j {
$sum = 0;
for $k ..^ $m -> $i {
$sum += @v[$i] * @A[$i; $j];
}
for $k ..^ $m -> $i {
@A[$i; $j] -= 2 * @v[$i] * $sum;
}
}
for 0 ..^ $m -> $j {
$sum = 0;
for $k ..^ $m -> $i {
$sum += @v[$i] * @Q[$i; $j];
}
for $k ..^ $m -> $i {
@Q[$i; $j] -= 2 * @v[$i] * $sum;
}
}
}
@Q
}
sub dotp(@a where Array:D, @b where Array:D --> Real) {
[+] @a >>*<< @b;
}
sub upper-solve(Array:D @U, @b where Array:D, Int:D $n --> Array) {
my @y = 0 xx $n;
@y[$n - 1] = @b[$n - 1] / @U[$n - 1; $n - 1];
for reverse ^($n - 1) -> $i {
@y[$i] = (@b[$i] - (dotp(@U[$i], @y))) / @U[$i; $i];
}
@y;
}
sub polyfit(@x where Array:D, @y where Array:D, Int:D $n) {
my Int $m = @x.elems;
my Array @V;
# Vandermonde matrix
for ^$m X (0 .. $n) -> ($i, $j) {
@V[$i; $j] = @x[$i] ** $j
}
# least squares
my $Q = householder(@V);
my @b = multiply($Q, @y);
return upper-solve(@V, @b, $n + 1);
}
sub print-mat(Array:D @M, Str:D $name) {
my Int ($m, $n) = (@M.elems, @M[0].elems);
print "\n$name:\n";
for 0 ..^ $m -> $i {
for 0 ..^ $n -> $j {
print @M[$i; $j].fmt("%12.6f ");
}
print "\n";
}
}
sub MAIN() {
############
# 1st part #
############
my Array @A = (
[12, -51, 4],
[ 6, 167, -68],
[-4, 24, -41],
[-1, 1, 0],
[ 2, 0, 3]
);
print-mat(@A, 'A');
my $Q = householder(@A);
$Q = transpose($Q);
print-mat($Q, 'Q');
# after householder, @A is now @R
print-mat(@A, 'R');
print-mat(multiply($Q, @A), 'check Q x R = A');
############
# 2nd part #
############
my @x = [^11];
my @y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
my @coef = polyfit(@x, @y, 2);
say
"\npolyfit:\n",
<constant X X^2>.fmt("%12s"),
"\n",
@coef.fmt("%12.6f");
}
|
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 arrangements of 1 to S meeting these requirements.
|
#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 {
if canFollow[ad-1][n-1] {
if bFirst {
for _, e := range arrang {
fmt.Printf("%2d ", e)
}
fmt.Println()
bFirst = false
}
res++
}
} else {
done++
for i := done - 1; i <= n-2; i += 2 {
ai := arrang[i]
if canFollow[ad-1][ai-1] {
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
res = ptrs(res, n, done)
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
}
}
}
return res
}
func primeTriangle(n int) int {
canFollow = make([][]bool, n)
for i := 0; i < n; i++ {
canFollow[i] = make([]bool, n)
for j := 0; j < n; j++ {
_, ok := pmap[i+j+2]
canFollow[i][j] = ok
}
}
bFirst = true
arrang = make([]int, n)
for i := 0; i < n; i++ {
arrang[i] = i + 1
}
return ptrs(0, n, 1)
}
func main() {
counts := make([]int, 19)
for i := 2; i <= 20; i++ {
counts[i-2] = primeTriangle(i)
}
fmt.Println()
for i := 0; i < 19; i++ {
fmt.Printf("%d ", counts[i])
}
fmt.Println()
}
|
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, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#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
-- isFactor :: Int -> Bool
script isFactor
on |λ|(x)
n mod x = 0
end |λ|
end script
-- Factors up to square root of n,
set lows to filter(isFactor, enumFromTo(1, intRoot))
-- and quotients of these factors beyond the square root,
-- integerQuotient :: Int -> Int
script integerQuotient
on |λ|(x)
(n / x) as integer
end |λ|
end script
-- excluding n itself (last item)
items 1 thru -2 of (lows & map(integerQuotient, ¬
items (1 + (blnPerfectSquare as integer)) thru -1 of reverse of lows))
end if
end properDivisors
-- TEST ----------------------------------------------------------------------
on run
-- numberAndDivisors :: Int -> [Int]
script numberAndDivisors
on |λ|(n)
{num:n, divisors:properDivisors(n)}
end |λ|
end script
-- maxDivisorCount :: Record -> Int -> Record
script maxDivisorCount
on |λ|(a, n)
set intDivisors to length of properDivisors(n)
if intDivisors ≥ divisors of a then
{num:n, divisors:intDivisors}
else
a
end if
end |λ|
end script
{oneToTen:map(numberAndDivisors, ¬
enumFromTo(1, 10)), mostDivisors:foldl(maxDivisorCount, ¬
{num:0, divisors:0}, enumFromTo(1, 20000))} ¬
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
|
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 involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#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 := (
( "aleph", 0, ~, ~ ),
( "beth", 0, ~, ~ ),
( "gimel", 0, ~, ~ ),
( "daleth", 0, ~, ~ ),
( "he", 0, ~, ~ ),
( "waw", 0, ~, ~ ),
( "zayin", 0, ~, ~ ),
( "heth", 0, ~, ~ )
);
main:
(
LREAL offset = 5; # const #
# initialise items #
LREAL total sum := 0;
FOR i FROM LWB items TO UPB items - 1 DO
expect OF items[i] := 1/(i-1+offset);
total sum +:= expect OF items[i]
OD;
expect OF items[UPB items] := 1 - total sum;
mapping OF items[LWB items] := expect OF items[LWB items];
FOR i FROM LWB items + 1 TO UPB items DO
mapping OF items[i] := mapping OF items[i-1] + expect OF items[i]
OD;
# printf((item repr, items)) #
# perform the sampling #
PROC sample = (REF[]LREAL mapping)INT:(
INT out;
LREAL rand real = random;
FOR j FROM LWB items TO UPB items DO
IF rand real < mapping[j] THEN
out := j;
done
FI
OD;
done: out
);
FOR i TO trials DO
prob count OF items[sample(mapping OF items)] +:= 1
OD;
FORMAT indent = $17k$;
# print the results #
printf(($"Trials: "g(0)l$, trials));
printf(($"Items:"$,indent));
FOR i FROM LWB items TO UPB items DO printf(($gn(col width)k" "$, name OF items[i])) OD;
printf(($l"Target prob.:"$, indent, $f(real repr)" "$, expect OF items));
printf(($l"Attained prob.:"$, indent));
FOR i FROM LWB items TO UPB items DO printf(($f(real repr)" "$, prob count OF items[i]/trials)) OD;
printf($l$)
)
|
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 between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#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)
L(p) primes
descendants[p].append(p)
L(s) 1 .< descendants.len - p
descendants[s + p] [+]= descendants[s].map(pr -> @p * pr)
L(p) primes [+] [4]
descendants[p].pop()
V total = 0
L(s) 1..maxsum
descendants[s].sort()
L(d) descendants[s]
I d > maxsum
L.break
ancestors[Int(d)] = ancestors[s] [+] [Int64(s)]
print([s]‘ Level: ’ancestors[s].len)
print(‘Ancestors: ’(I !ancestors[s].empty {String(ancestors[s])} E ‘None’))
print(‘Descendants: ’(I !descendants[s].empty {String(descendants[s].len)} E ‘None’))
I !descendants[s].empty
print(descendants[s])
print()
total += descendants[s].len
print(‘Total descendants ’total)
|
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 insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#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;
function Get_Priority (Element : Queue_Element) return Natural is
begin
return Element.Priority;
end Get_Priority;
function Before (Left, Right : Natural) return Boolean is
begin
return Left > Right;
end Before;
package String_Queues is new Synchronized_Queue_Interfaces
(Element_Type => Queue_Element);
package String_Priority_Queues is new Unbounded_Priority_Queues
(Queue_Interfaces => String_Queues,
Queue_Priority => Natural);
My_Queue : String_Priority_Queues.Queue;
begin
My_Queue.Enqueue (New_Item => (Priority => 3, Content => To_Unbounded_String ("Clear drains")));
My_Queue.Enqueue (New_Item => (Priority => 4, Content => To_Unbounded_String ("Feed cat")));
My_Queue.Enqueue (New_Item => (Priority => 5, Content => To_Unbounded_String ("Make tea")));
My_Queue.Enqueue (New_Item => (Priority => 1, Content => To_Unbounded_String ("Solve RC tasks")));
My_Queue.Enqueue (New_Item => (Priority => 2, Content => To_Unbounded_String ("Tax return")));
declare
Element : Queue_Element;
begin
while My_Queue.Current_Use > 0 loop
My_Queue.Dequeue (Element => Element);
Ada.Text_IO.Put_Line (Natural'Image (Element.Priority) & " => " & To_String (Element.Content));
end loop;
end;
end Priority_Queues;
|
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 example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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;
float gy2;
float gr2;
float gx3;
float gy3;
float gr3;
//----------Enter values for the given circles here----------
gx1 = 0;
gy1 = 0;
gr1 = 1;
gx2 = 4;
gy2 = 0;
gr2 = 1;
gx3 = 2;
gy3 = 4;
gr3 = 2;
//-----------------------------------------------------------
for (int i = 1; i <= 8; i++)
{
SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);
if (i == 1)
{
Console.WriteLine("X of point of the " + i + "st solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "st solution: " + ys.ToString());
Console.WriteLine(i + "st Solution circle's radius: " + rs.ToString());
}
else if (i == 2)
{
Console.WriteLine("X of point of the " + i + "ed solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "ed solution: " + ys.ToString());
Console.WriteLine(i + "ed Solution circle's radius: " + rs.ToString());
}
else if(i == 3)
{
Console.WriteLine("X of point of the " + i + "rd solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "rd solution: " + ys.ToString());
Console.WriteLine(i + "rd Solution circle's radius: " + rs.ToString());
}
else
{
Console.WriteLine("X of point of the " + i + "th solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "th solution: " + ys.ToString());
Console.WriteLine(i + "th Solution circle's radius: " + rs.ToString());
}
Console.WriteLine();
}
Console.ReadKey(true);
}
private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)
{
float s1 = 1;
float s2 = 1;
float s3 = 1;
if (calcCounter == 2)
{
s1 = -1;
s2 = -1;
s3 = -1;
}
else if (calcCounter == 3)
{
s1 = 1;
s2 = -1;
s3 = -1;
}
else if (calcCounter == 4)
{
s1 = -1;
s2 = 1;
s3 = -1;
}
else if (calcCounter == 5)
{
s1 = -1;
s2 = -1;
s3 = 1;
}
else if (calcCounter == 6)
{
s1 = 1;
s2 = 1;
s3 = -1;
}
else if (calcCounter == 7)
{
s1 = -1;
s2 = 1;
s3 = 1;
}
else if (calcCounter == 8)
{
s1 = 1;
s2 = -1;
s3 = 1;
}
//This calculation to solve for the solution circles is cited from the Java version
float v11 = 2 * x2 - 2 * x1;
float v12 = 2 * y2 - 2 * y1;
float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;
float v14 = 2 * s2 * r2 - 2 * s1 * r1;
float v21 = 2 * x3 - 2 * x2;
float v22 = 2 * y3 - 2 * y2;
float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;
float v24 = 2 * s3 * r3 - 2 * s2 * r2;
float w12 = v12 / v11;
float w13 = v13 / v11;
float w14 = v14 / v11;
float w22 = v22 / v21 - w12;
float w23 = v23 / v21 - w13;
float w24 = v24 / v21 - w14;
float P = -w23 / w22;
float Q = w24 / w22;
float M = -w12 * P - w13;
float N = w14 - w12 * Q;
float a = N * N + Q * Q - 1;
float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;
float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;
float D = b * b - 4 * a * c;
rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));
xs = M + N * rs;
ys = P + Q * rs;
}
}
}
|
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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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;
int v = 2;
for (int i = 2; i <= n; i++) {
v *= primes[i-2];
}
return v;
}
for (int i = 0; i < 10; i++) {
printf("primorial(%d) = %d\n", i, primorial(i));
}
for (int i = 1; i < 6; i++) {
start = millis();
int p = 10**i;
int pn = primorial(p);
int digits = floor(Math::log10(pn)) + 1;
printf("primorial(%d) has %d digits, in %dms\n", p, digits, millis() - start);
}
|
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, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#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 + 2 * s2, 2 * s0 + s1 + 2 * s2, 2 * s0 + 2 * s1 + 3 * s2)
newTri(-s0 + 2 * s1 + 2 * s2, -2 * s0 + s1 + 2 * s2, -2 * s0 + 2 * s1 + 3 * s2)
}
}
fun main(args: Array<String>) {
maxPeri = 100
while (maxPeri <= 10_000_000_000L) {
prim = 0
total = 0
newTri(3, 4, 5)
println("Up to $maxPeri: $total triples, $prim primatives")
maxPeri *= 10
}
}
|
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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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 decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#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 <- [1.0 .. x]){
o = domainR(oc, {n-1});
c = matrixSubtract(c, matrixMultiplybyN(o, matrixDotproduct(o, c)/matrixDotproduct(o, o)));
}
oc += c;
}
Q = {};
//from orthogonal to orthonormal columns
for (el <- oc){
c = domainR(oc, {el[0]});
Q += matrixNormalize({el}, c);
}
//from Q to R
R= matrixMultiplication(matrixTranspose(Q), matrix);
R= {<x,y,toReal(round(v))> | <x,y,v> <- R};
println("Q:");
iprintlnExp(Q);
println();
println("R:");
return R;
}
//a function that takes the transpose of a matrix, see also Rosetta Code problem "Matrix transposition"
public rel[real, real, real] matrixTranspose(rel[real x, real y, real v] matrix){
return {<y, x, v> | <x, y, v> <- matrix};
}
//a function to normalize an element of a matrix by the normalization of a column
public rel[real,real,real] matrixNormalize(rel[real x, real y, real v] element, rel[real x, real y, real v] column){
normalized = 1.0/nroot((0.0 | it + v*v | <x,y,v> <- column), 2);
return matrixMultiplybyN(element, normalized);
}
//a function that takes the dot product, see also Rosetta Code problem "Dot product"
public real matrixDotproduct(rel[real x, real y, real v] column1, rel[real x, real y, real v] column2){
return (0.0 | it + v1*v2 | <x1,y1,v1> <- column1, <x2,y2,v2> <- column2, y1==y2);
}
//a function to subtract two columns
public rel[real,real,real] matrixSubtract(rel[real x, real y, real v] column1, rel[real x, real y, real v] column2){
return {<x1,y1,v1-v2> | <x1,y1,v1> <- column1, <x2,y2,v2> <- column2, y1==y2};
}
//a function to multiply a column by a number
public rel[real,real,real] matrixMultiplybyN(rel[real x, real y, real v] column, real n){
return {<x,y,v*n> | <x,y,v> <- column};
}
//a function to perform matrix multiplication, see also Rosetta Code problem "Matrix multiplication".
public rel[real, real, real] matrixMultiplication(rel[real x, real y, real v] matrix1, rel[real x, real y, real v] matrix2){
if (max(matrix1.x) == max(matrix2.y)){
p = {<x1,y1,x2,y2, v1*v2> | <x1,y1,v1> <- matrix1, <x2,y2,v2> <- matrix2};
result = {};
for (y <- matrix1.y){
for (x <- matrix2.x){
v = (0.0 | it + v | <x1, y1, x2, y2, v> <- p, x==x2 && y==y1, x1==y2 && y2==x1);
result += <x,y,v>;
}
}
return result;
}
else throw "Matrix sizes do not match.";
}
// a function to visualize the result
public void displayMatrix(rel[real x, real y, real v] matrix){
points = [box(text("<v>"), align(0.3333*(x+1),0.3333*(y+1)),shrink(0.25)) | <x,y,v> <- matrix];
render(overlay([*points], aspectRatio(1.0)));
}
//a matrix, given by a relation of <x-coordinate, y-coordinate, value>.
public rel[real x, real y, real v] matrixA = {
<0.0,0.0,12.0>, <0.0,1.0, 6.0>, <0.0,2.0,-4.0>,
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>,
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0>
};
|
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 arrangements of 1 to S meeting these requirements.
|
#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_triangle Y do. 1 return.end.
L=: (L{~Y,i) (i,Y)} L
end.
end.
0
}}
prime_triangle_counter=: {{
NB. y is index into L and thus analogous to *a
p=. is_prime L{~y+0 1
if. N=y do.
count=: count+p return.
end.
i=. Y=. y+1
if. p do. prime_triangle_counter Y end.
while. M>i=. i+2 do.
if. is_prime L{~y,i do.
L=: (L{~Y,i) (i,Y)} L
prime_triangle_counter Y
L=: (L{~Y,i) (i,Y)} L
end.
end.
count
}}
prime_triangles=: {{
for_k. i.y-1 do.
L=: l=. 1+i.1+M=: 1+N=: k
count=: 0
prime_triangle_counter 0
L=: l
assert is_prime_triangle 0
echo (8":count),' | ',3":L
end.
}}
|
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, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#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)))
dlist))
;; Find out what number has the most divisors between 2 and 20,000.
;; Print a list of the largest known number's divisors as it is found.
(= div-lists (fn (cnt (o show 0))
(= tlist '()) (= clist tlist)
(when (> show 0) (prn tlist))
(up i 1 cnt
(divisor i)
(when (is 1 show) (prn dlist))
(when (>= (len dlist) (len tlist))
(= tlist dlist)
(when (is show 2) (prn tlist))
(let c (- (len dlist) 1)
(push (list i c) clist))))
(= many-divisors (list ((clist 0) 1)))
(for n 0 (is ((clist n) 1) ((clist 0) 1)) (= n (+ 1 n))
(push ((clist n) 0) many-divisors))
(= many-divisors (rev many-divisors))
(prn "The number with the most divisors under " cnt
" has " (many-divisors 0) " divisors.")
(prn "It is the number "
(if (> 2 (len many-divisors)) (cut (many-divisors) 1)
(many-divisors 1)) ".")
(prn "There are " (- (len many-divisors) 1) " numbers"
" with this trait, and they are "
(map [many-divisors _] (range 1 (- (len many-divisors) 1))))
(prn (map [divisor _] (cut many-divisors 1)))
many-divisors))
;; Do the tasks
(div-lists 10 1)
(div-lists 20000)
;; This took about 10 minutes on my machine.
|
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 involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#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 mapping to current application's class "NSMutableArray"'s arrayWithArray:(mapping)
tell mapping to makeObjectsPerformSelector:("addEntriesFromDictionary:") withObject:({actual:0})
-- … ensuring that they're sorted (for accuracy) in descending order (for efficiency) of probability.
set descriptor to current application's class "NSSortDescriptor"'s sortDescriptorWithKey:("probability") ascending:(false)
tell mapping to sortUsingDescriptors:({descriptor})
set o's mapping to mapping as list
set rndGenerator to current application's class "GKRandomDistribution"'s distributionForDieWithSideCount:(picks)
set onePickth to 1 / picks
repeat picks times
-- Get a random number between 0.0 and 1.0.
set r to rndGenerator's nextUniform()
-- Interpret the probability of the number occurring in the range it does
-- as picking the item with the same probability of being picked.
repeat with thisRecord in o's mapping
set r to r - (thisRecord's probability)
if (r ≤ 0) then
set thisRecord's actual to (thisRecord's actual) + onePickth
exit repeat
end if
end repeat
end repeat
return o's mapping
end probabilisticChoices
on task()
set mapping to {{|item|:"aleph", probability:1 / 5}, {|item|:"beth", probability:1 / 6}, ¬
{|item|:"gimel", probability:1 / 7}, {|item|:"daleth", probability:1 / 8}, ¬
{|item|:"he", probability:1 / 9}, {|item|:"waw", probability:1 / 10}, ¬
{|item|:"zayin", probability:1 / 11}, {|item|:"heth", probability:1759 / 27720}}
set picks to 1000000
set theResults to probabilisticChoices(mapping, picks)
set output to {}
set template to {"|item|:", missing value, ", probability:", missing value, ", actual:", missing value}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
repeat with thisRecord in theResults
set {|item|:item 2 of template, probability:item 4 of template, actual:item 6 of template} to thisRecord
set {|item|:template's second item, probability:template's fourth item, actual:template's sixth item} to thisRecord
set end of output to template as text
end repeat
set AppleScript's text item delimiters to "}, ¬
{"
set output to "{ ¬
{" & output & "} ¬
}"
set AppleScript's text item delimiters to astid
return output
end task
task()
|
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 between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#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
MaxAncestor = 99 ; greatest parent number
Descendants := []
Primes := GetPrimes(MaxPrime)
Exclusions := Primes.Clone()
Exclusions.Insert(4)
if A_Is64bitOS
{
Loop, % MaxAncestor
Descendants.Insert({})
for i, Prime in Primes
{
Descendants[Prime, Prime] := 0
for Parent, Children in Descendants
{
if ((Sum := Parent+Prime) > MaxAncestor)
break
for pr in Children
Descendants[Sum, pr*Prime] := 0
}
}
for i, v in Exclusions
Descendants[v].Remove(v, "")
}
else
{
Loop, % MaxAncestor
Descendants.Insert([])
for i, Prime in Primes
{
Descendants[Prime].Insert(Prime)
for Parent, Children in Descendants
{
if ((Sum := Parent+Prime) > MaxAncestor)
break
for j, pr in Children
Descendants[Sum].Insert(pr*Prime)
}
}
for i, v in Exclusions
Descendants[v].Remove()
}
if (MaxAncestor > MaxPrime)
Primes := GetPrimes(MaxAncestor)
IfExist, %A_ScriptName%.txt
FileDelete, %A_ScriptName%.txt
;-------------------------------------------------------
; Arrays :
; Integer keys are stored using the native integer type
; 32bit key max = 2.147.483.647
; 64bit key max = 9.223.372.036.854.775.807
;-------------------------------------------------------
Tot_desc = 0
for Parent, Children in Descendants
{
ls_desc =
if A_Is64bitOS
{
nb_desc = 0
for pr in Children
ls_desc .= ", " pr, nb_desc++
ls_desc := LTrim(ls_desc, ", ")
}
else
{
nb_desc := Children.MaxIndex()
for i, pr in Children
ls_desc .= "," pr
ls_desc := LTrim(ls_desc, ",")
Sort, ls_desc, N D`,
StringReplace, ls_desc, ls_desc, `,,`,%A_Space%, All
}
ls_anc =
nb_anc := GetAncestors(ls_anc, Parent)
ls_anc := LTrim(ls_anc, ", ")
FileAppend, % "[" Parent "] Level: " nb_anc "`r`nAncestors: " (nb_anc ? ls_anc : "None") "`r`n"
, %A_ScriptName%.txt
if nb_desc
{
Tot_desc += nb_desc
FileAppend, % "Descendants: " nb_desc "`r`n" ls_desc "`r`n`r`n", %A_ScriptName%.txt
}
else
FileAppend, % "Descendants: None`r`n`r`n", %A_ScriptName%.txt
}
FileAppend, % "Total descendants " Tot_desc, %A_ScriptName%.txt
return
GetAncestors(ByRef _lsAnc, _child)
{
global Primes
lChild := _child
lIndex := lParent := 0
while lChild > 1
{
lPrime := Primes[++lIndex]
while !mod(lChild, lPrime)
lChild //= lPrime, lParent += lPrime
}
if (lParent = _child or _child = 1)
return 0
_lsAnc := ", " lParent _lsAnc
li := GetAncestors(_lsAnc, lParent)
return ++li
}
GetPrimes(_maxPrime=0, _nbrPrime=0)
{
lPrimes := []
if (_maxPrime >= 2 or _nbrPrime >= 1)
{
lPrimes.Insert(2)
lValue = 1
while (lValue += 2) <= _maxPrime or lPrimes.MaxIndex() < _nbrPrime
{
lMaxPrime := Floor(Sqrt(lValue))
for lKey, lPrime in lPrimes
{
if (lPrime > lMaxPrime) ; if prime divisor is greater than Floor(Sqrt(lValue))
{
lPrimes.Insert(lValue)
break
}
if !Mod(lValue, lPrime)
break
}
}
}
return lPrimes
}
|
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 insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#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 */
/********************************************/
/* example structure item */
.struct 0
item_priority: @ priority
.struct item_priority + 4
item_address: @ string address
.struct item_address + 4
item_fin:
/* example structure heap */
.struct 0
heap_size: @ heap size
.struct heap_size + 4
heap_items: @ structure of items
.struct heap_items + (item_fin * NBMAXIELEMENTS)
heap_fin:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEmpty: .asciz "Empty queue. \n"
szMessNotEmpty: .asciz "Not empty queue. \n"
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .ascii "Priority : " @ message result
sMessPriority: .fill 11, 1, ' '
.asciz " : "
szString1: .asciz "Clear drains"
szString2: .asciz "Feed cat"
szString3: .asciz "Make tea"
szString4: .asciz "Solve RC tasks"
szString5: .asciz "Tax return"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
Queue1: .skip heap_fin @ queue memory place
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrQueue1 @ queue structure address
bl isEmpty
cmp r0,#0
beq 1f
ldr r0,iAdrszMessEmpty
bl affichageMess @ display message empty
b 2f
1:
ldr r0,iAdrszMessNotEmpty
bl affichageMess @ display message not empty
2:
@ init item 1
ldr r0,iAdrQueue1 @ queue structure address
mov r1,#3 @ priority
ldr r2,iAdrszString1
bl pushQueue @ add item in queue
cmp r0,#-1 @ error ?
beq 99f
ldr r0,iAdrQueue1 @ queue structure address
bl isEmpty
cmp r0,#0 @ not empty
beq 3f
ldr r0,iAdrszMessEmpty
bl affichageMess @ display message empty
b 4f
3:
ldr r0,iAdrszMessNotEmpty
bl affichageMess @ display message not empty
4:
@ init item 2
ldr r0,iAdrQueue1 @ queue structure address
mov r1,#4 @ priority
ldr r2,iAdrszString2
bl pushQueue @ add item in queue
cmp r0,#-1 @ error ?
beq 99f
@ init item 3
ldr r0,iAdrQueue1 @ queue structure address
mov r1,#5 @ priority
ldr r2,iAdrszString3
bl pushQueue @ add item in queue
cmp r0,#-1 @ error ?
beq 99f
@ init item 4
ldr r0,iAdrQueue1 @ queue structure address
mov r1,#1 @ priority
ldr r2,iAdrszString4
bl pushQueue @ add item in queue
cmp r0,#-1 @ error ?
beq 99f
@ init item 5
ldr r0,iAdrQueue1 @ queue structure address
mov r1,#2 @ priority
ldr r2,iAdrszString5
bl pushQueue @ add item in queue
cmp r0,#-1 @ error ?
beq 99f
5:
ldr r0,iAdrQueue1 @ queue structure address
bl popQueue @ return item
cmp r0,#-1 @ end ?
beq 100f
mov r2,r1 @ save string address
ldr r1,iAdrsMessPriority @ conversion priority
bl conversion10 @ decimal conversion
ldr r0,iAdrszMessResult
bl affichageMess @ display message
mov r0,r2 @ string address
bl affichageMess @ display message
ldr r0,iAdrszCarriageReturn
bl affichageMess
b 5b @ loop
99:
@ error
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrQueue1: .int Queue1
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszString3: .int szString3
iAdrszString4: .int szString4
iAdrszString5: .int szString5
iAdrszMessError: .int szMessError
iAdrszMessEmpty: .int szMessEmpty
iAdrszMessNotEmpty: .int szMessNotEmpty
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessPriority: .int sMessPriority
/******************************************************************/
/* test if queue empty */
/******************************************************************/
/* r0 contains the address of queue structure */
isEmpty:
push {r1,lr} @ save registres
ldr r1,[r0,#heap_size] @ heap size
cmp r1,#0
moveq r0,#1 @ empty queue
movne r0,#0 @ not empty
pop {r1,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* add item in queue */
/******************************************************************/
/* r0 contains the address of queue structure */
/* r1 contains the priority of item */
/* r2 contains the string address */
pushQueue:
push {r1-r9,lr} @ save registres
ldr r3,[r0,#heap_size] @ heap size
cmp r3,#0 @ heap empty ?
bne 1f
add r4,r0,#heap_items @ address of item structure
str r1,[r4,#item_priority] @ store in first item
str r2,[r4,#item_address]
mov r3,#1 @ heap size
str r3,[r0,#heap_size] @ new heap size
b 100f
1:
mov r4,r3 @ maxi index
lsr r5,r4,#1 @ current index = maxi / 2
mov r8,r1 @ save priority
mov r9,r2 @ save string address
2: @ insertion loop
cmp r4,#0 @ end loop ?
ble 3f
mov r6,#item_fin @ item size
mul r6,r5,r6 @ item shift
add r6,r0
add r6,#heap_items @ compute address item
ldr r7,[r6,#item_priority] @ load priority
cmp r7,r8 @ compare priority
ble 3f @ <= end loop
mov r1,r4 @ last index
mov r2,r5 @ current index
bl exchange
mov r4,r5 @ last index = current index
lsr r5,#1 @ current index / 2
b 2b
3: @ store item at last index find
mov r6,#item_fin @ item size
mul r6,r4,r6 @ item shift
add r6,r0
add r6,#heap_items @ item address
str r8,[r6,#item_priority]
str r9,[r6,#item_address]
add r3,#1 @ increment heap size
cmp r3,#NBMAXIELEMENTS @ maxi ?
movge r0,#-1 @ yes -> error
bge 100f
str r3,[r0,#heap_size] @ store new size
100:
pop {r1-r9,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* swap two elements of table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first index */
/* r2 contains the second index */
exchange:
push {r3-r6,lr} @ save registers
add r5,r0,#heap_items @ address items begin
mov r3,#item_fin @ item size
mul r4,r1,r3 @ compute item 1 shift
add r4,r5 @ compute item 1 address
mul r6,r2,r3 @ compute item 2 shift
add r6,r5 @ compute item 2 address
ldr r5,[r4,#item_priority] @ exchange
ldr r3,[r6,#item_priority]
str r3,[r4,#item_priority]
str r5,[r6,#item_priority]
ldr r5,[r4,#item_address]
ldr r3,[r6,#item_address]
str r5,[r6,#item_address]
str r3,[r4,#item_address]
100:
pop {r3-r6,lr}
bx lr @ return
/******************************************************************/
/* move one element of table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the origin index */
/* r2 contains the destination index */
moveItem:
push {r3-r6,lr} @ save registers
add r5,r0,#heap_items @ address items begin
mov r3,#item_fin @ item size
mul r4,r1,r3 @ compute item 1 shift
add r4,r5 @ compute item 1 address
mul r6,r2,r3 @ compute item 2 shift
add r6,r5 @ compute item 2 address
ldr r5,[r4,#item_priority] @ exchange
str r5,[r6,#item_priority]
ldr r5,[r4,#item_address]
str r5,[r6,#item_address]
100:
pop {r3-r6,lr}
bx lr @ return
/******************************************************************/
/* pop queue */
/******************************************************************/
/* r0 contains the address of queue structure */
/* r0 return priority */
/* r1 return string address */
popQueue:
push {r2-r10,lr} @ save registres
mov r1,r0 @ save address queue
bl isEmpty @ control if empty queue
cmp r0,#1 @ yes -> error
moveq r0,#-1
beq 100f
@ save données à retourner
mov r0,r1 @ restaur address queue
add r4,r0,#heap_items @ address of item structure
ldr r8,[r4,#item_priority] @ save priority first item
ldr r9,[r4,#item_address] @ save address string first item
ldr r3,[r0,#heap_size] @ heap size
sub r7,r3,#1 @ last item
mov r1,r7
mov r2,#0 @ first item
bl moveItem @ move last item in first item
cmp r7,#1 @ one only item ?
beq 10f @ yes -> end
mov r4,#0 @ first index
1:
cmp r4,r7 @ = last index
bge 10f @ yes -> end
mov r5,r7 @ last index
cmp r4,#0 @ init current index
moveq r6,#1 @ = 1
lslne r6,r4,#1 @ else = first index * 2
cmp r6,r7 @ current index > last index
bgt 2f @ yes
@ no compar priority current item last item
mov r1,#item_fin
mul r1,r6,r1
add r1,r0
add r1,#heap_items @ address of current item structure
ldr r1,[r1,#item_priority]
mov r10,#item_fin
mul r10,r5,r10
add r10,r0
add r10,#heap_items @ address of last item structure
ldr r10,[r10,#item_priority]
cmp r1,r10
movlt r5,r6
2:
add r10,r6,#1 @ increment current index
cmp r10,r7 @ end ?
bgt 3f @ yes
mov r1,#item_fin @ no compare priority
mul r1,r10,r1
add r1,r0
add r1,#heap_items @ address of item structure
ldr r1,[r1,#item_priority]
mov r2,#item_fin
mul r2,r5,r2
add r2,r0
add r2,#heap_items @ address of item structure
ldr r2,[r2,#item_priority]
cmp r1,r2
movlt r5,r10
3:
mov r1,r5 @ move item
mov r2,r4
bl moveItem
mov r4,r5
b 1b @ and loop
10:
sub r3,#1
str r3,[r0,#heap_size] @ new heap size
mov r0,r8 @ return priority
mov r1,r9 @ return string address
100:
pop {r2-r10,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ previous position
bne 1b @ else loop
@ end replaces digit in front of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4] @ store in area begin
add r4,#1
add r2,#1 @ previous position
cmp r2,#LGZONECAL @ end
ble 2b @ loop
mov r1,#' '
3:
strb r1,[r3,r4]
add r4,#1
cmp r4,#LGZONECAL @ end
ble 3b
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} @ save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 @ r2 <- r2 >> 2
mov r1, r0, LSR #31 @ r1 <- r0 >> 31
add r0, r2, r1 @ r0 <- r2 + r1
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2-r4}
bx lr @ return
|
http://rosettacode.org/wiki/Problem_of_Apollonius
|
Problem of Apollonius
|
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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(r2)
v14 = 2*s2*r2 - 2*s1*r1
v21 = 2*x3 - 2*x2
v22 = 2*y3 - 2*y2
v23 = sq(x2) - sq(x3) + sq(y2) - sq(y3) - sq(r2) + sq(r3)
v24 = 2*s3*r3 - 2*s2*r2
w12 = v12/v11
w13 = v13/v11
w14 = v14/v11
w22 = v22/v21 - w12
w23 = v23/v21 - w13
w24 = v24/v21 - w14
p = -w23/w22
q = w24/w22
m = -w12*p - w13
n = w14 - w12*q
a = sq(n) + sq(q) - 1
b = 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1
c = sq(x1) + sq(m) - 2*m*x1 + sq(p) + sq(y1) - 2*p*y1 - sq(r1)
d = sq(b) - 4*a*c
rs = (-b - Math.sqrt(d)) / (2*a)
xs = m + n*rs
ys = p + q*rs
new Circle(xs, ys, rs)
console.log c1 = new Circle(0, 0, 1)
console.log c2 = new Circle(2, 4, 2)
console.log c3 = new Circle(4, 0, 1)
console.log apollonius(c1, c2, c3)
console.log apollonius(c1, c2, c3, -1, -1, -1)
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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$
print "current program file (:last one on LRU list)"
print getLastLRU$(lbPath$)
end
Function getLastLRU$(lbPath$)
open lbPath$+"lbasic404.ini" for input as #1
while not(eof(#1))
line input #1, a$
if instr(a$, "recent files")<>0 then [readRecentFiles]
wend
getLastLRU$ = "* Failed: Recent files section not found *"
close #1
exit function
[readRecentFiles]
nRecent = val(word$(a$,1))
'print "nRecentFiles", nRecent
for i = 1 to nRecent
if eof(#1) then
getLastLRU$ = "* Failed: File ended while in recent files section *"
close #1
exit function
end if
line input #1, a$
'print i, a$
next
close #1
getLastLRU$ = a$
end function
|
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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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 not composite:
let n = 2 * i + 3
for k in countup(n * n, N, 2 * n):
sieve[(k - 3) div 2] = true
var primes = @[2]
for i, composite in sieve:
if not composite:
primes.add 2 * i + 3
if primes.len < NPrimes:
quit "Not enough primes. Please, increase value of N."
####################################################################################################
# Compute primorial.
import strformat
import bignum
const LastToPrint = NPrimes
iterator primorials(): Int =
## Yield successive primorial numbers.
var prim = newInt(1)
yield prim
for p in primes:
prim *= p
yield prim
var n = 0
for prim in primorials():
echo &"primorial({n}) = {prim}"
inc n
if n == 10: break
n = 0
var nextToPrint = 10
for prim in primorials():
if n == nextToPrint:
echo &"primorial({n}) has {($prim).len} digits"
if nextToPrint == LastToPrint: break
nextToPrint *= 10
inc n
echo ""
echo &"Total time: {cpuTime() - t0:.2f} s"
|
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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#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(#c)
where #c > #b
where (#a+#b+#c) <= #max_perimeter
sum 1
)
)
}
stdout(`Number of Pythagorean Triples in a Perimeter of 100: `)
stdoutnl(num_pythagorean_triples(100))
|
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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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 decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#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
-4 24 -41
q
-0.857143 0.3942857 -0.331429
-0.428571 -0.902857 0.0342857
0.2857143 -0.171429 -0.942857
r
-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 arrangements of 1 to S meeting these requirements.
|
#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))
printRow(a);
}
System.out.println();
StringBuilder s = new StringBuilder();
for (int i = 2; i <= 20; ++i) {
int[] a = new int[i];
for (int j = 0; j < i; ++j)
a[j] = j + 1;
if (i > 2)
s.append(" ");
s.append(countRows(a, 0, i));
}
System.out.println(s);
long finish = System.currentTimeMillis();
System.out.printf("\nElapsed time: %d milliseconds\n", finish - start);
}
private static void printRow(int[] a) {
for (int i = 0; i < a.length; ++i) {
if (i != 0)
System.out.print(" ");
System.out.printf("%2d", a[i]);
}
System.out.println();
}
private static boolean findRow(int[] a, int start, int length) {
if (length == 2)
return isPrime(a[start] + a[start + 1]);
for (int i = 1; i + 1 < length; i += 2) {
if (isPrime(a[start] + a[start + i])) {
swap(a, start + i, start + 1);
if (findRow(a, start + 1, length - 1))
return true;
swap(a, start + i, start + 1);
}
}
return false;
}
private static int countRows(int[] a, int start, int length) {
int count = 0;
if (length == 2) {
if (isPrime(a[start] + a[start + 1]))
++count;
} else {
for (int i = 1; i + 1 < length; i += 2) {
if (isPrime(a[start] + a[start + i])) {
swap(a, start + i, start + 1);
count += countRows(a, start + 1, length - 1);
swap(a, start + i, start + 1);
}
}
}
return count;
}
private static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
private static boolean isPrime(int n) {
return ((1L << n) & 0x28208a20a08a28acL) != 0;
}
}
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#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[(prev, i % 10)]++
prev = i % 10
I --k == 0
L.break
print(‘First #. primes. Transitions prime % 10 > next-prime % 10.’.format(limit))
L(trans) sorted(trans_map.keys())
print(‘#. -> #. count #5 frequency: #.4%’.format(trans[0], trans[1], trans_map[trans], 100.0 * trans_map[trans] / limit))
|
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, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#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 */
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessError: .asciz "\033[31mError Allocation !!!\n"
szCarriageReturn: .asciz "\n"
/* datas message display */
szMessEntete: .ascii "Number :"
sNumber: .space 12,' '
.asciz " Divisors :"
szMessResult: .ascii " "
sValue: .space 12,' '
.asciz ""
szMessDivNumber: .ascii "\nnumber divisors :"
sCounter: .space 12,' '
.asciz "\n"
szMessNumberMax: .ascii "Number :"
sNumberMax: .space 12,' '
.ascii " has "
sDivMax: .space 12, ' '
.asciz " divisors\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: @ program start
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
mov r2,#1
1:
mov r0,r2 @ number
ldr r1,iAdrsNumber @ and convert ascii string
bl conversion10
ldr r0,iAdrszMessEntete @ display result message
bl affichageMess
mov r0,r2 @ number
mov r1,#1 @ display flag
bl divisors @ display divisors
ldr r1,iAdrsCounter @ and convert ascii string
bl conversion10
ldr r0,iAdrszMessDivNumber @ display result message
bl affichageMess
add r2,r2,#1
cmp r2,#10
ble 1b
mov r2,#2
mov r3,#0
mov r4,#0
ldr r5,iMaxi
2:
mov r0,r2
mov r1,#0 @ display flag
bl divisors @ display divisors
cmp r0,r3
movgt r3,r0
movgt r4,r2
add r2,r2,#1
cmp r2,r5
ble 2b
mov r0,r4
ldr r1,iAdrsNumberMax @ and convert ascii string
bl conversion10
mov r0,r3
ldr r1,iAdrsDivMax @ and convert ascii string
bl conversion10
ldr r0,iAdrszMessNumberMax
bl affichageMess
ldr r0,iAdrszMessEndPgm @ display end message
bl affichageMess
b 100f
99: @ display error message
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessStartPgm: .int szMessStartPgm
iAdrszMessEndPgm: .int szMessEndPgm
iAdrszMessError: .int szMessError
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessResult: .int szMessResult
iAdrsValue: .int sValue
iAdrszMessDivNumber: .int szMessDivNumber
iAdrsCounter: .int sCounter
iAdrszMessEntete: .int szMessEntete
iAdrsNumber: .int sNumber
iAdrszMessNumberMax: .int szMessNumberMax
iAdrsDivMax: .int sDivMax
iAdrsNumberMax: .int sNumberMax
iMaxi: .int 20000
/******************************************************************/
/* divisors function */
/******************************************************************/
/* r0 contains the number */
/* r1 contains display flag (<>0: display, 0: no display )
/* r0 return divisors number */
divisors:
push {r1-r8,lr} @ save registers
cmp r0,#1 @ = 1 ?
movle r0,#0
ble 100f
mov r7,r0
mov r8,r1
cmp r8,#0
beq 1f
mov r0,#1 @ first divisor = 1
ldr r1,iAdrsValue @ and convert ascii string
bl conversion10
ldr r0,iAdrszMessResult @ display result message
bl affichageMess
1: @ begin loop
lsr r4,r7,#1 @ Maxi
mov r6,r4 @ first divisor
mov r5,#1 @ Counter divisors
2:
mov r0,r7 @ dividende = number
mov r1,r6 @ divisor
bl division
cmp r3,#0 @ remainder = 0 ?
bne 3f
add r5,r5,#1 @ increment counter
cmp r8,#0 @ display divisor ?
beq 3f
mov r0,r2 @ divisor
ldr r1,iAdrsValue @ and convert ascii string
bl conversion10
ldr r0,iAdrszMessResult @ display result message
bl affichageMess
3:
sub r6,r6,#1 @ decrement divisor
cmp r6,#2 @ End ?
bge 2b @ no loop
mov r0,r5 @ return divisors number
100:
pop {r1-r8,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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 involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#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 [
z: random 0.0 1.0
loop probabilities [item,prob][
if? z < prob [
unless key? samples item -> samples\[item]: 0
samples\[item]: samples\[item] + 1
break
]
else [
z: z - prob
]
]
]
[s1, s2]: 0.0
print [pad.right "Item" 10 pad "Target" 10 pad "Tesults" 10 pad "Differences" 15]
print repeat "-" 50
loop probabilities [item,prob][
r: samples\[item] // nofTrials
s1: s1 + r*100
s2: s2 + prob*100
print [
pad.right item 10
pad to :string prob 10
pad to :string round.to:4 r 10
pad to :string round.to:4 to :floating 100*1-r//prob 13 "%"
]
]
print repeat "-" 50
print [
pad.right "Total:" 10
pad to :string to :floating s2 10
pad to :string s1 10
]
|
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 between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#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 *FileOut;
char format[] = ", %lld";
int Primes[NBRPRIMES]; // table of the prime factors
int iPrimes; // max index of the prime factor table
short Ancestors[NBRANCESTORS]; // table of the parent's ancestors
struct Children {
long long Child;
struct Children *pNext;
};
struct Children *Parents[MAXPARENT+1][2]; // table pointing to the root and to the last descendants (per parent)
int CptDescendants[MAXPARENT+1]; // counter table of the descendants (per parent)
long long MaxDescendant = (long long) pow(3.0, 33.0); // greatest descendant number
short GetParent(long long child);
struct Children *AppendChild(struct Children *node, long long child);
short GetAncestors(short child);
void PrintDescendants(struct Children *node);
int GetPrimes(int primes[], int maxPrime);
int main()
{
long long Child;
short i, Parent, Level;
int TotDesc = 0;
if ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)
return 1;
for (Child = 1; Child <= MaxDescendant; Child++)
{
if (Parent = GetParent(Child))
{
Parents[Parent][1] = AppendChild(Parents[Parent][1], Child);
if (Parents[Parent][0] == NULL)
Parents[Parent][0] = Parents[Parent][1];
CptDescendants[Parent]++;
}
}
if (MAXPARENT > MAXPRIME)
if (GetPrimes(Primes, MAXPARENT) < 0)
return 1;
if (fopen_s(&FileOut, "Ancestors.txt", "w"))
return 1;
for (Parent = 1; Parent <= MAXPARENT; Parent++)
{
Level = GetAncestors(Parent);
fprintf(FileOut, "[%d] Level: %d\n", Parent, Level);
if (Level)
{
fprintf(FileOut, "Ancestors: %d", Ancestors[0]);
for (i = 1; i < Level; i++)
fprintf(FileOut, ", %d", Ancestors[i]);
}
else
fprintf(FileOut, "Ancestors: None");
if (CptDescendants[Parent])
{
fprintf(FileOut, "\nDescendants: %d\n", CptDescendants[Parent]);
strcpy_s(format, "%lld");
PrintDescendants(Parents[Parent][0]);
fprintf(FileOut, "\n");
}
else
fprintf(FileOut, "\nDescendants: None\n");
fprintf(FileOut, "\n");
TotDesc += CptDescendants[Parent];
}
fprintf(FileOut, "Total descendants %d\n\n", TotDesc);
if (fclose(FileOut))
return 1;
return 0;
}
short GetParent(long long child)
{
long long Child = child;
short Parent = 0;
short Index = 0;
while (Child > 1 && Parent <= MAXPARENT)
{
if (Index > iPrimes)
return 0;
while (Child % Primes[Index] == 0)
{
Child /= Primes[Index];
Parent += Primes[Index];
}
Index++;
}
if (Parent == child || Parent > MAXPARENT || child == 1)
return 0;
return Parent;
}
struct Children *AppendChild(struct Children *node, long long child)
{
static struct Children *NodeNew;
if (NodeNew = (struct Children *) malloc(sizeof(struct Children)))
{
NodeNew->Child = child;
NodeNew->pNext = NULL;
if (node != NULL)
node->pNext = NodeNew;
}
return NodeNew;
}
short GetAncestors(short child)
{
short Child = child;
short Parent = 0;
short Index = 0;
while (Child > 1)
{
while (Child % Primes[Index] == 0)
{
Child /= Primes[Index];
Parent += Primes[Index];
}
Index++;
}
if (Parent == child || child == 1)
return 0;
Index = GetAncestors(Parent);
Ancestors[Index] = Parent;
return ++Index;
}
void PrintDescendants(struct Children *node)
{
static struct Children *NodeCurr;
static struct Children *NodePrev;
NodeCurr = node;
NodePrev = NULL;
while (NodeCurr)
{
fprintf(FileOut, format, NodeCurr->Child);
strcpy_s(format, ", %lld");
NodePrev = NodeCurr;
NodeCurr = NodeCurr->pNext;
free(NodePrev);
}
return;
}
int GetPrimes(int primes[], int maxPrime)
{
if (maxPrime < 2)
return -1;
int Index = 0, Value = 1;
int Max, i;
primes[0] = 2;
while ((Value += 2) <= maxPrime)
{
Max = (int) floor(sqrt((double) Value));
for (i = 0; i <= Index; i++)
{
if (primes[i] > Max)
{
if (++Index >= NBRPRIMES)
return -1;
primes[Index] = Value;
break;
}
if (Value % primes[i] == 0)
break;
}
}
return Index;
}
|
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 insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#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){ ; insert and return new task
for T, P in Queue
if (T=Task) || !(Priority && Task)
return 0
return Task, Queue[Task] := Priority
}
;-----------------------------------
PQ_DelTask(Queue, Task){ ; delete and return task
for T, P in Queue
if (T = Task)
return Task, Queue.Remove(Task)
}
;-----------------------------------
PQ_Peek(Queue){ ; peek and return top priority task(s)
TopPriority := PQ_TopPriority(Queue)
for T, P in Queue
if (P = TopPriority)
PeekList .= (PeekList?"`n":"") "`t" T
return PeekList
}
;-----------------------------------
PQ_Check(Queue,Task){ ; check task and return its priority
for T, P in Queue
if (T = Task)
return P
return 0
}
;-----------------------------------
PQ_Edit(Queue,Task,Priority){ ; Update task priority and return its new priority
for T, P in Queue
if (T = Task)
return Priority, Queue[T]:=Priority
return 0
}
;-----------------------------------
PQ_View(Queue){ ; view current Queue
for T, P in Queue
Res .= P " : " T "`n"
Sort, Res, FMySort
return "Priority Queue=`n" Res
}
MySort(a,b){
RegExMatch(a,"(\d+) : (.*)", x), RegExMatch(b,"(\d+) : (.*)", y)
return x1>y1?1:x1<y1?-1: x2>y2?1:x2<y2?-1: 0
}
;-----------------------------------
PQ_TopPriority(Queue){ ; return queue's top priority
for T, P in Queue
TopPriority := TopPriority?TopPriority:P , TopPriority := TopPriority<P?TopPriority:P
return, TopPriority
}
|
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 example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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 of the problem.
t1 = How is the solution tangent (externally or internally) to c1.
t2 = How is the solution tangent (externally or internally) to c2.
t3 = How is the solution tangent (externally or internally) to c3.
Returns: The Circle that is tangent to c1, c2 and c3.
*/
Circle solveApollonius(in Circle c1, in Circle c2, in Circle c3,
in Tangent t1, in Tangent t2, in Tangent t3)
pure nothrow @safe @nogc {
alias Imd = immutable(double);
Imd s1 = (t1 == Tangent.externally) ? 1.0 : -1.0;
Imd s2 = (t2 == Tangent.externally) ? 1.0 : -1.0;
Imd s3 = (t3 == Tangent.externally) ? 1.0 : -1.0;
Imd v11 = 2 * c2.x - 2 * c1.x;
Imd v12 = 2 * c2.y - 2 * c1.y;
Imd v13 = c1.x ^^ 2 - c2.x ^^ 2 +
c1.y ^^ 2 - c2.y ^^ 2 -
c1.r ^^ 2 + c2.r ^^ 2;
Imd v14 = 2 * s2 * c2.r - 2 * s1 * c1.r;
Imd v21 = 2 * c3.x - 2 * c2.x;
Imd v22 = 2 * c3.y - 2 * c2.y;
Imd v23 = c2.x ^^ 2 - c3.x ^^ 2 +
c2.y ^^ 2 - c3.y ^^ 2 -
c2.r ^^ 2 + c3.r ^^ 2;
Imd v24 = 2 * s3 * c3.r - 2 * s2 * c2.r;
Imd w12 = v12 / v11;
Imd w13 = v13 / v11;
Imd w14 = v14 / v11;
Imd w22 = v22 / v21 - w12;
Imd w23 = v23 / v21 - w13;
Imd w24 = v24 / v21 - w14;
Imd P = -w23 / w22;
Imd Q = w24 / w22;
Imd M = -w12 * P - w13;
Imd N = w14 - w12 * Q;
Imd a = N * N + Q ^^ 2 - 1;
Imd b = 2 * M * N - 2 * N * c1.x +
2 * P * Q - 2 * Q * c1.y +
2 * s1 * c1.r;
Imd c = c1.x ^^ 2 + M ^^ 2 - 2 * M * c1.x +
P ^^ 2 + c1.y ^^ 2 - 2 * P * c1.y - c1.r ^^ 2;
// find a root of a quadratic equation.
// This requires the circle centers not to be e.g. colinear
Imd D = b ^^ 2 - 4 * a * c;
Imd rs = (-b - D.sqrt) / (2 * a);
return Circle(M + N * rs, P + Q * rs, rs);
}
void main() {
immutable c1 = Circle(0.0, 0.0, 1.0);
immutable c2 = Circle(4.0, 0.0, 1.0);
immutable c3 = Circle(2.0, 4.0, 2.0);
alias Te = Tangent.externally;
solveApollonius(c1, c2, c3, Te, Te, Te).writeln;
alias Ti = Tangent.internally;
solveApollonius(c1, c2, c3, Ti, Ti, Ti).writeln;
}
|
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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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);
until cnt = i;
mp_primorial(ctx.prime,x);
s:= mp_adecimal(x);
writeln('MaxPrime ',ctx.prime:10,length(s):8,' digits');
i := 10*i;
until i > 1000*1000;
t1 := time;
Writeln((t1-t0)*86400.0:10:3,' s');
end.
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#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
term1 =2 *m *n
term2 =m *m -n *n
term3 =m *m +n *n
perimeter =term1 +term2 +term3
if perimeter <=perimeterLimit then triples =triples +1
a =term1
b =term2
do
r = a mod b
a =b
b =r
loop until r <=0
if ( a =1) and ( perimeter <=perimeterLimit) then 'we've found a primitive triple if a =1, since hcf =1. And it is inside perimeter range. Save it in an array
primitives =primitives +1
if term1 >term2 then temp =term1: term1 =term2: term2 =temp 'swap so in increasing order of side length
nEx =int( perimeterLimit /perimeter) 'We have the primitive & removed any multiples. Now calculate ALL the multiples in range.
extras =extras +nEx
end if
scan
next n
next m
print " Number of primitives having perimeter below "; 10^power, " was "; primitives, " & "; extras, " non-primitive triples."
print time$()
next power
print "End"
end
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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 decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#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): String = {
val sw = new StringWriter
m.print(new PrintWriter(sw, true), 8, 6)
sw.toString
}
print(toString(d.getQ))
print(toString(d.getR))
}
|
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 arrangements of 1 to S meeting these requirements.
|
#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.threads for e in collect(permutations(2:2:r))
p = zeros(Int, r - 1)
for o in permutations(3:2:r)
i = 0
for (x, y) in zip(e, o)
p[i += 1] = x
p[i += 1] = y
end
length(e) > length(o) && (p[i += 1] = e[end])
if pmask[p[i] + r + 1] && pmask[p[begin] + 1] && all(j -> pmask[p[j] + p[j + 1]], 1:r-2)
lock(spinlock)
if counts[r] == 0
rowstrings[r] = " 1" * prod([lpad(n, 3) for n in p]) * lpad(r + 1, 3) * "\n"
end
counts[r] += 1
unlock(spinlock)
end
end
end
end
println(" 1 2\n" * prod(rowstrings), "\n", counts)
end
@time primetriangle(16)
|
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 arrangements of 1 to S meeting these requirements.
|
#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;
for my $e (permutations [@even_nums]) {
next if $$e[0] == 8 or $$e[0] == 14;
my $nope = 0;
for my $o (permutations [@odd_nums]) {
my @list = (zip(@$e, @$o), $n); # 'zip' makes a list with a gap if more evens than odds
splice @list, -2, -1 if not defined $list[-2]; # in which case splice out 'undef' in next-to-last position
my $it = slideatatime(1, 2, @list);
while ( my @rr = $it->() ) {
last unless defined $rr[1];
$nope++ and last unless is_prime $rr[0]+$rr[1];
}
unless ($nope) {
say '1 ' . join ' ', @list unless $count[$n];
$count[$n]++;
}
$nope = 0;
}
}
}
say "\n" . join ' ', @count[2..$#count];
|
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
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#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 OVER bits width;
b[ w ] := ( ( 1 + ( n MOD bits width ) ) CLEAR b[ w ] );
b
END # SET # ;
OP ELEM = ( INT n, REF[]BITS b )BOOL: ( 1 + ( n MOD bits width ) ) ELEM b[ n OVER bits width ];
# constructs a bit array long enough to hold n values #
OP BITARRAY = ( INT n )REF[]BITS: HEAP[ 0 : n OVER bits width ]BITS;
# construct a BITS value of all TRUE #
BITS all true = BEGIN
BITS v := 16r0;
FOR bit TO bits width DO v := bit SET v OD;
v
END;
# initialises a bit array to all TRUE #
OP SETALL = ( REF[]BITS b )REF[]BITS:
BEGIN
FOR p FROM LWB b TO UPB b DO b[ p ] := all true OD;
b
END # SETALL # ;
# construct a sieve initialised to all TRUE apart from the first bit #
INT sieve max = 15 500 000; # somewhat larger than the 1 000 000th prime #
INT prime max = 1 000 000;
REF[]BITS sieve = 1 CLEAR SETALL BITARRAY sieve max;
# sieve the primes #
FOR s FROM 2 TO ENTIER sqrt( sieve max ) DO
IF s ELEM sieve
THEN
FOR p FROM s * s BY s TO sieve max DO p CLEAR sieve OD
FI
OD;
# count the number of times each combination of #
# ( last digit of previous prime, last digit of prime ) occurs #
[ 0 : 9, 0 : 9 ]INT counts;
FOR p FROM 0 TO 9 DO FOR n FROM 0 TO 9 DO counts[ p, n ] := 0 OD OD;
INT previous prime := 2;
INT primes found := 1;
FOR p FROM 3 TO sieve max WHILE primes found < prime max DO
IF p ELEM sieve
THEN
primes found +:= 1;
counts[ previous prime MOD 10, p MOD 10 ] +:= 1;
previous prime := p
FI
OD;
# print the counts #
# there are thus 4 possible final digits: 1, 3, 7, 9 #
STRING labels = "123456789"; # "labels" for the counts #
INT total := 0;
FOR p TO 9 DO FOR n TO 9 DO total +:= counts[ p, n ] OD OD;
print( ( whole( primes found, 0 ), " primes, last prime considered: ", previous prime, newline ) );
FOR p TO 9 DO
FOR n TO 9 DO
IF counts[ p, n ] /= 0
THEN
print( ( labels[ p ], "->", labels[ n ]
, whole( counts[ p, n ], -8 )
, fixed( ( 100 * counts[ p, n ] ) / total, -8, 2 )
, newline
)
)
FI
OD
OD
|
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, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#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 with the most proper divisors (" maxProperDivisors ") is" maxN]
|
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 involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#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 ; auxiliary data
Loop % n-1
i := A_Index-1, r%A_Index% := r%i% + p%A_Index% ; cummulative distribution
Loop 1000000 {
Random R, 0, 1.0
Loop %n% ; linear search
If (R < r%A_Index%) {
c%A_Index%++
Break
}
}
; Output
Loop %n%
t .= s%A_Index% "`t" p%A_Index% "`t" c%A_Index%*1.0e-6 "`n"
Msgbox %t%
/*
output:
---------------------------
aleph 0.200000 0.199960
beth 0.166667 0.166146
gimel 0.142857 0.142624
daleth 0.125000 0.124924
he 0.111111 0.111226
waw 0.100000 0.100434
zayin 0.090909 0.091344
heth 0.063456 0.063342
---------------------------
*/
|
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 between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#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 && a != n; ) {
n = a;
a = ancestor[n];
result.push_back(n);
}
return result;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty()) {
std::cout << "none\n";
return;
}
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
for (integer p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return false;
}
return true;
}
int main(int argc, char** argv) {
const size_t limit = 100;
std::vector<integer> ancestor(limit, 0);
std::vector<std::vector<integer>> descendants(limit);
for (size_t prime = 0; prime < limit; ++prime) {
if (!is_prime(prime))
continue;
descendants[prime].push_back(prime);
for (size_t i = 0; i + prime < limit; ++i) {
integer s = i + prime;
for (integer n : descendants[i]) {
integer prod = n * prime;
descendants[s].push_back(prod);
if (prod < limit)
ancestor[prod] = s;
}
}
}
// print the results
size_t total_descendants = 0;
for (integer i = 1; i < limit; ++i) {
std::vector<integer> ancestors(get_ancestors(ancestor, i));
std::cout << "[" << i << "] Level: " << ancestors.size() << '\n';
std::cout << "Ancestors: ";
std::sort(ancestors.begin(), ancestors.end());
print_vector(ancestors);
std::cout << "Descendants: ";
std::vector<integer>& desc = descendants[i];
if (!desc.empty()) {
std::sort(desc.begin(), desc.end());
if (desc[0] == i)
desc.erase(desc.begin());
}
std::cout << desc.size() << '\n';
total_descendants += desc.size();
if (!desc.empty())
print_vector(desc);
std::cout << '\n';
}
std::cout << "Total descendants: " << total_descendants << '\n';
return 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 insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#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,b) == construct(a,b)$Rep @ %
elt(x,"key"):Key == (x@Rep).k
elt(x,"entry"):Entry == (x@Rep).e
x < y == x.key < y.key
x = y == x.key = y.key
hash x == hash(x.key)
if Entry has CoercibleTo OutputForm then
coerce(x):OutputForm == bracket [(x.key)::OutputForm,(x.entry)::OutputForm]
)abbrev Domain PRIORITY PriorityQueue
S ==> OrderedKeyEntry(Key,Entry)
PriorityQueue(Key:OrderedSet,Entry:SetCategory): Exports == Implementation where
Exports == PriorityQueueAggregate S with
heap : List S -> %
setelt: (%,Key,Entry) -> Entry
Implementation == Heap(S) add
setelt(x:%,key:Key,entry:Entry) ==
insert!(construct(key,entry)$S,x)
entry
|
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 example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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 x2 = c2.center[0]
let y2 = c2.center[1]
let r2 = c2.radius
let x3 = c3.center[0]
let y3 = c3.center[1]
let r3 = c3.radius
let v11 = 2.0 * x2 - 2.0 * x1
let v12 = 2.0 * y2 - 2.0 *y1
let v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2
let v14 = 2.0 * s2 * r2 - 2.0 * s1 * r1
let v21 = 2.0 * x3 - 2.0 * x2
let v22 = 2.0 * y3 - 2.0 * y2
let v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3
let v24 = 2.0 * s3 * r3 - 2 * s2 * r2
let w12 = v12 / v11
let w13 = v13 / v11
let w14 = v14 / v11
let w22 = v22 / v21-w12
let w23 = v23 / v21-w13
let w24 = v24 / v21-w14
let p = -w23 / w22
let q = w24 / w22
let m = -w12 * p - w13
let n = w14 - w12 * q
let a = n * n + q * q - 1.0
let b = 2.0 * m * n - 2.0 * n * x1 + 2 * p * q - 2.0 * q * y1 + 2.0 * s1 * r1
let c = x1 * x1 + m * m - 2.0 * m * x1 + p * p + y1 * y1 - 2.0 * p * y1 - r1 * r1
let d = b * b - 4.0 * a * c
let rs = (-b - sqrt(d)) / (2.0 * a)
let xs = m + n * rs
let ys = p + q * rs
Circle(center: [xs,ys], radius: rs)
}
let c1 = Circle(center: [0.0, 0.0], radius: 1.0)
let c2 = Circle(center: [4.0, 0.0], radius: 1.0)
let c3 = Circle(center: [2.0, 4.0], radius: 2.0)
print(solveApollonius(c1, c2, c3, 1.0, 1.0, 1.0))
print(solveApollonius(c1, c2, c3, -1.0, -1.0, -1.0))
|
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 example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#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 = n*n + q*q - 1
b = 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1
c = x1*x1 + m*m - 2*m*x1 + p*p + y1*y1 - 2*p*y1 - r1*r1
d = b*b - 4*a*c
rs = (-b - :math.sqrt(d)) / (2*a)
{m + n*rs, p + q*rs, rs}
end
defp calc({x1, y1, r1}, {x2, y2, r2}, s1, s2) do
v1 = x2 - x1
{(y2 - y1) / v1, (x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2) / (2*v1), (s2*r2 - s1*r1) / v1}
end
end
c1 = {0, 0, 1}
c2 = {2, 4, 2}
c3 = {4, 0, 1}
IO.inspect Circle.apollonius(c1, c2, c3, 1, 1, 1)
IO.inspect Circle.apollonius(c1, c2, c3, -1, -1, -1)
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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 ARGV.
See also Command-line arguments
Examples from GitHub.
|
#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
Print Mid$(a$, Rinstr(a$, "\")+1)="m2000.exe"
}
Checkit
\\ command$ return the file's path plus name of script
\\ we can use edit "callme.gsb" to paste these, and use USE callme to call it from M2000 console.
Module SayIt {
Show
Print command$
a$=key$
}
SayIt
|
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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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×7)
primorial(5) = 2310 (2×3×5×7×11)
primorial(6) = 30030 (2×3×5×7×11×13)
∙ ∙ ∙
To express this mathematically, primorialn is
the product of the first n (successive) primes:
p
r
i
m
o
r
i
a
l
n
=
∏
k
=
1
n
p
r
i
m
e
k
{\displaystyle primorial_{n}=\prod _{k=1}^{n}prime_{k}}
─── where
p
r
i
m
e
k
{\displaystyle prime_{k}}
is the kth prime number.
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
Task
Show the first ten primorial numbers (0 ──► 9, inclusive).
Show the length of primorial numbers whose index is: 10 100 1,000 10,000 and 100,000.
Show the length of the one millionth primorial number (optional).
Use exact integers, not approximations.
By length (above), it is meant the number of decimal digits in the numbers.
Related tasks
Sequence of primorial primes
Factorial
Fortunate_numbers
See also
the MathWorld webpage: primorial
the Wikipedia webpage: primorial.
the OEIS webpage: A002110.
|
#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])
end for
s = s[1..ceil(length(s)/2)]
end while
end if
return s[1]
end function
constant t0 = time(),
max10 = iff(platform()=JS?4:6),
tests = tagset(9,0)&sq_power(10,tagset(max10)),
primes = get_primes(1_000_000)
for i=1 to length(tests) do
integer ti = tests[i]
mpz primorial = vecprod(primes[1..ti])
string ps = iff(ti<10?sprintf("= %s",{mpz_get_str(primorial,comma_fill:=true)})
:sprintf("has %,d digits",mpz_sizeinbase(primorial,10)))
printf(1,"Primorial(%,d) %s\n", {ti, ps})
end for
?elapsed(time()-t0)
|
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, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#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 decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#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, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
regResult := polyfit(x, y, 2);
in
"q:\n" ++ delimit(delimit(floatToString(qrResult[1], 6), ','), '\n') ++ "\n\n" ++
"r:\n" ++ delimit(delimit(floatToString(qrResult[2], 1), ','), '\n') ++ "\n\n" ++
"polyfit:\n" ++ "[" ++ delimit(floatToString(regResult, 1), ',') ++ "]";
//---Polynomial Regression---
polyfit(x(1), y(1), n) :=
let
a[j] := x ^ j foreach j within 0 ... n;
in
lsqr(transpose(a), transpose([y]));
lsqr(a(2), b(2)) :=
let
qrDecomp := qr(a);
prod := mm(transpose(qrDecomp[1]), b);
in
solveUT(qrDecomp[2], prod);
solveUT(r(2), b(2)) :=
let
n := size(r[1]);
in
solveUTHelper(r, b, n, duplicate(0.0, n));
solveUTHelper(r(2), b(2), k, x(1)) :=
let
n := size(r[1]);
newX := setElementAt(x, k, (b[k][1] - sum(r[k][(k+1) ... n] * x[(k+1) ... n])) / r[k][k]);
in
x when k <= 0
else
solveUTHelper(r, b, k - 1, newX);
//---QR Decomposition---
qr(A(2)) := qrHelper(A, id(size(A)), 1);
qrHelper(A(2), Q(2), i) :=
let
m := size(A);
n := size(A[1]);
householder := makeHouseholder(A[i ... m, i]);
H[j,k] :=
householder[j - i + 1][k - i + 1] when j >= i and k >= i
else
1.0 when j = k else 0.0
foreach j within 1 ... m,
k within 1 ... m;
in
[Q,A] when i > (n - 1 when m = n else n)
else
qrHelper(mm(H, A), mm(Q, H), i + 1);
makeHouseholder(a(1)) :=
let
v := [1.0] ++ tail(a / (a[1] + sqrt(sum(a ^ 2)) * sign(a[1])));
H := id(size(a)) - (2.0 / mm([v], transpose([v])))[1,1] * mm(transpose([v]), [v]);
in
H;
//---Utilities---
id(n)[i,j] := 1.0 when i = j else 0.0
foreach i within 1 ... n,
j within 1 ... n;
mm(A(2), B(2))[i,j] := sum( A[i] * transpose(B)[j] );
|
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 arrangements of 1 to S meeting these requirements.
|
#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]
if n-done<=1 then
if can_follow[ad][n] then
if bFirst then
printf(1,"%s\n",join(arrang,fmt:="%d"))
bFirst = false
end if
res += 1
end if
else
done += 1
-- as per talk page, we only need to examine odd
-- numbers following an even number & vice versa
for i=done to n-1 by 2 do
integer ai = arrang[i]
if can_follow[ad][ai] then
integer aid = arrang[done]
arrang[i] = aid
arrang[done] = ai
res = ptrs(res,n,done)
arrang[i] = ai
arrang[done] = aid
end if
end for
end if
return res
end function
function prime_triangle(integer n)
can_follow = repeat(repeat(false,n),n)
for i=1 to n do
for j=1 to n do
can_follow[i][j] = is_prime(i+j)
end for
end for
arrang = tagset(n)
bFirst = true
return ptrs(0,n,1)
end function
sequence res = apply(tagset(20,2),prime_triangle)
printf(1,"%s\n",join(res,fmt:="%d"))
?elapsed(time()-t0)
|
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 the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#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
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#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) or (n mod (i + 16) = 0) or ¬
(n mod (i + 22) = 0) or (n mod (i + 24) = 0)) then return false
end repeat
return true
end isPrime
on conspiracy(limit)
script o
property counters : {{0, 0, 0, 0, 0, 0, 0, 0, 0}}
end script
repeat 8 times
copy beginning of o's counters to end of o's counters
end repeat
if (limit > 1) then
set primeCount to 1
set i to 2 -- First prime.
set n to 3 -- First number to test for primality.
repeat until (primeCount = limit)
if (isPrime(n)) then
set primeCount to primeCount + 1
set j to n mod 10
set item j of item i of o's counters to (item j of item i of o's counters) + 1
set i to j
end if
set n to n + 2
end repeat
end if
set output to {"First " & limit & " primes: transitions between end digits of consecutive primes."}
set totalTransitions to limit - 1
repeat with i in {1, 2, 3, 5, 7, 9}
set iTransitions to 0
repeat with j from 1 to 9 by 2
set iTransitions to iTransitions + (item j of item i of o's counters)
end repeat
repeat with j from 1 to 9 by 2
set ijCount to item j of item i of o's counters
if (ijCount > 0) then ¬
set end of output to ¬
(i as text) & " → " & j & ¬
(" count: " & ijCount) & ¬
(" preference for " & j & ": " & (ijCount * 10000 / iTransitions as integer) / 100) & ¬
("% overall occurrence: " & (ijCount * 10000 / totalTransitions as integer) / 100 & "%")
end repeat
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
end conspiracy
conspiracy(1000000)
|
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, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#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
No community queries yet
The top public SQL queries from the community will appear here once available.