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/Pythagoras_tree
|
Pythagoras tree
|
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).
Related tasks
Fractal tree
|
#Wren
|
Wren
|
import "graphics" for Canvas, Color
import "dome" for Window
import "./polygon" for Polygon
var DepthLimit = 7
var Hue = 0.15
class PythagorasTree {
construct new(width, height) {
Window.title = "Pythagoras Tree"
Window.resize(width, height)
Canvas.resize(width, height)
}
init() {
Canvas.cls(Color.white)
drawTree(275, 500, 375, 500, 0)
}
drawTree(x1, y1, x2, y2, depth) {
if (depth == DepthLimit) return
var dx = x2 - x1
var dy = y1 - y2
var x3 = x2 - dy
var y3 = y2 - dx
var x4 = x1 - dy
var y4 = y1 - dx
var x5 = x4 + 0.5 * (dx - dy)
var y5 = y4 - 0.5 * (dx + dy)
// draw a square
var col = Color.hsv((Hue + depth * 0.02) * 360, 1, 1)
var square = Polygon.quick([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])
square.drawfill(col)
square.draw(Color.lightgray)
// draw a triangle
col = Color.hsv((Hue + depth * 0.035) * 360, 1, 1)
var triangle = Polygon.quick([[x3, y3], [x4, y4], [x5, y5]])
triangle.drawfill(col)
triangle.draw(Color.lightgray)
drawTree(x4, y4, x5, y5, depth + 1)
drawTree(x5, y5, x3, y3, depth + 1)
}
update() {}
draw(alpha) {}
}
var Game = PythagorasTree.new(640, 640)
|
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.
|
#Batch_File
|
Batch File
|
if condition exit
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#BBC_BASIC
|
BBC BASIC
|
IF condition% THEN QUIT
|
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}}
|
#Java
|
Java
|
import Jama.Matrix;
import Jama.QRDecomposition;
public class Decompose {
public static void main(String[] args) {
var matrix = new Matrix(new double[][] {
{12, -51, 4},
{ 6, 167, -68},
{-4, 24, -41},
});
var qr = new QRDecomposition(matrix);
qr.getQ().print(10, 4);
qr.getR().print(10, 4);
}
}
|
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.
|
#D
|
D
|
#!/usr/bin/env rdmd
import std.stdio;
void main(in string[] args) {
writeln("Program: ", args[0]);
}
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Dart
|
Dart
|
#!/usr/bin/env dart
main() {
var program = new Options().script;
print("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.
|
#C.2B.2B
|
C++
|
#include <gmpxx.h>
#include <primesieve.hpp>
#include <cstdint>
#include <iomanip>
#include <iostream>
size_t digits(const mpz_class& n) { return n.get_str().length(); }
mpz_class primorial(unsigned int n) {
mpz_class p;
mpz_primorial_ui(p.get_mpz_t(), n);
return p;
}
int main() {
uint64_t index = 0;
primesieve::iterator pi;
std::cout << "First 10 primorial numbers:\n";
for (mpz_class pn = 1; index < 10; ++index) {
unsigned int prime = pi.next_prime();
std::cout << index << ": " << pn << '\n';
pn *= prime;
}
std::cout << "\nLength of primorial number whose index is:\n";
for (uint64_t power = 10; power <= 1000000; power *= 10) {
uint64_t prime = primesieve::nth_prime(power);
std::cout << std::setw(7) << power << ": "
<< digits(primorial(prime)) << '\n';
}
return 0;
}
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, 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
|
#F.23
|
F#
|
let isqrt n =
let rec iter t =
let d = n - t*t
if (0 <= d) && (d < t+t+1) // t*t <= n < (t+1)*(t+1)
then t else iter ((t+(n/t))/2)
iter 1
let rec gcd a b =
let t = a % b
if t = 0 then b else gcd b t
let coprime a b = gcd a b = 1
let num_to ms =
let mutable ctr = 0
let mutable prim_ctr = 0
let max_m = isqrt (ms/2)
for m = 2 to max_m do
for j = 0 to (m/2) - 1 do
let n = m-(2*j+1)
if coprime m n then
let s = 2*m*(m+n)
if s <= ms then
ctr <- ctr + (ms/s)
prim_ctr <- prim_ctr + 1
(ctr, prim_ctr)
let show i =
let s, p = num_to i in
printfn "For perimeters up to %d there are %d total and %d primitive" i s p;;
List.iter show [ 100; 1000; 10000; 100000; 1000000; 10000000; 100000000 ]
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#VBA
|
VBA
|
Public Sub quine()
quote = Chr(34)
comma = Chr(44)
cont = Chr(32) & Chr(95)
n = Array( _
"Public Sub quine()", _
" quote = Chr(34)", _
" comma = Chr(44)", _
" cont = Chr(32) & Chr(95)", _
" n = Array( _", _
" For i = 0 To 4", _
" Debug.Print n(i)", _
" Next i", _
" For i = 0 To 15", _
" Debug.Print quote & n(i) & quote & comma & cont", _
" Next i", _
" Debug.Print quote & n(15) & quote & Chr(41)", _
" For i = 5 To 15", _
" Debug.Print n(i)", _
" Next i", _
"End Sub")
For i = 0 To 4
Debug.Print n(i)
Next i
For i = 0 To 14
Debug.Print quote & n(i) & quote & comma & cont
Next i
Debug.Print quote & n(15) & quote & Chr(41)
For i = 5 To 15
Debug.Print n(i)
Next i
End Sub
|
http://rosettacode.org/wiki/Pythagoras_tree
|
Pythagoras tree
|
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).
Related tasks
Fractal tree
|
#Yabasic
|
Yabasic
|
Sub pythagoras_tree(x1, y1, x2, y2, depth)
local dx, dy, x3, y3, x4, y4, x5, y5
If depth > limit Return
dx = x2 - x1 : dy = y1 - y2
x3 = x2 - dy : y3 = y2 - dx
x4 = x1 - dy : y4 = y1 - dx
x5 = x4 + (dx - dy) / 2
y5 = y4 - (dx + dy) / 2
//draw the box
color 255 - depth * 20, 255, 0
fill triangle x1, y1, x2, y2, x3, y3
fill triangle x3, y3, x4, y4, x1, y1
fill triangle x4, y4, x5, y5, x3, y3
pythagoras_tree(x4, y4, x5, y5, depth +1)
pythagoras_tree(x5, y5, x3, y3, depth +1)
End Sub
// ------=< MAIN >=------
w = 800 : h = int(w * 11 / 16)
w2 = int(w / 2) : diff = int(w / 12)
limit = 12
open window w, h
//backcolor 0, 0, 0
clear window
pythagoras_tree(w2 - diff, h -10 , w2 + diff , h -10 , 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.
|
#Befunge
|
Befunge
|
_@
|
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.
|
#Bracmat
|
Bracmat
|
#include <stdlib.h>
/* More "natural" way of ending the program: finish all work and return
from main() */
int main(int argc, char **argv)
{
/* work work work */
...
return 0; /* the return value is the exit code. see below */
}
if(problem){
exit(exit_code);
/* On unix, exit code 0 indicates success, but other OSes may follow
different conventions. It may be more portable to use symbols
EXIT_SUCCESS and EXIT_FAILURE; it all depends on what meaning
of codes are agreed upon.
*/
}
|
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}}
|
#Julia
|
Julia
|
Q, R = qr([12 -51 4; 6 167 -68; -4 24 -41])
|
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.
|
#Delphi
|
Delphi
|
program ProgramName;
{$APPTYPE CONSOLE}
begin
Writeln('Program name: ' + ParamStr(0));
Writeln('Command line: ' + CmdLine);
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.
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
!print( "Name of this file: " get-from !args 0 )
|
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.
|
#Clojure
|
Clojure
|
(ns example
(:gen-class))
; Generate Prime Numbers (Implementation from RosettaCode--link above)
(defn primes-hashmap
"Infinite sequence of primes using an incremental Sieve or Eratosthenes with a Hashmap"
[]
(letfn [(nxtoddprm [c q bsprms cmpsts]
(if (>= c q) ;; only ever equal
; Update cmpsts with primes up to sqrt c
(let [p2 (* (first bsprms) 2),
nbps (next bsprms),
nbp (first nbps)]
(recur (+ c 2) (* nbp nbp) nbps (assoc cmpsts (+ q p2) p2)))
(if (contains? cmpsts c)
; Not prime
(recur (+ c 2) q bsprms
(let [adv (cmpsts c), ncmps (dissoc cmpsts c)]
(assoc ncmps
(loop [try (+ c adv)] ;; ensure map entry is unique
(if (contains? ncmps try)
(recur (+ try adv))
try))
adv)))
; prime
(cons c (lazy-seq (nxtoddprm (+ c 2) q bsprms cmpsts))))))]
(do (def baseoddprms (cons 3 (lazy-seq (nxtoddprm 5 9 baseoddprms {}))))
(cons 2 (lazy-seq (nxtoddprm 3 9 baseoddprms {}))))))
;; Generate Primorial Numbers
(defn primorial [n]
" Function produces the nth primorial number"
(if (= n 0)
1 ; by definition
(reduce *' (take n (primes-hashmap))))) ; multiply first n primes (retrieving primes from lazy-seq which generates primes as needed)
;; Show Results
(let [start (System/nanoTime)
elapsed-secs (fn [] (/ (- (System/nanoTime) start) 1e9))] ; System start time
(doseq [i (concat (range 10) [1e2 1e3 1e4 1e5 1e6])
:let [p (primorial i)]] ; Generate ith primorial number
(if (< i 10)
(println (format "primorial ( %7d ) = %10d" i (biginteger p))) ; Output for first 10
(println (format "primorial ( %7d ) has %8d digits\tafter %.3f secs" ; Output with time since starting for remainder
(long i) (count (str p)) (elapsed-secs))))))
|
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
|
#Factor
|
Factor
|
USING: accessors arrays formatting kernel literals math
math.functions math.matrices math.ranges sequences ;
IN: rosettacode.pyth
CONSTANT: T1 {
{ 1 2 2 }
{ -2 -1 -2 }
{ 2 2 3 }
}
CONSTANT: T2 {
{ 1 2 2 }
{ 2 1 2 }
{ 2 2 3 }
}
CONSTANT: T3 {
{ -1 -2 -2 }
{ 2 1 2 }
{ 2 2 3 }
}
CONSTANT: base { 3 4 5 }
TUPLE: triplets-count primitives total ;
: <0-triplets-count> ( -- a ) 0 0 \ triplets-count boa ;
: next-triplet ( triplet T -- triplet' ) [ 1array ] [ m. ] bi* first ;
: candidates-triplets ( seed -- candidates )
${ T1 T2 T3 } [ next-triplet ] with map ;
: add-triplets ( current-triples limit triplet -- stop )
sum 2dup > [
/i [ + ] curry change-total
[ 1 + ] change-primitives drop t
] [ 3drop f ] if ;
: all-triplets ( current-triples limit seed -- triplets )
3dup add-triplets [
candidates-triplets [ all-triplets ] with swapd reduce
] [ 2drop ] if ;
: count-triplets ( limit -- count )
<0-triplets-count> swap base all-triplets ;
: pprint-triplet-count ( limit count -- )
[ total>> ] [ primitives>> ] bi
"Up to %d: %d triples, %d primitives.\n" printf ;
: pyth ( -- )
8 [1,b] [ 10^ dup count-triplets pprint-triplet-count ] each ;
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#Verbexx
|
Verbexx
|
@VAR s = «@SAY (@FORMAT fmt:"@VAR s = %c%s%c;" 0x00AB s 0x00BB) s no_nl:;»; @SAY (@FORMAT fmt:"@VAR s = %c%s%c;" 0x00AB s 0x00BB) s no_nl:;
|
http://rosettacode.org/wiki/Pythagoras_tree
|
Pythagoras tree
|
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).
Related tasks
Fractal tree
|
#zkl
|
zkl
|
fcn pythagorasTree{
bitmap:=PPM(640,640,0xFF|FF|FF); // White background
fcn(bitmap, ax,ay, bx,by, depth=0){
if(depth>10) return();
dx,dy:=bx-ax, ay-by;
x3,y3:=bx-dy, by-dx;
x4,y4:=ax-dy, ay-dx;
x5,y5:=x4 + (dx - dy)/2, y4 - (dx + dy)/2;
bitmap.cross(x3,y3);bitmap.cross(x4,y4);bitmap.cross(x5,y5);
bitmap.line(ax,ay, bx,by, 0); bitmap.line(bx,by, x3,y3, 0);
bitmap.line(x3,y3, x4,y4, 0); bitmap.line(x4,y4, ax,ay, 0);
self.fcn(bitmap,x4,y4, x5,y5, depth+1);
self.fcn(bitmap,x5,y5, x3,y3, depth+1);
}(bitmap,275,500, 375,500);
bitmap.writeJPGFile("pythagorasTree.jpg",True);
}();
|
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.
|
#C
|
C
|
#include <stdlib.h>
/* More "natural" way of ending the program: finish all work and return
from main() */
int main(int argc, char **argv)
{
/* work work work */
...
return 0; /* the return value is the exit code. see below */
}
if(problem){
exit(exit_code);
/* On unix, exit code 0 indicates success, but other OSes may follow
different conventions. It may be more portable to use symbols
EXIT_SUCCESS and EXIT_FAILURE; it all depends on what meaning
of codes are agreed upon.
*/
}
|
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.
|
#C.23
|
C#
|
if (problem)
{
Environment.Exit(1);
}
|
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}}
|
#Maple
|
Maple
|
with(LinearAlgebra):
A:=<12,-51,4;6,167,-68;-4,24,-41>:
Q,R:=QRDecomposition(A):
Q;
R;
|
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.
|
#EchoLisp
|
EchoLisp
|
(js-eval "window.location.href")
→ "http://www.echolalie.org/echolisp/"
|
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.
|
#Elena
|
Elena
|
import extensions;
public program()
{
console.printLine(program_arguments.asEnumerable()); // the whole command line
console.printLine(program_arguments[0]); // the program 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.
|
#CLU
|
CLU
|
% This program uses the 'bigint' cluster from
% the 'misc.lib' included with PCLU.
isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then return(s) end
x1: int := (x0 + s/x0)/2
while x1 < x0 do
x0 := x1
x1 := (x0 + s/x0)/2
end
return(x0)
end isqrt
sieve = proc (n: int) returns (array[bool])
prime: array[bool] := array[bool]$fill(0,n+1,true)
prime[0] := false
prime[1] := false
for p: int in int$from_to(2, isqrt(n)) do
if prime[p] then
for c: int in int$from_to_by(p*p,n,p) do
prime[c] := false
end
end
end
return(prime)
end sieve
% Calculate the N'th primorial given a boolean array denoting primes
primorial = proc (n: int, prime: array[bool])
returns (bigint) signals (out_of_primes)
% 0'th primorial = 1
p: bigint := bigint$i2bi(1)
for i: int in array[bool]$indexes(prime) do
if ~prime[i] then continue end
if n=0 then break end
p := p * bigint$i2bi(i)
n := n-1
end
if n>0 then signal out_of_primes end
return(p)
end primorial
% Find the length in digits of a bigint without converting it to a string.
% The naive way takes over an hour to count the digits for p(100000),
% this one ~5 minutes.
n_digits = proc (n: bigint) returns (int)
own zero: bigint := bigint$i2bi(0)
own ten: bigint := bigint$i2bi(10)
digs: int := 1
dstep: int := 1
tenfac: bigint := ten
step: bigint := ten
while n >= tenfac do
digs := digs + dstep
step := step * ten
dstep := dstep + 1
next: bigint := tenfac*step
if n >= next then
tenfac := next
else
step, dstep := ten, 1
tenfac := tenfac*step
end
end
return(digs)
end n_digits
start_up = proc ()
po: stream := stream$primary_output()
% Sieve a million primes
prime: array[bool] := sieve(15485863)
% Show the first 10 primorials
for i: int in int$from_to(0,9) do
stream$puts(po, "primorial(" || int$unparse(i) || ") = ")
stream$putright(po, bigint$unparse(primorial(i, prime)), 15)
stream$putl(po, "")
end
% Show the length of some bigger primorial numbers
for tpow: int in int$from_to(1,5) do
p_ix: int := 10**tpow
stream$puts(po, "length of primorial(")
stream$putright(po, int$unparse(p_ix), 7)
stream$puts(po, ") = ")
stream$putright(po, int$unparse(n_digits(primorial(p_ix, prime))), 7)
stream$putl(po, "")
end
end start_up
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defun primorial-number-length (n w)
(values (primorial-number n) (primorial-length w)))
(defun primorial-number (n)
(loop for a below n collect (primorial a)))
(defun primorial-length (w)
(loop for a in w collect (length (write-to-string (primorial a)))))
(defun primorial (n &optional (m 1) (k -1) (z 1) &aux (f (primep m)))
(if (= k n) z (primorial n (1+ m) (+ k (if f 1 0)) (if f (* m z) z))))
(defun primep (n)
(loop for a from 2 to (isqrt n) never (zerop (mod n a))))
|
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
|
#Forth
|
Forth
|
\ Two methods to create Pythagorean Triples
\ this code has been tested using Win32Forth and gforth
: pythag_fibo ( f1 f0 -- )
\ Create Pythagorean Triples from 4 element Fibonacci series
\ this is called with the first two members of a 4 element Fibonacci series
\ Price and Burkhart have two good articles about this method
\ "Pythagorean Tree: A New Species" and
\ "Heron's Formula, Descartes Circles, and Pythagorean Triangles"
\ Horadam found out how to compute Pythagorean Triples from Fibonacci series
\ compute the two other members of the Fibonacci series and put them in
\ local variables. I was unable to do this with out using locals
2DUP + 2DUP + 2OVER 2DUP + 2DUP +
LOCALS| f3 f2 f1 f0 |
wk_level @ 9 .r f0 8 .r f1 8 .r f2 8 .r f3 8 .r
\ this block calculates the sides of the Pythagorean Triangle using single precision
\ f0 f3 * 14 .r \ side a (always odd)
\ 2 f1 * f2 * 10 .r \ side b (a multiple of 4)
\ f0 f2 * f1 f3 * + 10 .r \ side c, the hyponenuse, (always odd)
\ this block calculates double precision values
f0 f3 um* 15 d.r \ side a (always odd)
2 f1 * f2 um* 15 d.r \ side b (a multiple of 4)
f0 f2 um* f1 f3 um* d+ 17 d.r cr \ side c, the hypotenuse, (always odd)
MAX_LEVEL @ wk_LEVEL @ U> IF \ TRUE if MAX_LEVEL > WK_LEVEL
wk_level @ 1+ wk_level !
\ this creates a teranary tree of Pythagorean triples
\ use a two of the members of the Fibonacci series as seeds for the
\ next level
\ It's the same tree created by Barning or Hall using matrix multiplication
f3 f1 recurse
f3 f2 recurse
f0 f2 recurse
wk_level @ 1- wk_level !
else
then
drop drop drop drop ;
\ implements the Fibonacci series -- Pythagorean triple
\ the stack contents sets how many iteration levels there will be
: pf_test
\ the stack contents set up the maximum level
max_level !
0 wk_level !
cr
\ call the function with the first two elements of the base Fibonacci series
1 1 pythag_fibo ;
: gcd ( a b -- gcd )
begin ?dup while tuck mod repeat ;
\ this is the classical algorithm, known to Euclid, it is explained in many
\ books on Number Theory
\ this generates all primitive Pythagorean triples
\ i -- inner loop index or current loop index
\ j -- outer loop index
\ stack contents is the upper limit for j
\ i and j can not both be odd
\ the gcd( i, j ) must be 1
\ j is greater than i
\ the stack contains the upper limit of the j variable
: pythag_ancn ( limit -- )
cr
1 + 2 do
i 1 and if 2 else 1 then
\ this sets the start value of the inner loop so that
\ if the outer loop index is odd only even inner loop indices happen
\ if the outer loop index is even only odd inner loop indices happen
i swap do
i j gcd 1 - 0> if else \ do this if gcd( i, j ) is 1
j 5 .r i 5 .r
\ j j * i i * - 12 .r \ a side of Pythagorean triangle (always odd)
\ i j * 2 * 9 .r \ b side of Pythagorean triangle (multiple of 4)
\ i i * j j * + 9 .r \ hypotenuse of Pythagorean triangle (always odd)
\ this block calculates double precision Pythagorean triple values
j j um* i i um* d- 15 d.r \ a side of Pythagorean triangle (always odd)
i j um* d2* 15 d.r \ b side of Pythagorean triangle (multiple of 4)
i i um* j j um* d+ 17 d.r \ hypotenuse of Pythagorean triangle (always odd)
cr then 2 +loop \ keep i being all odd or all even
loop ;
Current directory: C:\Forth ok
FLOAD 'C:\Forth\ancien_fibo_pythag.F' ok
ok
ok
ok
3 pf_test
0 1 1 2 3 3 4 5
1 3 1 4 5 15 8 17
2 5 1 6 7 35 12 37
3 7 1 8 9 63 16 65
3 7 6 13 19 133 156 205
3 5 6 11 17 85 132 157
2 5 4 9 13 65 72 97
3 13 4 17 21 273 136 305
3 13 9 22 31 403 396 565
3 5 9 14 23 115 252 277
2 3 4 7 11 33 56 65
3 11 4 15 19 209 120 241
3 11 7 18 25 275 252 373
3 3 7 10 17 51 140 149
1 3 2 5 7 21 20 29
2 7 2 9 11 77 36 85
3 11 2 13 15 165 52 173
3 11 9 20 29 319 360 481
3 7 9 16 25 175 288 337
2 7 5 12 17 119 120 169
3 17 5 22 27 459 220 509
3 17 12 29 41 697 696 985
3 7 12 19 31 217 456 505
2 3 5 8 13 39 80 89
3 13 5 18 23 299 180 349
3 13 8 21 29 377 336 505
3 3 8 11 19 57 176 185
1 1 2 3 5 5 12 13
2 5 2 7 9 45 28 53
3 9 2 11 13 117 44 125
3 9 7 16 23 207 224 305
3 5 7 12 19 95 168 193
2 5 3 8 11 55 48 73
3 11 3 14 17 187 84 205
3 11 8 19 27 297 304 425
3 5 8 13 21 105 208 233
2 1 3 4 7 7 24 25
3 7 3 10 13 91 60 109
3 7 4 11 15 105 88 137
3 1 4 5 9 9 40 41
ok
ok
10 pythag_ancn
2 1 3 4 5
3 2 5 12 13
4 1 15 8 17
4 3 7 24 25
5 2 21 20 29
5 4 9 40 41
6 1 35 12 37
6 5 11 60 61
7 2 45 28 53
7 4 33 56 65
7 6 13 84 85
8 1 63 16 65
8 3 55 48 73
8 5 39 80 89
8 7 15 112 113
9 2 77 36 85
9 4 65 72 97
9 8 17 144 145
10 1 99 20 101
10 3 91 60 109
10 7 51 140 149
10 9 19 180 181
ok
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#VHDL
|
VHDL
|
LIBRARY ieee; USE std.TEXTIO.all;
entity quine is end entity quine;
architecture beh of quine is
type str_array is array(1 to 20) of string(1 to 80);
constant src : str_array := (
"LIBRARY ieee; USE std.TEXTIO.all; ",
"entity quine is end entity quine; ",
"architecture beh of quine is ",
" type str_array is array(1 to 20) of string(1 to 80); ",
" constant src : str_array := ( ",
"begin ",
" process variable l : line; begin ",
" for i in 1 to 5 loop write(l, src(i)); writeline(OUTPUT, l); end loop; ",
" for i in 1 to 20 loop ",
" write(l, character'val(32)&character'val(32)); ",
" write(l, character'val(32)&character'val(32)); ",
" write(l, character'val(34)); write(l, src(i)); write(l,character'val(34));",
" if i /= 20 then write(l, character'val(44)); ",
" else write(l, character'val(41)&character'val(59)); end if; ",
" writeline(OUTPUT, l); ",
" end loop; ",
" for i in 6 to 20 loop write(l, src(i)); writeline(OUTPUT, l); end loop; ",
" wait; ",
" end process; ",
"end architecture beh; ");
begin
process variable l : line; begin
for i in 1 to 5 loop write(l, src(i)); writeline(OUTPUT, l); end loop;
for i in 1 to 20 loop
write(l, character'val(32)&character'val(32));
write(l, character'val(32)&character'val(32));
write(l, character'val(34)); write(l, src(i)); write(l,character'val(34));
if i /= 20 then write(l, character'val(44));
else write(l, character'val(41)&character'val(59)); end if;
writeline(OUTPUT, l);
end loop;
for i in 6 to 20 loop write(l, src(i)); writeline(OUTPUT, l); end loop;
wait;
end process;
end architecture beh;
|
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.
|
#C.2B.2B
|
C++
|
#include <cstdlib>
void problem_occured()
{
std::exit(EXIT_FAILURE);
}
|
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.
|
#Clojure
|
Clojure
|
(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}}
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
{q,r}=QRDecomposition[{{12, -51, 4}, {6, 167, -68}, {-4, 24, -41}}];
q//MatrixForm
-> 6/7 3/7 -(2/7)
-69/175 158/175 6/35
-58/175 6/175 -33/35
r//MatrixForm
-> 14 21 -14
0 175 -70
0 0 35
|
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.
|
#Emacs_Lisp
|
Emacs Lisp
|
:;exec emacs -batch -l $0 -f main $*
;;; Shebang from John Swaby
;;; http://www.emacswiki.org/emacs/EmacsScripts
(defun main ()
(let ((program (nth 2 command-line-args)))
(message "Program: %s" program)))
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Erlang
|
Erlang
|
%% Compile
%%
%% erlc scriptname.erl
%%
%% Run
%%
%% erl -noshell -s scriptname
-module(scriptname).
-export([start/0]).
start() ->
Program = ?FILE,
io:format("Program: ~s~n", [Program]),
init:stop().
|
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.
|
#D
|
D
|
import std.stdio;
import std.format;
import std.bigint;
import std.math;
import std.algorithm;
int sieveLimit = 1300_000;
bool[] notPrime;
void main()
{
// initialize
sieve(sieveLimit);
// output 1
foreach (i; 0..10)
writefln("primorial(%d): %d", i, primorial(i));
// output 2
foreach (i; 1..6)
writefln("primorial(10^%d) has length %d", i, count(format("%d", primorial(pow(10, i)))));
}
BigInt primorial(int n)
{
if (n == 0) return BigInt(1);
BigInt result = BigInt(1);
for (int i = 0; i < sieveLimit && n > 0; i++)
{
if (notPrime[i]) continue;
result *= BigInt(i);
n--;
}
return result;
}
void sieve(int limit)
{
notPrime = new bool[limit];
notPrime[0] = notPrime[1] = true;
auto max = sqrt(cast (float) limit);
for (int n = 2; n <= max; n++)
{
if (!notPrime[n])
{
for (int k = n * n; k < limit; k += n)
{
notPrime[k] = true;
}
}
}
}
|
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
|
#Fortran
|
Fortran
|
module triples
implicit none
integer :: max_peri, prim, total
integer :: u(9,3) = reshape((/ 1, -2, 2, 2, -1, 2, 2, -2, 3, &
1, 2, 2, 2, 1, 2, 2, 2, 3, &
-1, 2, 2, -2, 1, 2, -2, 2, 3 /), &
(/ 9, 3 /))
contains
recursive subroutine new_tri(in)
integer, intent(in) :: in(:)
integer :: i
integer :: t(3), p
p = sum(in)
if (p > max_peri) return
prim = prim + 1
total = total + max_peri / p
do i = 1, 3
t(1) = sum(u(1:3, i) * in)
t(2) = sum(u(4:6, i) * in)
t(3) = sum(u(7:9, i) * in)
call new_tri(t);
end do
end subroutine new_tri
end module triples
program Pythagorean
use triples
implicit none
integer :: seed(3) = (/ 3, 4, 5 /)
max_peri = 10
do
total = 0
prim = 0
call new_tri(seed)
write(*, "(a, i10, 2(i10, a))") "Up to", max_peri, total, " triples", prim, " primitives"
if(max_peri == 100000000) exit
max_peri = max_peri * 10
end do
end program Pythagorean
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Program
Sub Main()
Dim s = "
Module Program
Sub Main()
Dim s = {0}{1}{0}
Console.WriteLine(s, ChrW(34), s)
End Sub
End Module"
Console.WriteLine(s, ChrW(34), s)
End Sub
End Module
|
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.
|
#COBOL
|
COBOL
|
IF problem
STOP RUN
END-IF
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#Common_Lisp
|
Common Lisp
|
(defun terminate (status)
#+sbcl ( sb-ext:quit :unix-status status) ; SBCL
#+ccl ( ccl:quit status) ; Clozure CL
#+clisp ( ext:quit status) ; GNU CLISP
#+cmu ( unix:unix-exit status) ; CMUCL
#+ecl ( ext:quit status) ; ECL
#+abcl ( ext:quit :status status) ; Armed Bear CL
#+allegro ( excl:exit status :quiet t) ; Allegro CL
#+gcl (common-lisp-user::bye status) ; GCL
#+ecl ( ext:quit status) ; ECL
(cl-user::quit)) ; Many implementations put QUIT in the sandbox CL-USER package.
|
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}}
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
A = [12 -51 4
6 167 -68
-4 24 -41];
[Q,R]=qr(A)
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Euphoria
|
Euphoria
|
constant cmd = command_line()
puts(1,cmd[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.
|
#F.23
|
F#
|
#light (*
exec fsharpi --exec $0 --quiet
*)
let scriptname =
let args = System.Environment.GetCommandLineArgs()
let arg0 = args.[0]
if arg0.Contains("fsi") then
let arg1 = args.[1]
if arg1 = "--exec" then
args.[2]
else
arg1
else
arg0
let main =
printfn "%s" 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.
|
#Delphi
|
Delphi
|
defmodule SieveofEratosthenes do
def init(lim) do
find_primes(2,lim,(2..lim))
end
def find_primes(count,lim,nums) when (count * count) > lim do
nums
end
def find_primes(count,lim,nums) when (count * count) <= lim do
find_primes(count+1,lim,Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count)))
end
end
|
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.
|
#Elixir
|
Elixir
|
defmodule SieveofEratosthenes do
def init(lim) do
find_primes(2,lim,(2..lim))
end
def find_primes(count,lim,nums) when (count * count) > lim do
nums
end
def find_primes(count,lim,nums) when (count * count) <= lim do
find_primes(count+1,lim,Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count)))
end
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
|
#FreeBASIC
|
FreeBASIC
|
' version 30-05-2016
' compile with: fbc -s console
' primitive pythagoras triples
' a = m^2 - n^2, b = 2mn, c = m^2 + n^2
' m, n are positive integers and m > n
' m - n = odd and GCD(m, n) = 1
' p = a + b + c
' max m for give perimeter
' p = m^2 - n^2 + 2mn + m^2 + n^2
' p = 2mn + m^2 + m^2 + n^2 - n^2 = 2mn + 2m^2
' m >> n and n = 1 ==> p = 2m + 2m^2 = 2m(1 + m)
' m >> 1 ==> p = 2m(m) = 2m^2
' max m for given perimeter = sqr(p / 2)
Function gcd(x As UInteger, y As UInteger) As UInteger
Dim As UInteger t
While y
t = y
y = x Mod y
x = t
Wend
Return x
End Function
Sub pyth_trip(limit As ULongInt, ByRef trip As ULongInt, ByRef prim As ULongInt)
Dim As ULongInt perimeter, lby2 = limit Shr 1
Dim As UInteger m, n
Dim As ULongInt a, b, c
For m = 2 To Sqr(limit / 2)
For n = 1 + (m And 1) To (m - 1) Step 2
' common divisor, try next n
If (gcd(m, n) > 1) Then Continue For
a = CULngInt(m) * m - n * n
b = CULngInt(m) * n * 2
c = CULngInt(m) * m + n * n
perimeter = a + b + c
' perimeter > limit, since n goes up try next m
If perimeter >= limit Then Continue For, For
prim += 1
If perimeter < lby2 Then
trip += limit \ perimeter
Else
trip += 1
End If
Next n
Next m
End Sub
' ------=< MAIN >=------
Dim As String str1, buffer = Space(14)
Dim As ULongInt limit, trip, prim
Dim As Double t, t1 = Timer
Print "below triples primitive time"
Print
For x As UInteger = 1 To 12
t = Timer
limit = 10 ^ x : trip = 0 : prim = 0
pyth_trip(limit, trip, prim)
LSet buffer, Str(prim) : str1 = buffer
Print Using "10^## ################ "; x; trip;
If x > 7 Then
Print str1;
Print Using " ######.## sec."; Timer - t
Else
Print str1
End If
Next x
Print : Print
Print Using "Total time needed #######.## sec."; Timer - t1
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#WDTE
|
WDTE
|
let str => import 'strings';
let v => "let str => import 'strings';\nlet v => {q};\nstr.format v v -- io.writeln io.stdout;";
str.format v v -- io.writeln io.stdout;
|
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.
|
#Computer.2Fzero_Assembly
|
Computer/zero Assembly
|
import core.stdc.stdio, core.stdc.stdlib;
extern(C) void foo() nothrow {
"foo at exit".puts;
}
extern(C) void bar() nothrow {
"bar at exit".puts;
}
extern(C) void spam() nothrow {
"spam at exit".puts;
}
int baz(in int x) pure nothrow
in {
assert(x != 0);
} body {
if (x < 0)
return 10;
if (x > 0)
return 20;
// x can't be 0.
// In release mode this becomes a halt, and it's sometimes
// necessary. If you remove this the compiler gives:
// Error: function test.notInfinite no return exp;
// or assert(0); at end of function
assert(false);
}
// This generates an error, that is not meant to be caught.
// Objects are not guaranteed to be finalized.
int empty() pure nothrow {
throw new Error(null);
}
static ~this() {
// This module destructor is never called if
// the program calls the exit function.
import std.stdio;
"Never called".writeln;
}
void main() {
atexit(&foo);
atexit(&bar);
atexit(&spam);
//abort(); // Also this is allowed. Will not call foo, bar, spam.
exit(0);
}
|
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}}
|
#Maxima
|
Maxima
|
load(lapack)$ /* This may hang up in wxMaxima, if this happens, use xMaxima or plain Maxima in a terminal */
a: matrix([12, -51, 4],
[ 6, 167, -68],
[-4, 24, -41])$
[q, r]: dgeqrf(a)$
mat_norm(q . r - a, 1);
4.2632564145606011E-14
/* Note: the lapack package is a lisp translation of the fortran lapack library */
|
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.
|
#Factor
|
Factor
|
#! /usr/bin/env factor
USING: namespaces io command-line ;
IN: scriptname
: main ( -- ) script get print ;
MAIN: main
|
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.
|
#Forth
|
Forth
|
0 arg type cr \ gforth or gforth-fast, for example
1 arg type cr \ name of script
|
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.
|
#F.23
|
F#
|
// Primorial Numbers. Nigel Galloway: August 3rd., 2021
primes32()|>Seq.scan((*)) 1|>Seq.take 10|>Seq.iter(printf "%d "); printfn "\n"
[10;100;1000;10000;100000]|>List.iter(fun n->printfn "%d" ((int)(System.Numerics.BigInteger.Log10 (Seq.item n (primesI()|>Seq.scan((*)) 1I)))+1))
|
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
|
#Go
|
Go
|
package main
import "fmt"
var total, prim, maxPeri int64
func newTri(s0, s1, s2 int64) {
if p := s0 + s1 + s2; p <= maxPeri {
prim++
total += maxPeri / p
newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)
newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)
newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)
}
}
func main() {
for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {
prim = 0
total = 0
newTri(3, 4, 5)
fmt.Printf("Up to %d: %d triples, %d primitives\n",
maxPeri, total, prim)
}
}
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#Whitespace
|
Whitespace
| |
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.
|
#D
|
D
|
import core.stdc.stdio, core.stdc.stdlib;
extern(C) void foo() nothrow {
"foo at exit".puts;
}
extern(C) void bar() nothrow {
"bar at exit".puts;
}
extern(C) void spam() nothrow {
"spam at exit".puts;
}
int baz(in int x) pure nothrow
in {
assert(x != 0);
} body {
if (x < 0)
return 10;
if (x > 0)
return 20;
// x can't be 0.
// In release mode this becomes a halt, and it's sometimes
// necessary. If you remove this the compiler gives:
// Error: function test.notInfinite no return exp;
// or assert(0); at end of function
assert(false);
}
// This generates an error, that is not meant to be caught.
// Objects are not guaranteed to be finalized.
int empty() pure nothrow {
throw new Error(null);
}
static ~this() {
// This module destructor is never called if
// the program calls the exit function.
import std.stdio;
"Never called".writeln;
}
void main() {
atexit(&foo);
atexit(&bar);
atexit(&spam);
//abort(); // Also this is allowed. Will not call foo, bar, spam.
exit(0);
}
|
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}}
|
#Nim
|
Nim
|
import math, strformat, strutils
import arraymancer
####################################################################################################
# First part: QR decomposition.
proc eye(n: Positive): Tensor[float] =
## Return the (n, n) identity matrix.
result = newTensor[float](n.int, n.int)
for i in 0..<n: result[i, i] = 1
proc norm(v: Tensor[float]): float =
## return the norm of a vector.
assert v.shape.len == 1
result = sqrt(dot(v, v)) * sgn(v[0]).toFloat
proc houseHolder(a: Tensor[float]): Tensor[float] =
## return the house holder of vector "a".
var v = a / (a[0] + norm(a))
v[0] = 1
result = eye(a.shape[0]) - (2 / dot(v, v)) * (v.unsqueeze(1) * v.unsqueeze(0))
proc qrDecomposition(a: Tensor): tuple[q, r: Tensor] =
## Return the QR decomposition of matrix "a".
assert a.shape.len == 2
let m = a.shape[0]
let n = a.shape[1]
result.q = eye(m)
result.r = a.clone
for i in 0..<(n - ord(m == n)):
var h = eye(m)
h[i..^1, i..^1] = houseHolder(result.r[i..^1, i].squeeze(1))
result.q = result.q * h
result.r = h * result.r
####################################################################################################
# Second part: polynomial regression example.
proc lsqr(a, b: Tensor[float]): Tensor[float] =
let (q, r) = a.qrDecomposition()
let n = r.shape[1]
result = solve(r[0..<n, _], (q.transpose() * b)[0..<n])
proc polyfit(x, y: Tensor[float]; n: int): Tensor[float] =
var z = newTensor[float](x.shape[0], n + 1)
var t = x.reshape(x.shape[0], 1)
for i in 0..n: z[_, i] = t^.i.toFloat
result = lsqr(z, y.transpose())
#———————————————————————————————————————————————————————————————————————————————————————————————————
proc printMatrix(a: Tensor) =
var str: string
for i in 0..<a.shape[0]:
let start = str.len
for j in 0..<a.shape[1]:
str.addSep(" ", start)
str.add &"{a[i, j]:8.3f}"
str.add '\n'
stdout.write str
proc printVector(a: Tensor) =
var str: string
for i in 0..<a.shape[0]:
str.addSep(" ")
str.add &"{a[i]:4.1f}"
echo str
let mat = [[12, -51, 4],
[ 6, 167, -68],
[-4, 24, -41]].toTensor.astype(float)
let (q, r) = mat.qrDecomposition()
echo "Q:"
printMatrix q
echo "R:"
printMatrix r
echo()
let x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].toTensor.astype(float)
let y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321].toTensor.astype(float)
echo "polyfit:"
printVector polyfit(x, y, 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.
|
#Fortran
|
Fortran
|
! program run with invalid name path/f
!
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun Jun 2 00:18:31
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!
!Compilation finished at Sun Jun 2 00:18:31
! program run with valid name path/rcname
!
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun Jun 2 00:19:01
!
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o rcname && ./rcname
! ./rcname approved.
! program continues...
!
!Compilation finished at Sun Jun 2 00:19:02
module sundry
contains
subroutine verify_name(required)
! name verification reduces the ways an attacker can rename rm as cp.
character(len=*), intent(in) :: required
character(len=1024) :: name
integer :: length, status
! I believe get_command_argument is part of the 2003 FORTRAN standard intrinsics.
call get_command_argument(0, name, length, status)
if (0 /= status) stop
if ((len_trim(name)+1) .ne. (index(name, required, back=.true.) + len(required))) stop
write(6,*) trim(name)//' approved.'
end subroutine verify_name
end module sundry
program name
use sundry
call verify_name('rcname')
write(6,*)'program continues...'
end program 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.
|
#Factor
|
Factor
|
USING: formatting kernel literals math math.functions
math.primes sequences ;
IN: rosetta-code.primorial-numbers
CONSTANT: primes $[ 1,000,000 nprimes ]
: digit-count ( n -- count ) log10 floor >integer 1 + ;
: primorial ( n -- m ) primes swap head product ;
: .primorial ( n -- ) dup primorial "Primorial(%d) = %d\n"
printf ;
: .digit-count ( n -- ) dup primorial digit-count
"Primorial(%d) has %d digits\n" printf ;
: part1 ( -- ) 10 iota [ .primorial ] each ;
: part2 ( -- ) { 10 100 1000 10000 100000 1000000 }
[ .digit-count ] each ;
: main ( -- ) part1 part2 ;
MAIN: main
|
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.
|
#Fortran
|
Fortran
|
Base: 10 100 1,000 10,000 100,000
Secs: 554 278 185 117 52 - but wrong!
64-bit 300 241
|
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
|
#Groovy
|
Groovy
|
class Triple {
BigInteger a, b, c
def getPerimeter() { this.with { a + b + c } }
boolean isValid() { this.with { a*a + b*b == c*c } }
}
def initCounts (def n = 10) {
(n..1).collect { 10g**it }.inject ([:]) { Map map, BigInteger perimeterLimit ->
map << [(perimeterLimit): [primative: 0g, total: 0g]]
}
}
def findPythagTriples, findChildTriples
findPythagTriples = {Triple t = new Triple(a:3, b:4, c:5), Map counts = initCounts() ->
def p = t.perimeter
def currentCounts = counts.findAll { pLimit, tripleCounts -> p <= pLimit }
if (! currentCounts || ! t.valid) { return }
currentCounts.each { pLimit, tripleCounts ->
tripleCounts.with { primative ++; total += pLimit.intdiv(p) }
}
findChildTriples(t, currentCounts)
counts
}
findChildTriples = { Triple t, Map counts ->
t.with {
[
[ a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c],
[ a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c],
[-a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c]
]*.sort().each { aa, bb, cc ->
findPythagTriples(new Triple(a:aa, b:bb, c:cc), counts)
}
}
}
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#Wren
|
Wren
|
import "/fmt" for Fmt
var a = "import $c/fmt$c for Fmt$c$cvar a = $q$cFmt.lprint(a, [34, 34, 10, 10, a, 10])"
Fmt.lprint(a, [34, 34, 10, 10, a, 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.
|
#DBL
|
DBL
|
IF (CONDITION) 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.
|
#Delphi
|
Delphi
|
System.Halt;
|
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}}
|
#PARI.2FGP
|
PARI/GP
|
matqr(M)
|
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.
|
#FreeBASIC_2
|
FreeBASIC
|
' FB 1.05.0 Win64
Print "The program was invoked like this => "; Command(0) + " " + Command(-1)
Print "Press any key to quit"
Sleep
|
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.
|
#Gambas
|
Gambas
|
Public Sub Main()
Dim sTemp As String
Print "Command to start the program was ";;
For Each sTemp In Args.All
Print sTemp;;
Next
End
|
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.
|
#FreeBASIC
|
FreeBASIC
|
' version 22-09-2015
' compile with: fbc -s console
Const As UInteger Base_ = 1000000000
ReDim Shared As UInteger primes()
Sub sieve(need As UInteger)
' estimate is to high, but ensures that we have enough primes
Dim As UInteger max = need * (Log(need) + Log(Log(need)))
Dim As UInteger t = 1 ,x , x2
Dim As Byte p(max)
ReDim primes (need + need \ 3) ' we trim the array later
primes(0) = 1 ' by definition
primes(1) = 2 ' first prime, the only even prime
' only consider the odd number
For x = 3 To Sqr(max) Step 2
If p(x) = 0 Then
For x2 = x * x To max Step x * 2
p(x2) = 1
Next
End If
Next
' move found primes to array
For x = 3 To max Step 2
If p(x) = 0 Then
t += 1
primes(t) = x
EndIf
Next
'ReDim Preserve primes(t)
ReDim Preserve primes(need)
End Sub
' ------=< MAIN >=------
Dim As UInteger n, i, pow, primorial
Dim As String str_out, buffer = Space(10)
Dim As UInteger max = 100000 ' maximum number of primes we need
sieve(max)
primorial = 1
Print
For n = 0 To 9
primorial = primorial * primes(n)
Print Using " primorial(#) ="; n;
RSet buffer, Str(primorial)
str_out = buffer
Print str_out
Next
' could use GMP, but why not make are own big integer routine
Dim As UInteger bigint(max), first = max, last = max
Dim As UInteger l, p, carry, low = 9, high = 10
Dim As ULongInt result
Dim As UInteger Ptr big_i
' start at the back, number grows to the left like normal number
bigint(last) = primorial
Print
For pow = 0 To Len(Str(max)) -2
If pow > 0 Then
low = high
high = high * 10
End If
For n = low + 1 To high
carry = 0
big_i = @bigint(last)
For i = last To first Step -1
result = CULngInt(primes(n)) * *big_i + carry
carry = result \ Base_
*big_i = result - carry * Base_
big_i = big_i -1
Next i
If carry <> 0 Then
first = first -1
*big_i = carry
End If
Next n
l = Len(Str(bigint(first))) + (last - first) * 9
Print " primorial("; high; ") has "; l ;" digits"
Next pow
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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
|
#Haskell
|
Haskell
|
pytr :: Int -> [(Bool, Int, Int, Int)]
pytr n =
filter
(\(_, a, b, c) -> a + b + c <= n)
[ (prim a b c, a, b, c)
| a <- xs,
b <- drop a xs,
c <- drop b xs,
a ^ 2 + b ^ 2 == c ^ 2
]
where
xs = [1 .. n]
prim a b _ = gcd a b == 1
main :: IO ()
main =
putStrLn $
"Up to 100 there are "
<> show (length xs)
<> " triples, of which "
<> show (length $ filter (\(x, _, _, _) -> x) xs)
<> " are primitive."
where
xs = pytr 100
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#x86_Assembly
|
x86 Assembly
|
.global _start;_start:mov $p,%rsi;mov $1,%rax;mov $1,%rdi;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $p,%rsi;mov $1,%rax;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $60,%rax;syscall;q:.byte 34;p:.ascii ".global _start;_start:mov $p,%rsi;mov $1,%rax;mov $1,%rdi;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $p,%rsi;mov $1,%rax;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $60,%rax;syscall;q:.byte 34;p:.ascii "
|
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.
|
#E
|
E
|
if (true) {
interp.exitAtTop()
}
|
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.
|
#EDSAC_order_code
|
EDSAC order code
|
if rcode != :ok, do: System.halt(1)
|
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}}
|
#Perl
|
Perl
|
use strict;
use warnings;
use PDL;
use PDL::LinearAlgebra qw(mqr);
my $a = pdl(
[12, -51, 4],
[ 6, 167, -68],
[-4, 24, -41],
[-1, 1, 0],
[ 2, 0, 3]
);
my ($q, $r) = mqr($a);
print $q, $r, $q x $r;
|
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
|
#11l
|
11l
|
F proper_divs(n)
R Array(Set((1 .. (n + 1) I/ 2).filter(x -> @n % x == 0 & @n != x)))
print((1..10).map(n -> proper_divs(n)))
V (n, leng) = max(((1..20000).map(n -> (n, proper_divs(n).len))), key' pd -> pd[1])
print(n‘ ’leng)
|
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.
|
#11l
|
11l
|
T Circle
Float x, y, r
F (x, y, r)
.x = x
.y = y
.r = r
F String()
R ‘Circle(x=#., y=#., r=#.)’.format(.x, .y, .r)
F solveApollonius(c1, c2, c3, s1, s2, s3)
V (x1, y1, r1) = c1
V (x2, y2, r2) = c2
V (x3, y3, r3) = c3
V v11 = 2 * x2 - 2 * x1
V v12 = 2 * y2 - 2 * y1
V v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2
V v14 = 2 * s2 * r2 - 2 * s1 * r1
V v21 = 2 * x3 - 2 * x2
V v22 = 2 * y3 - 2 * y2
V v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3
V v24 = 2 * s3 * r3 - 2 * s2 * r2
V w12 = v12 / v11
V w13 = v13 / v11
V w14 = v14 / v11
V w22 = v22 / v21 - w12
V w23 = v23 / v21 - w13
V w24 = v24 / v21 - w14
V P = -w23 / w22
V Q = w24 / w22
V M = -w12 * P - w13
V n = w14 - w12 * Q
V a = n * n + Q * Q - 1
V b = 2 * M * n - 2 * n * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1
V c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1
V D = b * b - 4 * a * c
V rs = (-b - sqrt(D)) / (2 * a)
V xs = M + n * rs
V ys = P + Q * rs
R Circle(xs, ys, rs)
V (c1, c2, c3) = (Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2))
print(solveApollonius(c1, c2, c3, 1, 1, 1))
print(solveApollonius(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.
|
#Genie
|
Genie
|
[indent=4]
init
print args[0]
print Path.get_basename(args[0])
print Environment.get_application_name()
print Environment.get_prgname()
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Program:", os.Args[0])
}
|
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.
|
#Frink
|
Frink
|
primorial[n] := product[first[primes[], n]]
for n = 0 to 9
println["primorial[$n] = " + primorial[n]]
for n = [10, 100, 1000, 10000, 100000, million]
println["Length of primorial $n is " + length[toString[primorial[n]]] + " decimal digits."]
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math/big"
"time"
"github.com/jbarham/primegen.go"
)
func main() {
start := time.Now()
pg := primegen.New()
var i uint64
p := big.NewInt(1)
tmp := new(big.Int)
for i <= 9 {
fmt.Printf("primorial(%v) = %v\n", i, p)
i++
p = p.Mul(p, tmp.SetUint64(pg.Next()))
}
for _, j := range []uint64{1e1, 1e2, 1e3, 1e4, 1e5, 1e6} {
for i < j {
i++
p = p.Mul(p, tmp.SetUint64(pg.Next()))
}
fmt.Printf("primorial(%v) has %v digits", i, len(p.String()))
fmt.Printf("\t(after %v)\n", time.Since(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
|
#Icon_and_Unicon
|
Icon and Unicon
|
link numbers
link printf
procedure main(A) # P-triples
plimit := (0 < integer(\A[1])) | 100 # get perimiter limit
nonprimitiveS := set() # record unique non-primitives triples
primitiveS := set() # record unique primitive triples
u := 0
while (g := (u +:= 1)^2) + 3 * u + 2 < plimit / 2 do {
every v := seq(1) do {
a := g + (i := 2*u*v)
b := (h := 2*v^2) + i
c := g + h + i
if (p := a + b + c) > plimit then break
insert( (gcd(u,v)=1 & u%2=1, primitiveS) | nonprimitiveS, memo(a,b,c))
every k := seq(2) do { # k is for larger non-primitives
if k*p > plimit then break
insert(nonprimitiveS,memo(a*k,b*k,c*k) )
}
}
}
printf("Under perimiter=%d: Pythagorean Triples=%d including primitives=%d\n",
plimit,*nonprimitiveS+*primitiveS,*primitiveS)
every put(gcol := [] , &collections)
printf("Time=%d, Collections: total=%d string=%d block=%d",&time,gcol[1],gcol[3],gcol[4])
end
procedure memo(x[]) #: return a csv string of arguments in sorted order
every (s := "") ||:= !sort(x) do s ||:= ","
return s[1:-1]
end
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#zkl
|
zkl
|
zkl: 123
123
|
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.
|
#Elixir
|
Elixir
|
if rcode != :ok, do: System.halt(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.
|
#Emacs_Lisp
|
Emacs Lisp
|
(when something
(kill-emacs))
|
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}}
|
#Phix
|
Phix
|
-- demo/rosettacode/QRdecomposition.exw
with javascript_semantics
function matrix_mul(sequence a, b)
integer arows = ~a, acols = ~a[1],
brows = ~b, bcols = ~b[1]
if acols!=brows then return 0 end if
sequence c = repeat(repeat(0,bcols),arows)
for i=1 to arows do
for j=1 to bcols do
for k=1 to acols do
c[i][j] += a[i][k]*b[k][j]
end for
end for
end for
return c
end function
function vtranspose(sequence v)
-- transpose a vector of length m into an mx1 matrix,
-- eg {1,2,3} -> {{1},{2},{3}}
integer l = length(v)
sequence res = repeat(0,l)
for i=1 to l do res[i] = {v[i]} end for
return res
end function
function mat_col(sequence a, integer col)
integer la = length(a)
sequence res = repeat(0,la)
for i=col to la do
res[i] = a[i,col]
end for
return res
end function
function mat_norm(sequence a)
atom res = 0
for i=1 to length(a) do
res += a[i]*a[i]
end for
res = sqrt(res)
return res
end function
function mat_ident(integer n)
sequence res = repeat(repeat(0,n),n)
for i=1 to n do
res[i,i] = 1
end for
return res
end function
function QRHouseholder(sequence a)
integer cols = length(a[1]),
rows = length(a),
m = max(cols,rows),
n = min(rows,cols)
sequence q, I = mat_ident(m), Q = I, u, v
--
-- Programming note: The code of this main loop was not as easily
-- written as the first glance might suggest. Explicitly setting
-- to 0 any a[i,j] [etc] that should be 0 but have inadvertently
-- gotten set to +/-1e-15 or thereabouts may be advisable. The
-- commented-out code was retrieved from a backup and should be
-- treated as an example and not be trusted (iirc, it made no
-- difference to the test cases used, so I deleted it, and then
-- had second thoughts about it a few days later).
--
for j=1 to min(m-1,n) do
u = mat_col(a,j)
u[j] -= mat_norm(u)
v = sq_div(u,mat_norm(u))
q = sq_sub(I,sq_mul(2,matrix_mul(vtranspose(v),{v})))
a = matrix_mul(q,a)
-- for row=j+1 to length(a) do
-- a[row][j] = 0
-- end for
Q = matrix_mul(Q,q)
end for
-- Get the upper triangular matrix R.
sequence R = repeat(repeat(0,n),m)
for i=1 to n do -- (logically 1 to m(>=n), but no need)
for j=i to n do
R[i,j] = a[i,j]
end for
end for
return {Q,R}
end function
constant a = {{12, -51, 4},
{ 6, 167, -68},
{-4, 24, -41}}
sequence {q,r} = QRHouseholder(a)
ppOpt({pp_Nest,1,pp_IntFmt,"%4d",pp_FltFmt,"%4g",pp_IntCh,false})
?"A" pp(a)
?"Q" pp(q)
?"R" pp(r)
?"Q * R" pp(matrix_mul(q,r))
function matrix_transpose(sequence mat)
integer rows = length(mat),
cols = length(mat[1])
sequence res = repeat(repeat(0,rows),cols)
for r=1 to rows do
for c=1 to cols do
res[c][r] = mat[r][c]
end for
end for
return res
end function
--?"Q * Q'" pp(matrix_mul(q,matrix_transpose(q))) -- (~1e-16s)
?"Q * Q`" pp(sq_round(matrix_mul(q,matrix_transpose(q)),1e15))
procedure least_squares()
sequence x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321},
a = repeat(repeat(0,3),length(x))
for i=1 to length(x) do
for j=1 to 3 do
a[i,j] = power(x[i],j-1)
end for
end for
{q,r} = QRHouseholder(a)
sequence t = matrix_transpose(q),
b = matrix_mul(t,vtranspose(y)),
z = repeat(0,3)
for k=3 to 1 by -1 do
atom s = 0
if k<3 then
for j = k+1 to 3 do
s += r[k,j]*z[j]
end for
end if
z[k] = (b[k][1]-s)/r[k,k]
end for
printf(1,"Least-squares solution:\n")
-- printf(1," %v\n",{z}) -- {1.0,2.0.3,0}
-- printf(1," %v\n",{sq_sub(z,{1,2,3})}) -- (+/- ~1e-14s)
printf(1," %v\n",{sq_round(z,1e13)}) -- {1,2,3}
end procedure
least_squares()
|
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
|
#360_Assembly
|
360 Assembly
|
* Proper divisors 14/06/2016
PROPDIV CSECT
USING PROPDIV,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
LA R10,1 n=1
LOOPN1 C R10,=F'10' do n=1 to 10
BH ELOOPN1
LR R1,R10 n
BAL R14,PDIV pdiv(n)
ST R0,NN nn=pdiv(n)
MVC PG,PGT init buffer
LA R11,PG pgi=0
XDECO R10,XDEC edit n
MVC 0(3,R11),XDEC+9 output n
LA R11,7(R11) pgi=pgi+7
L R1,NN nn
XDECO R1,XDEC edit nn
MVC 0(3,R11),XDEC+9 output nn
LA R11,20(R11) pgi=pgi+20
LA R5,1 i=1
LOOPNI C R5,NN do i=1 to nn
BH ELOOPNI
LR R1,R5 i
SLA R1,2 *4
L R2,TDIV-4(R1) tdiv(i)
XDECO R2,XDEC edit tdiv(i)
MVC 0(3,R11),XDEC+9 output tdiv(i)
LA R11,3(R11) pgi=pgi+3
LA R5,1(R5) i=i+1
B LOOPNI
ELOOPNI XPRNT PG,80 print buffer
LA R10,1(R10) n=n+1
B LOOPN1
ELOOPN1 SR R0,R0 0
ST R0,M m=0
LA R10,1 n=1
LOOPN2 C R10,=F'20000' do n=1 to 20000
BH ELOOPN2
LR R1,R10 n
BAL R14,PDIV nn=pdiv(n)
C R0,M if nn>m
BNH NNNHM
ST R10,II ii=n
ST R0,M m=nn
NNNHM LA R10,1(R10) n=n+1
B LOOPN2
ELOOPN2 MVC PG,PGR init buffer
L R1,II ii
XDECO R1,XDEC edit ii
MVC PG(5),XDEC+7 output ii
L R1,M m
XDECO R1,XDEC edit m
MVC PG+9(4),XDEC+8 output m
XPRNT PG,80 print buffer
L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
*------- pdiv --function(x)----->number of divisors---
PDIV ST R1,X x
C R1,=F'1' if x=1
BNE NOTONE
LA R0,0 return(0)
BR R14
NOTONE LR R4,R1 x
N R4,=X'00000001' mod(x,2)
LA R4,1(R4) +1
ST R4,ODD odd=mod(x,2)+1
LA R8,1 ia=1
LA R0,1 1
ST R0,TDIV tdiv(1)=1
SR R9,R9 ib=0
L R7,ODD odd
LA R7,1(R7) j=odd+1
LOOPJ LR R5,R7 do j=odd+1 by odd
MR R4,R7 j*j
C R5,X while j*j<x
BNL ELOOPJ
L R4,X x
SRDA R4,32 .
DR R4,R7 /j
LTR R4,R4 if mod(x,j)=0
BNZ ITERJ
LA R8,1(R8) ia=ia+1
LR R1,R8 ia
SLA R1,2 *4 (F)
ST R7,TDIV-4(R1) tdiv(ia)=j
LA R9,1(R9) ib=ib+1
L R4,X x
SRDA R4,32 .
DR R4,R7 j
LR R2,R9 ib
SLA R2,2 *4 (F)
ST R5,TDIVB-4(R2) tdivb(ib)=x/j
ITERJ A R7,ODD j=j+odd
B LOOPJ
ELOOPJ LR R5,R7 j
MR R4,R7 j*j
C R5,X if j*j=x
BNE JTJNEX
LA R8,1(R8) ia=ia+1
LR R1,R8 ia
SLA R1,2 *4 (F)
ST R7,TDIV-4(R1) tdiv(ia)=j
JTJNEX LA R1,TDIV(R1) @tdiv(ia+1)
LA R2,TDIVB-4(R2) @tdivb(ib)
LTR R6,R9 do i=ib to 1 by -1
BZ ELOOPI
LOOPI MVC 0(4,R1),0(R2) tdiv(ia)=tdivb(i)
LA R8,1(R8) ia=ia+1
LA R1,4(R1) r1+=4
SH R2,=H'4' r2-=4
BCT R6,LOOPI i=i-1
ELOOPI LR R0,R8 return(ia)
BR R14 return to caller
* ---- ----------------------------------------
TDIV DS 80F
TDIVB DS 40F
M DS F
NN DS F
II DS F
X DS F
ODD DS F
PGT DC CL80'... has .. proper divisors:'
PGR DC CL80'..... has ... proper divisors.'
PG DC CL80' '
XDEC DS CL12
YREGS
END PROPDIV
|
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.
|
#Ada
|
Ada
|
package Apollonius is
type Point is record
X, Y : Long_Float := 0.0;
end record;
type Circle is record
Center : Point;
Radius : Long_Float := 0.0;
end record;
type Tangentiality is (External, Internal);
function Solve_CCC
(Circle_1, Circle_2, Circle_3 : Circle;
T1, T2, T3 : Tangentiality := External)
return Circle;
end Apollonius;
|
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.
|
#Groovy
|
Groovy
|
#!/usr/bin/env groovy
def program = getClass().protectionDomain.codeSource.location.path
println "Program: " + program
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Haskell
|
Haskell
|
import System (getProgName)
main :: IO ()
main = getProgName >>= putStrLn . ("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.
|
#Haskell
|
Haskell
|
import Control.Arrow ((&&&))
import Data.List (scanl1, foldl1')
getNthPrimorial :: Int -> Integer
getNthPrimorial n = foldl1' (*) (take n primes)
primes :: [Integer]
primes = 2 : filter isPrime [3,5..]
isPrime :: Integer -> Bool
isPrime = isPrime_ primes
where isPrime_ :: [Integer] -> Integer -> Bool
isPrime_ (p:ps) n
| p * p > n = True
| n `mod` p == 0 = False
| otherwise = isPrime_ ps n
primorials :: [Integer]
primorials = 1 : scanl1 (*) primes
main :: IO ()
main = do
-- Print the first 10 primorial numbers
let firstTen = take 10 primorials
putStrLn $ "The first 10 primorial numbers are: " ++ show firstTen
-- Show the length of the primorials with index 10^[1..6]
let powersOfTen = [1..6]
primorialTens = map (id &&& (length . show . getNthPrimorial . (10^))) powersOfTen
calculate = mapM_ (\(a,b) -> putStrLn $ "Primorial(10^"++show a++") has "++show b++" digits")
calculate primorialTens
|
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
|
#J
|
J
|
pytr=: 3 :0
r=. i. 0 3
for_a. 1 + i. <.(y-1)%3 do.
b=. 1 + a + i. <.(y%2)-3*a%2
c=. a +&.*: b
keep=. (c = <.c) *. y >: a+b+c
if. 1 e. keep do.
r=. r, a,.b ,.&(keep&#) c
end.
end.
(,.~ prim"1)r
)
prim=: 1 = 2 +./@{. |:
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#Erlang
|
Erlang
|
% Implemented by Arjun Sunel
if problem ->
exit(1).
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#F.23
|
F#
|
open System
if condition then
Environment.Exit 1
|
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}}
|
#PowerShell
|
PowerShell
|
function qr([double[][]]$A) {
$m,$n = $A.count, $A[0].count
$pm,$pn = ($m-1), ($n-1)
[double[][]]$Q = 0..($m-1) | foreach{$row = @(0) * $m; $row[$_] = 1; ,$row}
[double[][]]$R = $A | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})}
foreach ($h in 0..$pn) {
[double[]]$u = $R[$h..$pm] | foreach{$_[$h]}
[double]$nu = $u | foreach {[double]$sq = 0} {$sq += $_*$_} {[Math]::Sqrt($sq)}
$u[0] -= if ($u[0] -lt 0) {$nu} else {-$nu}
[double]$nu = $u | foreach {$sq = 0} {$sq += $_*$_} {[Math]::Sqrt($sq)}
[double[]]$u = $u | foreach { $_/$nu}
[double[][]]$v = 0..($u.Count - 1) | foreach{$i = $_; ,($u | foreach{2*$u[$i]*$_})}
[double[][]]$CR = $R | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})}
[double[][]]$CQ = $Q | foreach{$row = $_; ,@(0..$pm | foreach{$row[$_]})}
foreach ($i in $h..$pm) {
foreach ($j in $h..$pn) {
$R[$i][$j] -= $h..$pm | foreach {[double]$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CR[$_][$j]} {$sum}
}
}
if (0 -eq $h) {
foreach ($i in $h..$pm) {
foreach ($j in $h..$pm) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i][$_]*$CQ[$_][$j]} {$sum}
}
}
} else {
$p = $h-1
foreach ($i in $h..$pm) {
foreach ($j in 0..$p) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CQ[$_][$j]} {$sum}
}
foreach ($j in $h..$pm) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CQ[$_][$j]} {$sum}
}
}
}
}
foreach ($i in 0..$pm) {
foreach ($j in $i..$pm) {$Q[$i][$j],$Q[$j][$i] = $Q[$j][$i],$Q[$i][$j]}
}
[PSCustomObject]@{"Q" = $Q; "R" = $R}
}
function leastsquares([Double[][]]$A,[Double[]]$y) {
$QR = qr $A
[Double[][]]$Q = $QR.Q
[Double[][]]$R = $QR.R
$m,$n = $A.count, $A[0].count
[Double[]]$z = foreach ($j in 0..($m-1)) {
0..($m-1) | foreach {$sum = 0} {$sum += $Q[$_][$j]*$y[$_]} {$sum}
}
[Double[]]$x = @(0)*$n
for ($i = $n-1; $i -ge 0; $i--) {
for ($j = $i+1; $j -lt $n; $j++) {
$z[$i] -= $x[$j]*$R[$i][$j]
}
$x[$i] = $z[$i]/$R[$i][$i]
}
$x
}
function polyfit([Double[]]$x,[Double[]]$y,$n) {
$m = $x.Count
[Double[][]]$A = 0..($m-1) | foreach{$row = @(1) * ($n+1); ,$row}
for ($i = 0; $i -lt $m; $i++) {
for ($j = $n-1; 0 -le $j; $j--) {
$A[$i][$j] = $A[$i][$j+1]*$x[$i]
}
}
leastsquares $A $y
}
function show($m) {$m | foreach {write-host "$_"}}
$A = @(@(12,-51,4), @(6,167,-68), @(-4,24,-41))
$x = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
$y = @(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
$QR = qr $A
$ps = (polyfit $x $y 2)
"Q = "
show $QR.Q
"R = "
show $QR.R
"polyfit "
"X^2 X constant"
"$(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.
|
#ALGOL_68
|
ALGOL 68
|
BEGIN # find solutions to the "Prime Triangle" - a triangle of numbers that sum to primes #
INT max number = 18; # largest number we will consider #
# construct a primesieve and from that a table of pairs of numbers whose sum is prime #
[ 0 : 2 * max number ]BOOL prime;
prime[ 0 ] := prime[ 1 ] := FALSE;
prime[ 2 ] := TRUE;
FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE OD;
FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO
IF prime[ i ] THEN
FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD
FI
OD;
# returns the number of possible arrangements of the integers for a row in the prime triangle #
PROC count arrangements = ( INT n )INT:
IF n < 2 THEN # no solutions for n < 2 # 0
ELIF n < 4 THEN
# for 2 and 3. there is only 1 solution: 1, 2 and 1, 2, 3 #
FOR i TO n DO print( ( whole( i, -3 ) ) ) OD; print( ( newline ) );
1
ELSE
# 4 or more - must find the solutions #
BOOL print solution := TRUE;
[ 0 : n ]BOOL used;
[ 0 : n ]INT number;
# the triangle row must have 1 in the leftmost and n in the rightmost elements #
# the numbers must alternate between even and odd in order for the sum to be prime #
FOR i FROM 0 TO n DO
used[ i ] := FALSE;
number[ i ] := i MOD 2
OD;
used[ 1 ] := TRUE;
number[ n ] := n;
used[ n ] := TRUE;
# find the intervening numbers and count the solutions #
INT count := 0;
INT p := 2;
WHILE p > 0 DO
INT p1 = number[ p - 1 ];
INT current = number[ p ];
INT next := current + 2;
WHILE IF next >= n THEN FALSE ELSE NOT prime[ p1 + next ] OR used[ next ] FI DO
next +:= 2
OD;
IF next >= n THEN next := 0 FI;
IF p = n - 1 THEN
# we are at the final number before n #
# it must be the final even/odd number preceded by the final odd/even number #
IF next /= 0 THEN
# possible solution #
IF prime[ next + n ] THEN
# found a solution #
count +:= 1;
IF print solution THEN
FOR i TO n - 2 DO
print( ( whole( number[ i ], -3 ) ) )
OD;
print( ( whole( next, -3 ), whole( n, - 3 ), newline ) );
print solution := FALSE
FI
FI;
next := 0
FI;
# backtrack for more solutions #
p -:= 1
# here will be a further backtrack as next is 0 ( there could only be one possible number at p - 1 ) #
FI;
IF next /= 0 THEN
# have a/another number that can appear at p #
used[ current ] := FALSE;
used[ next ] := TRUE;
number[ p ] := next;
p +:= 1
ELIF p <= 2 THEN
# no more solutions #
p := 0
ELSE
# can't find a number for this position, backtrack #
used[ number[ p ] ] := FALSE;
number[ p ] := p MOD 2;
p -:= 1
FI
OD;
count
FI # count arrangements # ;
[ 2 : max number ]INT arrangements;
FOR n FROM LWB arrangements TO UPB arrangements DO
arrangements[ n ] := count arrangements( n )
OD;
FOR n FROM LWB arrangements TO UPB arrangements DO
print( ( " ", whole( arrangements[ n ], 0 ) ) )
OD;
print( ( newline ) )
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
|
#Action.21
|
Action!
|
BYTE FUNC GetDivisors(INT a INT ARRAY divisors)
INT i,max
BYTE count
max=a/2
count=0
FOR i=1 TO max
DO
IF a MOD i=0 THEN
divisors(count)=i
count==+1
FI
OD
RETURN (count)
PROC Main()
DEFINE MAXNUM="20000"
INT i,j,count,max,ind
INT ARRAY divisors(100)
BYTE ARRAY pdc(MAXNUM+1)
FOR i=1 TO 10
DO
count=GetDivisors(i,divisors)
PrintF("%I has %I proper divisors: [",i,count)
FOR j=0 TO count-1
DO
PrintI(divisors(j))
IF j<count-1 THEN
Put(32)
FI
OD
PrintE("]")
OD
PutE() PrintE("Searching for max number of divisors:")
FOR i=1 TO MAXNUM
DO
pdc(i)=1
OD
FOR i=2 TO MAXNUM
DO
FOR j=i+i TO MAXNUM STEP i
DO
pdc(j)==+1
OD
OD
max=0 ind=0
FOR i=1 TO MAXNUM
DO
count=pdc(i)
IF count>max THEN
max=count ind=i
FI
OD
PrintF("%I has %I proper divisors%E",ind,max)
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.
|
#Arturo
|
Arturo
|
define :circle [x y r][]
solveApollonius: function [c1 c2 c3 s1 s2 s3][
v11: sub 2*c2\x 2*c1\x
v12: sub 2*c2\y 2*c1\y
v13: (sub (sub c1\x*c1\x c2\x*c2\x) + (sub c1\y*c1\y c2\y*c2\y) c1\r*c1\r) + c2\r*c2\r
v14: sub 2*s2*c2\r 2*s1*c1\r
v21: sub 2*c3\x 2*c2\x
v22: sub 2*c3\y 2*c2\y
v23: (sub (sub c2\x*c2\x c3\x*c3\x) + (sub c2\y*c2\y c3\y*c3\y) c2\r*c2\r) + c3\r*c3\r
v24: sub 2*s3*c3\r 2*s2*c2\r
w12: v12/v11
w13: v13/v11
w14: v14/v11
w22: sub v22/v21 w12
w23: sub v23/v21 w13
w24: sub v24/v21 w14
p: neg w23/w22
q: w24/w22
m: sub (neg w12)*p w13
n: sub w14 w12*q
a: dec add n*n q*q
b: add (sub 2*m*n 2*n*c1\x) + (sub 2*p*q 2*q*c1\y) 2*s1*c1\r
c: sub sub (sub (c1\x*c1\x) + m*m 2*m*c1\x) + (p*p) + c1\y*c1\y 2*p*c1\y c1\r*c1\r
d: (b*b)-4*a*c
rs: ((neg b)-sqrt d )/(2*a)
xs: m+n*rs
ys: p+q*rs
return @[xs ys rs]
]
c1: to :circle [0.0 0.0 1.0]
c2: to :circle [4.0 0.0 1.0]
c3: to :circle [2.0 4.0 2.0]
print solveApollonius c1 c2 c3 1.0 1.0 1.0
print solveApollonius c1 c2 c3 neg 1.0 neg 1.0 neg 1.0
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
write(&progname) # obtain and write out the program name from the keyword &progname
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.
|
#Io
|
Io
|
#!/usr/bin/env io
main := method(
program := System args at(0)
("Program: " .. program) println
)
if (System args size > 0 and System args at(0) containsSeq("scriptname"), main)
|
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.
|
#J
|
J
|
primorial=:*/@:p:@i."0
|
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.
|
#Java
|
Java
|
import java.math.BigInteger;
public class PrimorialNumbers {
final static int sieveLimit = 1300_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.printf("primorial(%d): %d%n", i, primorial(i));
for (int i = 1; i < 6; i++) {
int len = primorial((int) Math.pow(10, i)).toString().length();
System.out.printf("primorial(10^%d) has length %d%n", i, len);
}
}
static BigInteger primorial(int n) {
if (n == 0)
return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = 0; i < sieveLimit && n > 0; i++) {
if (notPrime[i])
continue;
result = result.multiply(BigInteger.valueOf(i));
n--;
}
return result;
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}
|
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
|
#Java
|
Java
|
import java.math.BigInteger;
import static java.math.BigInteger.ONE;
public class PythTrip{
public static void main(String[] args){
long tripCount = 0, primCount = 0;
//change this to whatever perimeter limit you want;the RAM's the limit
BigInteger periLimit = BigInteger.valueOf(100),
peri2 = periLimit.divide(BigInteger.valueOf(2)),
peri3 = periLimit.divide(BigInteger.valueOf(3));
for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){
BigInteger aa = a.multiply(a);
for(BigInteger b = a.add(ONE);
b.compareTo(peri2) < 0; b = b.add(ONE)){
BigInteger bb = b.multiply(b);
BigInteger ab = a.add(b);
BigInteger aabb = aa.add(bb);
for(BigInteger c = b.add(ONE);
c.compareTo(peri2) < 0; c = c.add(ONE)){
int compare = aabb.compareTo(c.multiply(c));
//if a+b+c > periLimit
if(ab.add(c).compareTo(periLimit) > 0){
break;
}
//if a^2 + b^2 != c^2
if(compare < 0){
break;
}else if (compare == 0){
tripCount++;
System.out.print(a + ", " + b + ", " + c);
//does binary GCD under the hood
if(a.gcd(b).equals(ONE)){
System.out.print(" primitive");
primCount++;
}
System.out.println();
}
}
}
}
System.out.println("Up to a perimeter of " + periLimit + ", there are "
+ tripCount + " triples, of which " + primCount + " are primitive.");
}
}
|
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.
|
#Factor
|
Factor
|
USING: kernel system ;
t [ 0 exit ] when
|
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.
|
#Forth
|
Forth
|
debug @
if QUIT \ quit back to the interpreter
else BYE \ exit forth environment completely (e.g. end of a Forth shell script)
then
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.