task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/QR_decomposition
|
QR decomposition
|
Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#VBA
|
VBA
|
Option Base 1
Private Function vtranspose(v As Variant) As Variant
'-- transpose a vector of length m into an mx1 matrix,
'-- eg {1,2,3} -> {1;2;3}
vtranspose = WorksheetFunction.Transpose(v)
End Function
Private Function mat_col(a As Variant, col As Integer) As Variant
Dim res() As Double
ReDim res(UBound(a))
For i = col To UBound(a)
res(i) = a(i, col)
Next i
mat_col = res
End Function
Private Function mat_norm(a As Variant) As Double
mat_norm = Sqr(WorksheetFunction.SumProduct(a, a))
End Function
Private Function mat_ident(n As Integer) As Variant
mat_ident = WorksheetFunction.Munit(n)
End Function
Private Function sq_div(a As Variant, p As Double) As Variant
Dim res() As Variant
ReDim res(UBound(a))
For i = 1 To UBound(a)
res(i) = a(i) / p
Next i
sq_div = res
End Function
Private Function sq_mul(p As Double, a As Variant) As Variant
Dim res() As Variant
ReDim res(UBound(a), UBound(a, 2))
For i = 1 To UBound(a)
For j = 1 To UBound(a, 2)
res(i, j) = p * a(i, j)
Next j
Next i
sq_mul = res
End Function
Private Function sq_sub(x As Variant, y As Variant) As Variant
Dim res() As Variant
ReDim res(UBound(x), UBound(x, 2))
For i = 1 To UBound(x)
For j = 1 To UBound(x, 2)
res(i, j) = x(i, j) - y(i, j)
Next j
Next i
sq_sub = res
End Function
Private Function matrix_mul(x As Variant, y As Variant) As Variant
matrix_mul = WorksheetFunction.MMult(x, y)
End Function
Private Function QRHouseholder(ByVal a As Variant) As Variant
Dim columns As Integer: columns = UBound(a, 2)
Dim rows As Integer: rows = UBound(a)
Dim m As Integer: m = WorksheetFunction.Max(columns, rows)
Dim n As Integer: n = WorksheetFunction.Min(rows, columns)
I_ = mat_ident(m)
Q_ = I_
Dim q As Variant
Dim u As Variant, v As Variant, j As Integer
For j = 1 To WorksheetFunction.Min(m - 1, n)
u = mat_col(a, j)
u(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)
Q_ = matrix_mul(Q_, q)
Next j
'-- Get the upper triangular matrix R.
Dim R() As Variant
ReDim R(m, n)
For i = 1 To m 'in Phix this is n
For j = 1 To n 'in Phix this is i to n. starting at 1 to fill zeroes
R(i, j) = a(i, j)
Next j
Next i
Dim res(2) As Variant
res(1) = Q_
res(2) = R
QRHouseholder = res
End Function
Private Sub pp(m As Variant)
For i = 1 To UBound(m)
For j = 1 To UBound(m, 2)
Debug.Print Format(m(i, j), "0.#####"),
Next j
Debug.Print
Next i
End Sub
Public Sub main()
a = [{12, -51, 4; 6, 167, -68; -4, 24, -41;-1,1,0;2,0,3}]
result = QRHouseholder(a)
q = result(1)
r_ = result(2)
Debug.Print "A"
pp a
Debug.Print "Q"
pp q
Debug.Print "R"
pp r_
Debug.Print "Q * R"
pp matrix_mul(q, r_)
End Sub
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#AWK
|
AWK
|
# syntax: GAWK -f PRIMALITY_BY_WILSONS_THEOREM.AWK
# converted from FreeBASIC
BEGIN {
start = 2
stop = 200
for (i=start; i<=stop; i++) {
if (is_wilson_prime(i)) {
printf("%5d%1s",i,++count%10?"":"\n")
}
}
printf("\nWilson primality test range %d-%d: %d\n",start,stop,count)
exit(0)
}
function is_wilson_prime(n, fct,i) {
fct = 1
for (i=2; i<=n-1; i++) {
# because (a mod n)*b = (ab mod n)
# it is not necessary to calculate the entire factorial
fct = (fct * i) % n
}
return(fct == n-1)
}
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#BASIC
|
BASIC
|
function wilson_prime(n)
fct = 1
for i = 2 to n-1
fct = (fct * i) mod n
next i
if fct = n-1 then return True else return False
end function
print "Primes below 100" & Chr(10)
for i = 2 to 100
if wilson_prime(i) then print i; " ";
next i
end
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#PL.2FI
|
PL/I
|
declare (t(100),i) fixed binary;
i=101;
t(i)=0;
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#PowerShell
|
PowerShell
|
#Requires -Version <N>[.<n>]
#Requires –PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
#Requires -Modules { <Module-Name> | <Hashtable> }
#Requires –ShellId <ShellId>
#Requires -RunAsAdministrator
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#Python
|
Python
|
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']
>>>
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#Racket
|
Racket
|
use MONKEY-TYPING;
augment class Int {
method times (&what) { what() xx self } # pretend like we're Ruby
}
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#EchoLisp
|
EchoLisp
|
(lib 'math) ;; (in-primes n) stream
(decimals 4)
(define (print-trans trans m N)
(printf "%d first primes. Transitions prime %% %d → next-prime %% %d." N m m)
(define s (// (apply + (vector->list trans)) 100))
(for ((i (* m m)) (t trans))
#:continue (<= t 1) ;; get rid of 2,5 primes
(printf " %d → %d count: %10d frequency: %d %% "
(quotient i m) (% i m) t (// t s) )))
;; can apply to any modulo m
;; (in-primes n) returns a stream of primes
(define (task (m 10) (N 1000_000))
(define trans (make-vector (* m m)))
(for ((p1 (in-primes 2)) (p2 (in-primes 3)) (k N))
(vector+= trans (+ (* (% p1 m) m) (% p2 m)) 1))
(print-trans trans m N))
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#360_Assembly
|
360 Assembly
|
PRIMEDE CSECT
USING PRIMEDE,R13
B 80(R15) skip savearea
DC 17F'0' savearea
DC CL8'PRIMEDE'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 end prolog
LA R2,0
LA R3,1023
LA R4,1024
MR R2,R4
ST R3,N n=1023*1024
LA R5,WBUFFER
LA R6,0
L R1,N n
XDECO R1,0(R5)
LA R5,12(R5)
MVC 0(3,R5),=C' : '
LA R5,3(R5)
LA R0,2
ST R0,I i=2
WHILE1 EQU * do while(i<=n/2)
L R2,N
SRA R2,1
L R4,I
CR R4,R2 i<=n/2
BH EWHILE1
WHILE2 EQU * do while(n//i=0)
L R3,N
LA R2,0
D R2,I
LTR R2,R2 n//i=0
BNZ EWHILE2
ST R3,N n=n/i
ST R3,M m=n
L R1,I i
XDECO R1,WDECO
MVC 0(5,R5),WDECO+7
LA R5,5(R5)
MVI OK,X'01' ok
B WHILE2
EWHILE2 EQU *
L R4,I
CH R4,=H'2' if i=2 then
BNE NE2
LA R0,3
ST R0,I i=3
B EIFNE2
NE2 L R2,I else
LA R2,2(R2)
ST R2,I i=i+2
EIFNE2 B WHILE1
EWHILE1 EQU *
CLI OK,X'01' if ^ok then
BE NOTPRIME
MVC 0(7,R5),=C'[prime]'
LA R5,7(R5)
B EPRIME
NOTPRIME L R1,M m
XDECO R1,WDECO
MVC 0(5,R5),WDECO+7
EPRIME XPRNT WBUFFER,80 put
L R13,4(0,R13) epilog
LM R14,R12,12(R13)
XR R15,R15
BR R14
N DS F
I DS F
M DS F
OK DC X'00'
WBUFFER DC CL80' '
WDECO DS CL16
YREGS
END PRIMEDE
|
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
|
#C.23
|
C#
|
namespace RosettaCode.ProperDivisors
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static class Program
{
private static IEnumerable<int> ProperDivisors(int number)
{
return
Enumerable.Range(1, number / 2)
.Where(divisor => number % divisor == 0);
}
private static void Main()
{
foreach (var number in Enumerable.Range(1, 10))
{
Console.WriteLine("{0}: {{{1}}}", number,
string.Join(", ", ProperDivisors(number)));
}
var record = Enumerable.Range(1, 20000).Select(number => new
{
Number = number,
Count = ProperDivisors(number).Count()
}).OrderByDescending(currentRecord => currentRecord.Count).First();
Console.WriteLine("{0}: {1}", record.Number, record.Count);
}
}
}
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#Clojure
|
Clojure
|
(defn to-cdf [pdf]
(reduce
(fn [acc n] (conj acc (+ (or (last acc) 0) n)))
[]
pdf))
(defn choose [cdf]
(let [r (rand)]
(count
(filter (partial > r) cdf))))
(def *names* '[aleph beth gimel daleth he waw zayin heth])
(def *pdf* (map double [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720]))
(let [num-trials 1000000
cdf (to-cdf *pdf*)
indexes (range (count *names*)) ;; use integer key internally, not name
expected (into (sorted-map) (zipmap indexes *pdf*))
actual (frequencies (repeatedly num-trials #(choose cdf)))]
(doseq [[idx exp] expected]
(println "Expected number of" (*names* idx) "was"
(* num-trials exp) "and actually got" (actual idx))))
|
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
|
Primes - allocate descendants to their ancestors
|
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#Nim
|
Nim
|
import algorithm, strformat, strutils, sugar
const MaxSum = 99
func getPrimes(max: Positive): seq[int] =
if max < 2: return
result.add 2
for n in countup(3, max, 2):
block check:
for p in result:
if n mod p == 0:
break check
result.add n
let primes = getPrimes(MaxSum)
var descendants, ancestors = newSeq[seq[int]](MaxSum + 1)
for p in primes:
descendants[p].add p
for s in 1..(descendants.high - p):
descendants[s + p].add collect(newSeq, for pr in descendants[s]: p * pr)
for p in primes & 4:
discard descendants[p].pop()
var total = 0
for s in 1..MaxSum:
descendants[s].sort()
for d in descendants[s]:
if d > MaxSum: break
ancestors[d] = ancestors[s] & s
let dlength = descendants[s].len
echo &"[{s}] Level: {ancestors[s].len}"
echo "Ancestors: ", if ancestors[s].len != 0: ancestors[s].join(" ") else: "None"
echo "Descendants: ", if dlength != 0: $dlength else: "None"
if dlength != 0: echo descendants[s].join(", ")
echo ""
inc total, dlength
echo "Total descendants: ", total
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#CLU
|
CLU
|
prio_queue = cluster [P, T: type] is new, empty, push, pop
where P has lt: proctype (P,P) returns (bool)
item = struct[prio: P, val: T]
rep = array[item]
new = proc () returns (cvt)
return (rep$create(0))
end new
empty = proc (pq: cvt) returns (bool)
return (rep$empty(pq))
end empty
parent = proc (k: int) returns (int)
return ((k-1)/2)
end parent
left = proc (k: int) returns (int)
return (2*k + 1)
end left
right = proc (k: int) returns (int)
return (2*k + 2)
end right
swap = proc (pq: rep, a: int, b: int)
temp: item := pq[a]
pq[a] := pq[b]
pq[b] := temp
end swap
min_heapify = proc (pq: rep, k: int)
l: int := left(k)
r: int := right(k)
smallest: int := k
if l < rep$size(pq) cand pq[l].prio < pq[smallest].prio then
smallest := l
end
if r < rep$size(pq) cand pq[r].prio < pq[smallest].prio then
smallest := r
end
if smallest ~= k then
swap(pq, k, smallest)
min_heapify(pq, smallest)
end
end min_heapify
push = proc (pq: cvt, prio: P, val: T)
rep$addh(pq, item${prio: prio, val: val})
i: int := rep$high(pq)
while i ~= 0 cand pq[i].prio < pq[parent(i)].prio do
swap(pq, i, parent(i))
i := parent(i)
end
end push
pop = proc (pq: cvt) returns (P, T) signals (empty)
if empty(up(pq)) then signal empty end
if rep$size(pq) = 1 then
i: item := rep$remh(pq)
return (i.prio, i.val)
end
root: item := pq[0]
pq[0] := rep$remh(pq)
min_heapify(pq, 0)
return (root.prio, root.val)
end pop
end prio_queue
start_up = proc ()
% use ints for priority and strings for data
prioq = prio_queue[int,string]
% make the priority queue
pq: prioq := prioq$new()
% add some tasks
prioq$push(pq, 3, "Clear drains")
prioq$push(pq, 4, "Feed cat")
prioq$push(pq, 5, "Make tea")
prioq$push(pq, 1, "Solve RC tasks")
prioq$push(pq, 2, "Tax return")
% print them all out in order
po: stream := stream$primary_output()
while ~prioq$empty(pq) do
prio: int task: string
prio, task := prioq$pop(pq)
stream$putl(po, int$unparse(prio) || ": " || task)
end
end start_up
|
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.
|
#Haskell
|
Haskell
|
data Circle = Circle { x, y, r :: Double } deriving (Show, Eq)
data Tangent = Externally | Internally deriving Eq
{--
Solves the Problem of Apollonius (finding a circle tangent to three
other circles in the plane).
Params:
c1 = First circle of the problem.
c2 = Second circle of the problem.
c3 = Third circle of the problem.
t1 = How is the solution tangent (externally or internally) to c1.
t2 = How is the solution tangent (externally or internally) to c2.
t3 = How is the solution tangent (externally or internally) to c3.
Returns: The Circle that is tangent to c1, c2 and c3.
--}
solveApollonius :: Circle -> Circle -> Circle ->
Tangent -> Tangent -> Tangent ->
Circle
solveApollonius c1 c2 c3 t1 t2 t3 =
Circle (m + n * rs) (p + q * rs) rs
where
s1 = if t1 == Externally then 1.0 else -1.0
s2 = if t2 == Externally then 1.0 else -1.0
s3 = if t3 == Externally then 1.0 else -1.0
v11 = 2 * x c2 - 2 * x c1
v12 = 2 * y c2 - 2 * y c1
v13 = x c1 ^ 2 - x c2 ^ 2 +
y c1 ^ 2 - y c2 ^ 2 -
r c1 ^ 2 + r c2 ^ 2
v14 = 2 * s2 * r c2 - 2 * s1 * r c1
v21 = 2 * x c3 - 2 * x c2
v22 = 2 * y c3 - 2 * y c2
v23 = x c2 ^ 2 - x c3 ^ 2 +
y c2 ^ 2 - y c3 ^ 2 -
r c2 ^ 2 + r c3 ^ 2;
v24 = 2 * s3 * r c3 - 2 * s2 * r c2
w12 = v12 / v11
w13 = v13 / v11
w14 = v14 / v11
w22 = v22 / v21 - w12
w23 = v23 / v21 - w13
w24 = v24 / v21 - w14
p = -w23 / w22
q = w24 / w22
m = -w12 * p - w13
n = w14 - w12 * q
a = n * n + q ^ 2 - 1
b = 2 * m * n - 2 * n * x c1 +
2 * p * q - 2 * q * y c1 +
2 * s1 * r c1
c = x c1 ^ 2 + m ^ 2 - 2 * m * x c1 +
p ^ 2 + y c1 ^ 2 - 2 * p * y c1 - r c1 ^ 2
-- Find a root of a quadratic equation.
-- This requires the circle centers not to be e.g. colinear.
d = b ^ 2 - 4 * a * c
rs = (-b - sqrt d) / (2 * a)
main = do
let c1 = Circle 0.0 0.0 1.0
let c2 = Circle 4.0 0.0 1.0
let c3 = Circle 2.0 4.0 2.0
let te = Externally
print $ solveApollonius c1 c2 c3 te te te
let ti = Internally
print $ solveApollonius c1 c2 c3 ti ti ti
|
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.
|
#Oberon-2
|
Oberon-2
|
MODULE ProgramName;
IMPORT
NPCT:Args,
Out;
BEGIN
Out.Object("Program name: " + Args.Get(0));Out.Ln
END ProgramName.
|
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.
|
#Objective-C
|
Objective-C
|
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
@autoreleasepool {
char *program = argv[0];
printf("Program: %s\n", program);
// Alternatively:
NSString *program2 = [[NSProcessInfo processInfo] processName];
NSLog(@"Program: %@\n", program2);
}
return 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.
|
#Sidef
|
Sidef
|
say (
'First ten primorials: ',
{|i| pn_primorial(i) }.map(^10).join(', ')
)
{ |i|
say ("primorial(10^#{i}) has " + pn_primorial(10**i).len + ' digits')
} << 1..6
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#OCaml
|
OCaml
|
let isqrt n =
let rec iter t =
let d = n - t*t in
if (0 <= d) && (d < t+t+1) (* t*t <= n < (t+1)*(t+1) *)
then t else iter ((t+(n/t))/2)
in iter 1
let rec gcd a b =
let t = a mod b in
if t = 0 then b else gcd b t
let coprime a b = gcd a b = 1
let num_to ms =
let ctr = ref 0 in
let prim_ctr = ref 0 in
let max_m = isqrt (ms/2) in
for m = 2 to max_m do
for j = 0 to (m/2) - 1 do
let n = m-(2*j+1) in
if coprime m n then
let s = 2*m*(m+n) in
if s <= ms then
(ctr := !ctr + (ms/s); incr prim_ctr)
done
done;
(!ctr, !prim_ctr)
let show i =
let s, p = num_to i in
Printf.printf "For perimeters up to %d there are %d total and %d primitive\n%!" i s p;;
List.iter show [ 100; 1000; 10000; 100000; 1000000; 10000000; 100000000 ]
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module Checkit {
For i=1 to 200
Thread {
k++
Print "Thread:"; num, "k=";k
} as M
Thread M Execute {
static num=M, k=1000*i
}
Thread M interval 100+900*rnd
next i
Task.Main 20 {
if random(10)=1 then Set End
}
}
Checkit
|
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.
|
#M4
|
M4
|
beginning
define(`problem',1)
ifelse(problem,1,`m4exit(1)')
ending
|
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}}
|
#Wren
|
Wren
|
import "/matrix" for Matrix
import "/fmt" for Fmt
var minor = Fn.new { |x, d|
var nr = x.numRows
var nc = x.numCols
var m = Matrix.new(nr, nc)
for (i in 0...d) m[i, i] = 1
for (i in d...nr) {
for (j in d...nc) m[i, j] = x[i, j]
}
return m
}
var vmadd = Fn.new { |a, b, s|
var n = a.count
var c = List.filled(n, 0)
for (i in 0...n) c[i] = a[i] + s * b[i]
return c
}
var vmul = Fn.new { |v|
var n = v.count
var x = Matrix.new(n, n)
for (i in 0...n) {
for (j in 0...n) x[i, j] = -2 * v[i] * v[j]
}
for (i in 0...n) x[i, i] = x[i, i] + 1
return x
}
var vnorm = Fn.new { |x|
var n = x.count
var sum = 0
for (i in 0...n) sum = sum + x[i] * x[i]
return sum.sqrt
}
var vdiv = Fn.new { |x, d|
var n = x.count
var y = List.filled(n, 0)
for (i in 0...n) y[i] = x[i] / d
return y
}
var mcol = Fn.new { |m, c|
var n = m.numRows
var v = List.filled(n, 0)
for (i in 0...n) v[i] = m[i, c]
return v
}
var householder = Fn.new { |m|
var nr = m.numRows
var nc = m.numCols
var q = List.filled(nr, null)
var z = m.copy()
var k = 0
while (k < nc && k < nr-1) {
var e = List.filled(nr, 0)
z = minor.call(z, k)
var x = mcol.call(z, k)
var a = vnorm.call(x)
if (m[k, k] > 0) a = -a
for (i in 0...nr) e[i] = (i == k) ? 1 : 0
e = vmadd.call(x, e, a)
e = vdiv.call(e, vnorm.call(e))
q[k] = vmul.call(e)
z = q[k] * z
k = k + 1
}
var Q = q[0]
var R = q[0] * m
var i = 1
while (i < nc && i < nr-1) {
Q = q[i] * Q
i = i + 1
}
R = Q * m
Q = Q.transpose
return [Q, R]
}
var inp = [
[12, -51, 4],
[ 6, 167, -68],
[-4, 24, -41],
[-1, 1, 0],
[ 2, 0, 3]
]
var x = Matrix.new(inp)
var res = householder.call(x)
var Q = res[0]
var R = res[1]
var m = Q * R
System.print("Q:")
Fmt.mprint(Q, 8, 3)
System.print("\nR:")
Fmt.mprint(R, 8, 3)
System.print("\nQ * R:")
Fmt.mprint(m, 8, 3)
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#C
|
C
|
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
// uses wilson's theorem
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
// Can check up to 21, more will require a big integer library
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#C.23
|
C#
|
using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
// initialization
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
// dumps a chunk of the prime list (lst)
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
// returns the ordinal string representation of a number
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
// shows the results of one type of prime tabulation
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
// for stand-alone computation
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
// end stand-alone
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
// stand-alone computation
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#Raku
|
Raku
|
use MONKEY-TYPING;
augment class Int {
method times (&what) { what() xx self } # pretend like we're Ruby
}
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#REXX
|
REXX
|
The REXX language has several pragmatic statements:
∙ NUMERIC DIGITS {nnn}
∙ NUMERIC FORM {ENGINEERING │ SCIENTIFIC}
∙ NUMERIC FUZZ {nnn}
∙ OPTIONS {xxx yyy zzz}
∙ TRACE {options}
∙ SIGNAL {ON │ OFF} LOSTDIGITS
∙ SIGNAL {ON │ OFF} NOVALUE
∙ SIGNAL {ON │ OFF} SYNTAX
∙ SIGNAL │ CALL {ON │ OFF} ERROR
∙ SIGNAL │ CALL {ON │ OFF} FAILURE
∙ SIGNAL │ CALL {ON │ OFF} HALT
∙ SIGNAL │ CALL {ON │ OFF} NOTREADY
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#Scala
|
Scala
|
@inline
@tailrec
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#Tcl
|
Tcl
|
set -vx # Activate both script line output and command line arguments pragma
set +vx # Deactivate both pragmatic directives
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#UNIX_Shell
|
UNIX Shell
|
set -vx # Activate both script line output and command line arguments pragma
set +vx # Deactivate both pragmatic directives
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#Elixir
|
Elixir
|
defmodule Prime do
def conspiracy(m) do
IO.puts "#{m} first primes. Transitions prime % 10 → next-prime % 10."
Enum.map(prime(m), &rem(&1, 10))
|> Enum.chunk(2,1)
|> Enum.reduce(Map.new, fn [a,b],acc -> Map.update(acc, {a,b}, 1, &(&1+1)) end)
|> Enum.sort
|> Enum.each(fn {{a,b},v} ->
sv = to_string(v) |> String.rjust(10)
sf = Float.to_string(100.0*v/m, [decimals: 4])
IO.puts "#{a} → #{b} count:#{sv} frequency:#{sf} %"
end)
end
def prime(n) do
max = n * :math.log(n * :math.log(n)) |> trunc # from Rosser's theorem
Enum.to_list(2..max)
|> prime(:math.sqrt(max), [])
|> Enum.take(n)
end
defp prime([h|t], limit, result) when h>limit, do: Enum.reverse(result, [h|t])
defp prime([h|t], limit, result) do
prime((for x <- t, rem(x,h)>0, do: x), limit, [h|result])
end
end
Prime.conspiracy(1000000)
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#F.23
|
F#
|
// Prime Conspiracy. Nigel Galloway: March 27th., 2018
primes|>Seq.take 10000|>Seq.map(fun n->n%10)|>Seq.pairwise|>Seq.countBy id|>Seq.groupBy(fun((n,_),_)->n)|>Seq.sortBy(fst)
|>Seq.iter(fun(_,n)->Seq.sortBy(fun((_,n),_)->n) n|>Seq.iter(fun((n,g),z)->printfn "%d -> %d ocurred %3d times" n g z))
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#AArch64_Assembly
|
AArch64 Assembly
|
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program primeDecomp64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBFACT, 100
/*******************************************/
/* Structures */
/********************************************/
/* structurea area factors */
.struct 0
fac_value: // factor
.struct fac_value + 8
fac_number: // number of identical factors
.struct fac_number + 8
fac_end:
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessNotPrime: .asciz "Not prime.\n"
szMessPrime: .asciz "Prime\n"
szCarriageReturn: .asciz "\n"
szSpaces: .asciz " "
szMessNumber: .asciz " The factors of @ are :\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sZoneConv: .skip 32
.align 4
tbZoneDecom: .skip fac_end * NBFACT
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // program start
ldr x0,qAdrszMessStartPgm // display start message
bl affichageMess
ldr x20,qVal
//mov x20,17
mov x0,x20
ldr x1,qAdrtbZoneDecom
bl decompFact // decomposition
cmp x0,#0
beq 1f
mov x2,x0
mov x0,x20
ldr x1,qAdrtbZoneDecom
bl displayFactors // display factors
b 2f
1:
ldr x0,qAdrszMessPrime // prime
bl affichageMess
2:
ldr x0,qAdrszMessEndPgm // display end message
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessNotPrime: .quad szMessNotPrime
qAdrszMessPrime: .quad szMessPrime
qAdrtbZoneDecom: .quad tbZoneDecom
//qVal: .quad 2 <<31
qVal: .quad 1047552 // test not prime
//qVal: .quad 1429671721 // test not prime (37811 * 37811)
/******************************************************************/
/* prime decomposition */
/******************************************************************/
/* x0 contains the number */
/* x1 contains address factors array */
/* REMARK no save register x9-x19 */
decompFact:
stp x1,lr,[sp,-16]! // save registers
mov x12,x0 // save number
bl isPrime // prime ?
cbnz x0,12f // yes -> no decomposition
mov x19,fac_end // element area size
mov x18,0 // raz indice
mov x16,0 // prev divisor
mov x17,0 // number of identical divisors
mov x13,2 // first divisor
2:
cmp x12,1
beq 10f
udiv x14,x12,x13 // division
msub x15,x14,x13,x12 // remainder = x12 -(x13*x14)
cbnz x15,5f // if remainder <> zero x13 not divisor
mov x12,x14 // quotient -> new dividende
cmp x13,x16 // same divisor ?
beq 4f // yes
cbz x16,3f // yes it is first divisor ?
madd x11,x18,x19,x1 // no -> store prev divisor in the area
str x16,[x11,fac_value]
str x17,[x11,fac_number] // and store number of same factor
add x18,x18,1 // increment indice
mov x17,0 // raz number of same factor
3:
mov x16,x13 // save new divisor
4:
add x17,x17,1 // increment number of same factor
mov x0,x12 // the new dividende is prime ?
bl isPrime
cbnz x0,10f // yes
b 2b // else loop
5: // divisor is not a factor
cmp x13,2 // begin ?
cinc x13,x13,ne // if divisor <> 2 add 1
add x13,x13,1
b 2b // and loop
10: // new dividende is prime
cmp x16,x12 // divisor = dividende ?
cinc x17,x17,eq //add 1 if last dividende = diviseur
madd x11,x18,x19,x1
str x16,[x11,fac_value] // store divisor in area
str x17,[x11,fac_number] // and store number
add x18,x18,1 // increment indice
cmp x16,x12 //store last dividende if <> diviseur
beq 11f
madd x11,x18,x19,x1
str x12,[x11,fac_value] // sinon stockage dans la table
mov x17,1
str x17,[x11,fac_number] // store 1 in number
add x18,x18,1
11:
mov x0,x18 // return nb factors
b 100f
12:
mov x0,#0 // number is prime
b 100f
100:
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/******************************************************************/
/* prime decomposition */
/******************************************************************/
/* x0 contains the number */
/* x1 contains address factors array */
/* x2 number of factors */
displayFactors:
stp x1,lr,[sp,-16]! // save registres
mov x19,fac_end // element area size
mov x13,x1 // save area address
ldr x1,qAdrsZoneConv // load zone conversion address
bl conversion10
ldr x0,qAdrszMessNumber
bl strInsertAtCharInc // insert result at Second @ character
bl affichageMess
mov x9,0 // indice
1:
madd x10,x9,x19,x13 // compute address area element
ldr x0,[x10,fac_value]
ldr x12,[x10,fac_number]
bl conversion10 // decimal conversion
2:
mov x0,x1
bl affichageMess
ldr x0,qAdrszSpaces
bl affichageMess
subs x12,x12,#1
bgt 2b
add x9,x9,1
cmp x9,x2
blt 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrsZoneConv: .quad sZoneConv
qAdrszSpaces: .quad szSpaces
qAdrszMessNumber: .quad szMessNumber
/******************************************************************/
/* test if number is prime */
/******************************************************************/
/* x0 contains the number */
/* x0 return 1 if prime else return 0 */
isPrime:
stp x1,lr,[sp,-16]! // save registers
cmp x0,1 // <= 1 ?
ble 98f
cmp x0,3 // 2 and 3 prime
ble 97f
tst x0,1 // even ?
beq 98f
mov x9,3 // first divisor
1:
udiv x11,x0,x9
msub x10,x11,x9,x0 // compute remainder
cbz x10,98f // end if zero
add x9,x9,#2 // increment divisor
cmp x9,x11 // divisors<=quotient ?
ble 1b // loop
97:
mov x0,1 // return prime
b 100f
98:
mov x0,0 // not prime
b 100f
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
|
#C.2B.2B
|
C++
|
#include <vector>
#include <iostream>
#include <algorithm>
std::vector<int> properDivisors ( int number ) {
std::vector<int> divisors ;
for ( int i = 1 ; i < number / 2 + 1 ; i++ )
if ( number % i == 0 )
divisors.push_back( i ) ;
return divisors ;
}
int main( ) {
std::vector<int> divisors ;
unsigned int maxdivisors = 0 ;
int corresponding_number = 0 ;
for ( int i = 1 ; i < 11 ; i++ ) {
divisors = properDivisors ( i ) ;
std::cout << "Proper divisors of " << i << ":\n" ;
for ( int number : divisors ) {
std::cout << number << " " ;
}
std::cout << std::endl ;
divisors.clear( ) ;
}
for ( int i = 11 ; i < 20001 ; i++ ) {
divisors = properDivisors ( i ) ;
if ( divisors.size( ) > maxdivisors ) {
maxdivisors = divisors.size( ) ;
corresponding_number = i ;
}
divisors.clear( ) ;
}
std::cout << "Most divisors has " << corresponding_number <<
" , it has " << maxdivisors << " divisors!\n" ;
return 0 ;
}
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#Common_Lisp
|
Common Lisp
|
(defvar *probabilities* '((aleph 1/5)
(beth 1/6)
(gimel 1/7)
(daleth 1/8)
(he 1/9)
(waw 1/10)
(zayin 1/11)
(heth 1759/27720)))
(defun calculate-probabilities (choices &key (repetitions 1000000))
(assert (= 1 (reduce #'+ choices :key #'second)))
(labels ((make-ranges ()
(loop for (datum probability) in choices
sum (coerce probability 'double-float) into total
collect (list datum total)))
(pick (ranges)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(loop with random = (random 1.0d0)
for (datum below) of-type (t double-float) in ranges
when (< random below)
do (return datum)))
(populate-hash (ranges)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(loop repeat (the fixnum repetitions)
with hash = (make-hash-table)
do (incf (the fixnum (gethash (pick ranges) hash 0)))
finally (return hash)))
(make-table-data (hash)
(loop for (datum probability) in choices
collect (list datum
(float (/ (gethash datum hash)
repetitions))
(float probability)))))
(format t "Datum~10,2TOccured~20,2TExpected~%")
(format t "~{~{~A~10,2T~F~20,2T~F~}~%~}"
(make-table-data (populate-hash (make-ranges))))))
CL-USER> (calculate-probabilities *probabilities*)
Datum Occured Expected
ALEPH 0.200156 0.2
BETH 0.166521 0.16666667
GIMEL 0.142936 0.14285715
DALETH 0.124779 0.125
HE 0.111601 0.11111111
WAW 0.100068 0.1
ZAYIN 0.090458 0.09090909
HETH 0.063481 0.06345599
|
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
|
Primes - allocate descendants to their ancestors
|
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#Perl
|
Perl
|
use List::Util qw(sum uniq);
use ntheory qw(nth_prime);
my $max = 99;
my %tree;
sub allocate {
my($n, $i, $sum,, $prod) = @_;
$i //= 0; $sum //= 0; $prod //= 1;
for my $k (0..$max) {
next if $k < $i;
my $p = nth_prime($k+1);
if (($sum + $p) <= $max) {
allocate($n, $k, $sum + $p, $prod * $p);
} else {
last if $sum == $prod;
$tree{$sum}{descendants}{$prod} = 1;
$tree{$prod}{ancestor} = [uniq $sum, @{$tree{$sum}{ancestor}}] unless $prod > $max || $sum == 0;
last;
}
}
}
sub abbrev { # abbreviate long lists to first and last 5 elements
my(@d) = @_;
return @d if @d < 11;
@d[0 .. 4], '...', @d[-5 .. -1];
}
allocate($_) for 1 .. $max;
for (1 .. 15, 46, $max) {
printf "%2d, %2d Ancestors: %-15s", $_, (scalar uniq @{$tree{$_}{ancestor}}),
'[' . join(' ',uniq @{$tree{$_}{ancestor}}) . ']';
my $dn = 0; my $dl = '';
if ($tree{$_}{descendants}) {
$dn = keys %{$tree{$_}{descendants}};
$dl = join ' ', abbrev(sort { $a <=> $b } keys %{$tree{$_}{descendants}});
}
printf "%5d Descendants: %s", $dn, "[$dl]\n";
}
map { for my $k (keys %{$tree{$_}{descendants}}) { $total += $tree{$_}{descendants}{$k} } } 1..$max;
print "\nTotal descendants: $total\n";
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#CoffeeScript
|
CoffeeScript
|
PriorityQueue = ->
# Use closure style for object creation (so no "new" required).
# Private variables are toward top.
h = []
better = (a, b) ->
h[a].priority < h[b].priority
swap = (a, b) ->
[h[a], h[b]] = [h[b], h[a]]
sift_down = ->
max = h.length
n = 0
while n < max
c1 = 2*n + 1
c2 = c1 + 1
best = n
best = c1 if c1 < max and better(c1, best)
best = c2 if c2 < max and better(c2, best)
return if best == n
swap n, best
n = best
sift_up = ->
n = h.length - 1
while n > 0
parent = Math.floor((n-1) / 2)
return if better parent, n
swap n, parent
n = parent
# now return the public interface, which is an object that only
# has functions on it
self =
size: ->
h.length
push: (priority, value) ->
elem =
priority: priority
value: value
h.push elem
sift_up()
pop: ->
throw Error("cannot pop from empty queue") if h.length == 0
value = h[0].value
last = h.pop()
if h.length > 0
h[0] = last
sift_down()
value
# test
do ->
pq = PriorityQueue()
pq.push 3, "Clear drains"
pq.push 4, "Feed cat"
pq.push 5, "Make tea"
pq.push 1, "Solve RC tasks"
pq.push 2, "Tax return"
while pq.size() > 0
console.log pq.pop()
# test high performance
for n in [1..100000]
priority = Math.random()
pq.push priority, priority
v = pq.pop()
console.log "First random element was #{v}"
while pq.size() > 0
new_v = pq.pop()
throw Error "Queue broken" if new_v < v
v = new_v
console.log "Final random element was #{v}"
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
link graphics
record circle(x,y,r)
global scale,xoffset,yoffset,yadjust
procedure main()
WOpen("size=400,400") | stop("Unable to open Window")
scale := 28
xoffset := WAttrib("width") / 2
yoffset := ( yadjust := WAttrib("height")) / 2
WC(c1 := circle(0,0,1),"black")
WC(c2 := circle(4,0,1),"black")
WC(c3 := circle(2,4,2),"black")
WC(c4 := Apollonius(c1,c2,c3,1,1,1),"green") #/ Expects "Circle[x=2.00,y=2.10,r=3.90]" (green circle in image)
WC(c5 := Apollonius(c1,c2,c3,-1,-1,-1),"red") #/ Expects "Circle[x=2.00,y=0.83,r=1.17]" (red circle in image)
WAttrib("fg=blue")
DrawLine( 0*scale+xoffset, yadjust-(-1*scale+yoffset), 0*scale+xoffset, yadjust-(4*scale+yoffset) )
DrawLine( -1*scale+xoffset, yadjust-(0*scale+yoffset), 4*scale+xoffset, yadjust-(0*scale+yoffset) )
WDone()
end
procedure WC(c,fg) # write and plot circle
WAttrib("fg="||fg)
DrawCircle(c.x*scale+xoffset, yadjust-(c.y*scale+yoffset), c.r*scale)
return write("Circle(x,y,r) := (",c.x,", ",c.y,", ",c.r,")")
end
procedure Apollonius(c1,c2,c3,s1,s2,s3) # solve Apollonius
v11 := 2.*(c2.x - c1.x)
v12 := 2.*(c2.y - c1.y)
v13 := c1.x^2 - c2.x^2 + c1.y^2 - c2.y^2 - c1.r^2 + c2.r^2
v14 := 2.*(s2*c2.r - s1*c1.r)
v21 := 2.*(c3.x - c2.x)
v22 := 2.*(c3.y - c2.y)
v23 := c2.x^2 - c3.x^2 + c2.y^2 - c3.y^2 - c2.r^2 + c3.r^2
v24 := 2.*(s3*c3.r - s2*c2.r)
w12 := v12/v11
w13 := v13/v11
w14 := v14/v11
w22 := v22/v21-w12
w23 := v23/v21-w13
w24 := v24/v21-w14
P := -w23/w22
Q := w24/w22
M := -w12*P-w13
N := w14 - w12*Q
a := N*N + Q*Q - 1
b := 2*M*N - 2*N*c1.x + 2*P*Q - 2*Q*c1.y + 2*s1*c1.r
c := c1.x*c1.x + M*M - 2*M*c1.x + P*P + c1.y*c1.y - 2*P*c1.y - c1.r*c1.r
#// Find a root of a quadratic equation. This requires the circle centers not to be e.g. colinear
D := b*b-4*a*c
rs := (-b-sqrt(D))/(2*a)
xs := M + N * rs
ys := P + Q * rs
return circle(xs,ys,rs)
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.
|
#OCaml
|
OCaml
|
let () =
print_endline Sys.executable_name;
print_endline Sys.argv.(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.
|
#Octave
|
Octave
|
function main()
program = program_name();
printf("Program: %s", program);
endfunction
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.
|
#Smalltalk
|
Smalltalk
| |
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.
|
#Wren
|
Wren
|
import "/big" for BigInt
import "/math" for Int
import "/fmt" for Fmt
var vecprod = Fn.new { |primes|
var le = primes.count
if (le == 0) return BigInt.one
var s = List.filled(le, null)
for (i in 0...le) s[i] = BigInt.new(primes[i])
while (le > 1) {
var c = (le/2).floor
for(i in 0...c) s[i] = s[i] * s[le-i-1]
if (le & 1 == 1) c = c + 1
le = c
}
return s[0]
}
var primes = Int.primeSieve(1.3e6) // enough to generate first 100,000 primes
var prod = 1
System.print("The first ten primorial numbers are:")
for (i in 0..9) {
System.print("%(i): %(prod)")
prod = prod * primes[i]
}
System.print("\nThe following primorials have the lengths shown:")
// first multiply the first 100,000 primes together in pairs to reduce BigInt conversions needed
var primes2 = List.filled(50000, 0)
for (i in 0...50000) primes2[i] = primes[2*i] * primes[2*i+1]
for (i in [10, 100, 1000, 10000, 100000]) {
Fmt.print("$6d: $d", i, vecprod.call(primes2[0...i/2]).toString.count)
}
|
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
|
#Ol
|
Ol
|
; triples generator based on Euclid's formula, creates lazy list
(define (euclid-formula max)
(let loop ((a 3) (b 4) (c 5) (tail #null))
(if (<= (+ a b c) max)
(cons (tuple a b c) (lambda ()
(let ((d (- b)) (z (- a)))
(loop (+ a d d c c) (+ a a d c c) (+ a a d d c c c) (lambda ()
(loop (+ a b b c c) (+ a a b c c) (+ a a b b c c c) (lambda ()
(loop (+ z b b c c) (+ z z b c c) (+ z z b b c c c) tail))))))))
tail)))
; let's do calculations
(define (calculate max)
(let loop ((p 0) (t 0) (ll (euclid-formula max)))
(cond
((null? ll)
(cons p t))
((function? ll)
(loop p t (ll)))
(else
(let ((triple (car ll)))
(loop (+ p 1) (+ t (div max (apply + triple)))
(cdr ll)))))))
; print values for 10..100000
(for-each (lambda (max)
(print max ": " (calculate max)))
(map (lambda (n) (expt 10 n)) (iota 6 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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
If[problem, Abort[]];
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#MATLAB
|
MATLAB
|
if condition
return
end
|
http://rosettacode.org/wiki/QR_decomposition
|
QR decomposition
|
Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decomposition.
Task
Demonstrate the QR decomposition on the example matrix from the Wikipedia article:
A
=
(
12
−
51
4
6
167
−
68
−
4
24
−
41
)
{\displaystyle A={\begin{pmatrix}12&-51&4\\6&167&-68\\-4&24&-41\end{pmatrix}}}
and the usage for linear least squares problems on the example from Polynomial regression. The method of Householder reflections should be used:
Method
Multiplying a given vector
a
{\displaystyle {\mathit {a}}}
, for example the first column of matrix
A
{\displaystyle {\mathit {A}}}
, with the Householder matrix
H
{\displaystyle {\mathit {H}}}
, which is given as
H
=
I
−
2
u
T
u
u
u
T
{\displaystyle H=I-{\frac {2}{u^{T}u}}uu^{T}}
reflects
a
{\displaystyle {\mathit {a}}}
about a plane given by its normal vector
u
{\displaystyle {\mathit {u}}}
. When the normal vector of the plane
u
{\displaystyle {\mathit {u}}}
is given as
u
=
a
−
∥
a
∥
2
e
1
{\displaystyle u=a-\|a\|_{2}\;e_{1}}
then the transformation reflects
a
{\displaystyle {\mathit {a}}}
onto the first standard basis vector
e
1
=
[
1
0
0
.
.
.
]
T
{\displaystyle e_{1}=[1\;0\;0\;...]^{T}}
which means that all entries but the first become zero. To avoid numerical cancellation errors, we should take the opposite sign of
a
1
{\displaystyle a_{1}}
:
u
=
a
+
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle u=a+{\textrm {sign}}(a_{1})\|a\|_{2}\;e_{1}}
and normalize with respect to the first element:
v
=
u
u
1
{\displaystyle v={\frac {u}{u_{1}}}}
The equation for
H
{\displaystyle H}
thus becomes:
H
=
I
−
2
v
T
v
v
v
T
{\displaystyle H=I-{\frac {2}{v^{T}v}}vv^{T}}
or, in another form
H
=
I
−
β
v
v
T
{\displaystyle H=I-\beta vv^{T}}
with
β
=
2
v
T
v
{\displaystyle \beta ={\frac {2}{v^{T}v}}}
Applying
H
{\displaystyle {\mathit {H}}}
on
a
{\displaystyle {\mathit {a}}}
then gives
H
a
=
−
sign
(
a
1
)
∥
a
∥
2
e
1
{\displaystyle H\;a=-{\textrm {sign}}(a_{1})\;\|a\|_{2}\;e_{1}}
and applying
H
{\displaystyle {\mathit {H}}}
on the matrix
A
{\displaystyle {\mathit {A}}}
zeroes all subdiagonal elements of the first column:
H
1
A
=
(
r
11
r
12
r
13
0
∗
∗
0
∗
∗
)
{\displaystyle H_{1}\;A={\begin{pmatrix}r_{11}&r_{12}&r_{13}\\0&*&*\\0&*&*\end{pmatrix}}}
In the second step, the second column of
A
{\displaystyle {\mathit {A}}}
, we want to zero all elements but the first two, which means that we have to calculate
H
{\displaystyle {\mathit {H}}}
with the first column of the submatrix (denoted *), not on the whole second column of
A
{\displaystyle {\mathit {A}}}
.
To get
H
2
{\displaystyle H_{2}}
, we then embed the new
H
{\displaystyle {\mathit {H}}}
into an
m
×
n
{\displaystyle m\times n}
identity:
H
2
=
(
1
0
0
0
H
0
)
{\displaystyle H_{2}={\begin{pmatrix}1&0&0\\0&H&\\0&&\end{pmatrix}}}
This is how we can, column by column, remove all subdiagonal elements of
A
{\displaystyle {\mathit {A}}}
and thus transform it into
R
{\displaystyle {\mathit {R}}}
.
H
n
.
.
.
H
3
H
2
H
1
A
=
R
{\displaystyle H_{n}\;...\;H_{3}H_{2}H_{1}A=R}
The product of all the Householder matrices
H
{\displaystyle {\mathit {H}}}
, for every column, in reverse order, will then yield the orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
.
H
1
H
2
H
3
.
.
.
H
n
=
Q
{\displaystyle H_{1}H_{2}H_{3}\;...\;H_{n}=Q}
The QR decomposition should then be used to solve linear least squares (Multiple regression) problems
A
x
=
b
{\displaystyle {\mathit {A}}x=b}
by solving
R
x
=
Q
T
b
{\displaystyle R\;x=Q^{T}\;b}
When
R
{\displaystyle {\mathit {R}}}
is not square, i.e.
m
>
n
{\displaystyle m>n}
we have to cut off the
m
−
n
{\displaystyle {\mathit {m}}-n}
zero padded bottom rows.
R
=
(
R
1
0
)
{\displaystyle R={\begin{pmatrix}R_{1}\\0\end{pmatrix}}}
and the same for the RHS:
Q
T
b
=
(
q
1
q
2
)
{\displaystyle Q^{T}\;b={\begin{pmatrix}q_{1}\\q_{2}\end{pmatrix}}}
Finally, solve the square upper triangular system by back substitution:
R
1
x
=
q
1
{\displaystyle R_{1}\;x=q_{1}}
|
#zkl
|
zkl
|
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
A:=GSL.Matrix(3,3).set(12.0, -51.0, 4.0,
6.0, 167.0, -68.0,
4.0, 24.0, -41.0);
Q,R:=A.QRDecomp();
println("Q:\n",Q.format());
println("R:\n",R.format());
println("Q*R:\n",(Q*R).format());
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#C.2B.2B
|
C++
|
#include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#Wren
|
Wren
|
/* windows.wren */
class Windows {
static message { "Using Windows" }
static lineSeparator { "\\r\\n" }
}
|
http://rosettacode.org/wiki/Pragmatic_directives
|
Pragmatic directives
|
Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
Task
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
|
#XPL0
|
XPL0
|
string 0; \makes all following strings in the code zero-terminated
string 1; \(or any non-zero argument) reverts to MSB termination
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#Factor
|
Factor
|
USING: assocs formatting grouping kernel math math.primes math.statistics
sequences sorting ;
IN: rosetta-code.prime-conspiracy
: transitions ( n -- alist )
nprimes [ 10 mod ] map 2 clump histogram >alist natural-sort ;
: t-values ( transition -- i j count freq )
first2 [ first2 ] dip dup 10000. / ;
: print-trans ( transition -- )
t-values "%d -> %d count: %5d frequency: %5.2f%%\n" printf ;
: header ( n -- )
"First %d primes. Transitions prime %% 10 -> next-prime %% 10.\n" printf ;
: main ( -- )
1,000,000 dup header transitions [ print-trans ] each ;
MAIN: main
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#Fortran
|
Fortran
|
PROGRAM INHERIT !Last digit persistence in successive prime numbers.
USE PRIMEBAG !Inherit this also.
INTEGER MBASE,P0,NHIC !Problem bounds.
PARAMETER (MBASE = 13, P0 = 2, NHIC = 100000000) !This should do.
INTEGER N(0:MBASE - 1,0:MBASE - 1,2:MBASE) !The counts. A triangular shape would be better.
INTEGER I,B,D1,D2 !Assistants.
INTEGER P,PP !Prime, and Previous Prime.
MSG = 6 !Standard output.
WRITE (MSG,1) MBASE,P0,NHIC !Announce intent.
1 FORMAT ("Working in base 2 to ",I0," count the transitions "
1 "from the low-order digit of one prime number ",/,
2 "to the low-order digit of its successor. Starting with ",I0,
3 " and making ",I0," advances.")
IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!" !Attempt in hope.
Chug through the primes.
10 N = 0 !Clear all my counts!
P = P0 !Start with the starting prime.
DO I = 1,NHIC !Make the specified number of advances.
PP = P !Thus, remember the previous prime.
P = NEXTPRIME(P) !And obtain the current prime.
DO B = 2,MBASE !For these, step through the relevant bases.
D1 = MOD(PP,B) !Last digit of the previous prime.
D2 = MOD(P,B) !In the base of the moment.
N(D1,D2,B) = N(D1,D2,B) + 1 !Whee!
END DO !On to the next base.
END DO !And the next advance.
WRITE (MSG,11) P !Might as well announce where we got to.
11 FORMAT ("Ending with ",I0) !Hopefully, no overflow.
Cast forth the results.
20 DO B = 2,MBASE !Present results for each base.
WRITE (MSG,21) B !Announce it.
21 FORMAT (/,"For base ",I0) !Set off with a blank line.
WRITE (MSG,22) (D1, D1 = 0,B - 1) !The heading.
22 FORMAT (" Last digit ending ",I2,66I9) !Alignment to match FORMAT 23.
DO D2 = 0,B - 1 !For a given base, these are the possible ending digits of the successor.
IF (ALL(N(0:B - 1,D2,B).EQ.0)) CYCLE !No progenitor advanced to this successor digit?
WRITE (MSG,23) D2,N(0:B - 1,D2,B) !Otherwise, show the counts for the progenitor's digits.
23 FORMAT (" next prime ends",I3,":",I2,66I9) !Ah, layout.
END DO !On to the next successor digit.
END DO !On to the next base.
END !That was easy.
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#ABAP
|
ABAP
|
class ZMLA_ROSETTA definition
public
create public .
public section.
types:
enumber TYPE N LENGTH 60,
listof_enumber TYPE TABLE OF enumber .
class-methods FACTORS
importing
value(N) type ENUMBER
exporting
value(ORET) type LISTOF_ENUMBER .
protected section.
private section.
ENDCLASS.
CLASS ZMLA_ROSETTA IMPLEMENTATION.
* <SIGNATURE>---------------------------------------------------------------------------------------+
* | Static Public Method ZMLA_ROSETTA=>FACTORS
* +-------------------------------------------------------------------------------------------------+
* | [--->] N TYPE ENUMBER
* | [<---] ORET TYPE LISTOF_ENUMBER
* +--------------------------------------------------------------------------------------</SIGNATURE>
method FACTORS.
CLEAR oret.
WHILE n mod 2 = 0.
n = n / 2.
APPEND 2 to oret.
ENDWHILE.
DATA: lim type enumber,
i type enumber.
lim = sqrt( n ).
i = 3.
WHILE i <= lim.
WHILE n mod i = 0.
APPEND i to oret.
n = n / i.
lim = sqrt( n ).
ENDWHILE.
i = i + 2.
ENDWHILE.
IF n > 1.
APPEND n to oret.
ENDIF.
endmethod.
ENDCLASS.
|
http://rosettacode.org/wiki/Primality_by_trial_division
|
Primality by trial division
|
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#11l
|
11l
|
F is_prime(n)
I n < 2
R 0B
L(i) 2..Int(sqrt(n))
I n % i == 0
R 0B
R 1B
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#11l
|
11l
|
F bisect_right(a, x)
V lo = 0
V hi = a.len
L lo < hi
V mid = (lo + hi) I/ 2
I x < a[mid]
hi = mid
E
lo = mid + 1
R lo
V _cin = [0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01]
V _cout = [0.10, 0.18, 0.26, 0.32, 0.38, 0.44, 0.50, 0.54, 0.58, 0.62, 0.66, 0.70, 0.74, 0.78, 0.82, 0.86, 0.90, 0.94, 0.98, 1.00]
F pricerounder(pricein)
R :_cout[bisect_right(:_cin, pricein)]
L(i) 0..10
print(‘#.2 #.2’.format(i / 10, pricerounder(i / 10)))
|
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
|
#Ceylon
|
Ceylon
|
shared void run() {
function divisors(Integer int) =>
if(int <= 1)
then {}
else (1..int / 2).filter((Integer element) => element.divides(int));
for(i in 1..10) {
print("``i`` => ``divisors(i)``");
}
value start = 1;
value end = 20k;
value mostDivisors =
map {for(i in start..end) i->divisors(i).size}
.inverse()
.max(byKey(byIncreasing(Integer.magnitude)));
print("the number(s) with the most divisors between ``start`` and ``end`` is/are:
``mostDivisors?.item else "nothing"`` with ``mostDivisors?.key else "no"`` divisors");
}
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#D
|
D
|
void main() {
import std.stdio, std.random, std.string, std.range;
enum int nTrials = 1_000_000;
const items = "aleph beth gimel daleth he waw zayin heth".split;
const pr = [1/5., 1/6., 1/7., 1/8., 1/9., 1/10., 1/11., 1759/27720.];
double[pr.length] counts = 0.0;
foreach (immutable _; 0 .. nTrials)
counts[pr.dice]++;
writeln("Item Target prob Attained prob");
foreach (name, p, co; zip(items, pr, counts[]))
writefln("%-7s %.8f %.8f", name, p, co / nTrials);
}
|
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
|
Primes - allocate descendants to their ancestors
|
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#Phix
|
Phix
|
with javascript_semantics
constant maxSum = 99
function stringify(sequence s)
s = deep_copy(s)
for i=1 to length(s) do
s[i] = sprintf("%d",s[i])
end for
return s
end function
procedure main()
atom t0 = time()
integer p
sequence descendants = repeat({},maxSum+1),
ancestors = repeat({},maxSum+1),
primes = get_primes_le(maxSum)
for i=1 to length(primes) do
p = primes[i]
descendants[p] = append(descendants[p], p)
for s=1 to length(descendants)-p do
descendants[s+p] = deep_copy(descendants[s+p])
& sq_mul(descendants[s],p)
end for
end for
p = 4
for i=0 to length(primes) do
if i>0 then p = primes[i] end if
if length(descendants[p])!=0 then
descendants[p] = descendants[p][1..$-1]
end if
end for
integer total = 0
for s=1 to maxSum do
sequence x = sort(deep_copy(descendants[s]))
total += length(x)
for i=1 to length(x) do
atom d = x[i]
if d>maxSum then exit end if
ancestors[d] = deep_copy(ancestors[d])
&append(deep_copy(ancestors[s]),s)
end for
if s<26 or find(s,{46,74,99}) then
sequence d = ancestors[s]
integer l = length(d)
string sp = iff(l=1?" ":"s")
d = stringify(d)
printf(1,"%2d: %d Ancestor%s: [%-14s", {s, l, sp, join(d)&"]"})
d = sort(deep_copy(descendants[s]))
l = length(d)
sp = iff(l=1?" ":"s")
if l<10 then
d = stringify(d)
else
d[4..-4] = {0}
d = stringify(d)
d[4] = "..."
end if
printf(1,"%5d Descendant%s: [%s]\n", {l, sp, join(d)})
end if
end for
printf(1,"\nTotal descendants %d\n", total)
?elapsed(time()-t0) -- about 1s
?elapsed(power(3,33)/4e9) -- over 16 days
end procedure
main()
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#Common_Lisp
|
Common Lisp
|
;priority-queue's are implemented with association lists
(defun make-pq (alist)
(sort (copy-alist alist) (lambda (a b) (< (car a) (car b)))))
;
;Will change the state of pq
;
(define-modify-macro insert-pq (pair)
(lambda (pq pair) (sort-alist (cons pair pq))))
(define-modify-macro remove-pq-aux () cdr)
(defmacro remove-pq (pq)
`(let ((aux (copy-alist ,pq)))
(REMOVE-PQ-AUX ,pq)
(car aux)))
;
;Will not change the state of pq
;
(defun insert-pq-non-destructive (pair pq)
(sort-alist (cons pair pq)))
(defun remove-pq-non-destructive (pq)
(cdr pq))
;testing
(defparameter a (make-pq '((1 . "Solve RC tasks") (3 . "Clear drains") (2 . "Tax return") (5 . "Make tea"))))
(format t "~a~&" a)
(insert-pq a '(4 . "Feed cat"))
(format t "~a~&" a)
(format t "~a~&" (remove-pq a))
(format t "~a~&" a)
(format t "~a~&" (remove-pq a))
(format t "~a~&" a)
|
http://rosettacode.org/wiki/Problem_of_Apollonius
|
Problem of Apollonius
|
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the 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.
|
#J
|
J
|
require 'math/misc/amoeba'
NB.*apollonius v solves Apollonius problems
NB. y is Cx0 Cy0 R0, Cx1 Cy1 R1,: Cx2 Cy2 R2
NB. x are radius scale factors to control which circles are included
NB. in the common tangent circle. 1 to surround, _1 to exclude.
NB. returns Cxs Cys Rs
apollonius =: verb define"1 _
1 apollonius y
:
centers=. 2{."1 y
radii=. x * {:"1 y
goal=. 1e_20 NB. goal simplex volume
dist=. radii + [: +/"1&.:*: centers -"1 ] NB. distances to tangents
'soln err'=. ([: +/@:*:@, -/~@dist) f. amoeba goal centers
if. err > 10 * goal do. '' return. end. NB. no solution found
avg=. +/ % #
(, avg@dist) soln
)
|
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.
|
#Ol
|
Ol
|
(print (car *vm-args*))
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Order
|
Order
|
__FILE__
|
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.
|
#zkl
|
zkl
|
sieve:=Import("sieve.zkl",False,False,False).postponed_sieve;
primes:=Utils.Generator(sieve).walk(0d10); // first 10 primes
foreach n in (10)
{ primes[0,n].reduce('*,1):println("primorial(%d)=%d".fmt(n,_)); }
var [const] BN=Import("zklBigNum");
primes:=Utils.Generator(sieve).walk(0d1_000_000);
foreach n in ([1..6]){ n=(10).pow(n);
primes[0,n].pump(BN(1).mul)
:println("primorial(%,d)=%,d digits".fmt(n,_.numDigits));
}
|
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
|
#PARI.2FGP
|
PARI/GP
|
do(lim)={
my(prim,total,P);
lim\=1;
for(m=2,sqrtint(lim\2),
forstep(n=1+m%2,min(sqrtint(lim-m^2),m-1),2,
P=2*m*(m+n);
if(gcd(m,n)==1 && P<=lim,
prim++;
total+=lim\P
)
)
);
[prim,total]
};
do(100)
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#Maxima
|
Maxima
|
/* Basically, it's simply quit() */
block([ans], loop, if (ans: read("Really quit ? (y, n)")) = 'y
then quit()
elseif ans = 'n then (print("Nice choice!"), 'done)
else (print("I dont' understand..."), go(loop)));
|
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.
|
#.D0.9C.D0.9A-61.2F52
|
МК-61/52
|
ИП0 x=0 04 С/П ...
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#CLU
|
CLU
|
% Wilson primality test
wilson = proc (n: int) returns (bool)
if n<2 then return (false) end
fac_mod: int := 1
for i: int in int$from_to(2, n-1) do
fac_mod := fac_mod * i // n
end
return (fac_mod + 1 = n)
end wilson
% Print primes up to 100 using Wilson's theorem
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(1, 100) do
if wilson(i) then
stream$puts(po, int$unparse(i) || " ")
end
end
stream$putl(po, "")
end start_up
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#Common_Lisp
|
Common Lisp
|
(defun factorial (n)
(if (< n 2) 1 (* n (factorial (1- n)))) )
(defun primep (n)
"Primality test using Wilson's Theorem"
(unless (zerop n)
(zerop (mod (1+ (factorial (1- n))) n)) ))
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#FreeBASIC
|
FreeBASIC
|
' version 13-04-2017
' updated 09-08-2018 Using bit-sieve of odd numbers
' compile with: fbc -s console
' compile with: fbc -s console -Wc -O2 ->more than 2x faster(20.2-> 8,7s)
const max = 2040*1000*1000 ' enough for 100,000,000 primes
const max2 = (max -1) \ 2
Dim As uByte _bit(7)
Dim shared As uByte sieve(max2 \ 8 + 1)
Dim shared As ULong end_digit(1 To 9, 1 To 9)
Dim As ULong i, j, x, i1, j1, x1, c, c1
Dim As String frmt_str = " # " + Chr(26) + " # count:######## frequency:##.##%"
' bit Mask
For i = 0 To 7
_bit(i) = 1 shl i
Next
' sieving
For i = 1 To (sqr(max) -1) / 2
x = 2*i+1
If (sieve(i Shr 3) And _bit(i And 7)) = 0 Then
For j = (2*i+2)*i To max2 Step x
sieve(j Shr 3) or= _bit(j And 7)
Next
End If
Next
' count
x = 2 : c = 1
For i = 1 To max2
If (sieve(i Shr 3) And _bit(i And 7)) = 0 Then
j = (2*i+1) Mod 10
end_digit(x, j) += 1
x = j
c += 1
If c = 1000000 Or c = 100000000 Then
Print "first "; c; " primes"
c1 = c \ 100
For i1 = 1 To 9
For j1 = 1 To 9
x1 = end_digit(i1, j1)
If x1 <> 0 Then
Print Using frmt_str; i1; j1; x1; (x1 / c1)
End If
Next
Next
Print
If c = 100000000 Then Exit for
End If
End If
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#ACL2
|
ACL2
|
(include-book "arithmetic-3/top" :dir :system)
(defun prime-factors-r (n i)
(declare (xargs :mode :program))
(cond ((or (zp n) (zp (- n i)) (zp i) (< i 2) (< n 2))
(list n))
((= (mod n i) 0)
(cons i (prime-factors-r (floor n i) 2)))
(t (prime-factors-r n (1+ i)))))
(defun prime-factors (n)
(declare (xargs :mode :program))
(prime-factors-r n 2))
|
http://rosettacode.org/wiki/Primality_by_trial_division
|
Primality by trial division
|
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#360_Assembly
|
360 Assembly
|
* Primality by trial division 26/03/2017
PRIMEDIV CSECT
USING PRIMEDIV,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R10,PG pgi=0
LA R6,1 i=1
DO WHILE=(C,R6,LE,=F'50') do i=1 to 50
LR R1,R6 i
BAL R14,ISPRIME call isprime(i)
IF C,R0,EQ,=F'1' THEN if isprime(i) then
XDECO R6,XDEC edit i
MVC 0(4,R10),XDEC+8 output i
LA R10,4(R10) pgi+=4
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT PG,L'PG print buffer
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
*------- ---- ----------------------------------------
ISPRIME EQU * function isprime(n)
IF C,R1,LE,=F'1' THEN if n<=1 then
LA R0,0 return(0)
BR R14 return
ENDIF , endif
IF C,R1,EQ,=F'2' THEN if n=2 then
LA R0,1 return(1)
BR R14 return
ENDIF , endif
LR R4,R1 n
N R4,=X'00000001' n and 1
IF LTR,R4,Z,R4 THEN if mod(n,2)=0 then
LA R0,0 return(0)
BR R14 return
ENDIF , endif
LA R7,3 j=3
LA R5,9 r5=j*j
DO WHILE=(CR,R5,LE,R1) do j=3 by 2 while j*j<=n
LR R4,R1 n
SRDA R4,32 ~
DR R4,R7 /j
IF LTR,R4,Z,R4 THEN if mod(n,j)=0 then
LA R0,0 return(0)
BR R14 return
ENDIF , endif
LA R7,2(R7) j+=2
LR R5,R7 j
MR R4,R7 r5=j*j
ENDDO , enddo j
LA R0,1 return(1)
BR R14 return
*------- ---- ----------------------------------------
PG DC CL80' ' buffer
XDEC DS CL12 temp for xdeco
YREGS
END PRIMEDIV
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#Action.21
|
Action!
|
DEFINE COUNT="20"
BYTE ARRAY levels=[6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 101]
BYTE ARRAY values=[10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100]
PROC PrintValue(BYTE v)
PrintB(v/100) Put('.)
v=v MOD 100
PrintB(v/10)
v=v MOD 10
PrintB(v)
RETURN
BYTE FUNC Map(BYTE v)
BYTE i
FOR i=0 TO COUNT-1
DO
IF v<levels(i) THEN
RETURN (values(i))
FI
OD
RETURN (v)
PROC Main()
BYTE i,v
FOR i=0 TO 100
DO
v=Map(i)
PrintValue(v)
IF i MOD 5=4 THEN
PutE()
ELSE
Put(' )
FI
OD
RETURN
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#Ada
|
Ada
|
type Price is delta 0.01 digits 3 range 0.0..1.0;
function Scale (Value : Price) return Price is
X : constant array (1..19) of Price :=
( 0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51,
0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96
);
Y : constant array (1..20) of Price :=
( 0.10, 0.18, 0.26, 0.32, 0.38, 0.44, 0.50, 0.54, 0.58, 0.62,
0.66, 0.70, 0.74, 0.78, 0.82, 0.86, 0.90, 0.94, 0.98, 1.0
);
Low : Natural := X'First;
High : Natural := X'Last;
Middle : Natural;
begin
loop
Middle := (Low + High) / 2;
if Value = X (Middle) then
return Y (Middle + 1);
elsif Value < X (Middle) then
if Low = Middle then
return Y (Low);
end if;
High := Middle - 1;
else
if High = Middle then
return Y (High + 1);
end if;
Low := Middle + 1;
end if;
end loop;
end Scale;
|
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
|
#Clojure
|
Clojure
|
(ns properdivisors
(:gen-class))
(defn proper-divisors [n]
" Proper divisors of n"
(if (= n 1)
[]
(filter #(= 0 (rem n %)) (range 1 n))))
;; Property divisors of numbers 1 to 20,000 inclusive
(def data (for [n (range 1 (inc 20000))]
[n (proper-divisors n)]))
;; Find Max
(defn maximal-key [k x & xs]
" Normal max-key only finds one key that produces maximum, while this function finds them all "
(reduce (fn [ys x]
(let [c (compare (k x) (k (peek ys)))]
(cond
(pos? c) [x]
(neg? c) ys
:else (conj ys x))))
[x]
xs))
(println "n\tcnt\tPROPER DIVISORS")
(doseq [n (range 1 11)]
(let [factors (proper-divisors n)]
(println n "\t" (count factors) "\t" factors)))
(def max-data (apply maximal-key (fn [[i pd]] (count pd)) data))
(doseq [[n factors] max-data]
(println n " has " (count factors) " divisors"))
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#E
|
E
|
pragma.syntax("0.9")
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#Elixir
|
Elixir
|
defmodule Probabilistic do
@tries 1000000
@probs [aleph: 1/5,
beth: 1/6,
gimel: 1/7,
daleth: 1/8,
he: 1/9,
waw: 1/10,
zayin: 1/11,
heth: 1759/27720]
def test do
trials = for _ <- 1..@tries, do: get_choice(@probs, :rand.uniform)
IO.puts "Item Expected Actual"
fmt = " ~-8s ~.6f ~.6f~n"
Enum.each(@probs, fn {glyph,expected} ->
actual = length(for ^glyph <- trials, do: glyph) / @tries
:io.format fmt, [glyph, expected, actual]
end)
end
defp get_choice([{glyph,_}], _), do: glyph
defp get_choice([{glyph,prob}|_], ran) when ran < prob, do: glyph
defp get_choice([{_,prob}|t], ran), do: get_choice(t, ran - prob)
end
Probabilistic.test
|
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
|
Primes - allocate descendants to their ancestors
|
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#Python
|
Python
|
from __future__ import print_function
from itertools import takewhile
maxsum = 99
def get_primes(max):
if max < 2:
return []
lprimes = [2]
for x in range(3, max + 1, 2):
for p in lprimes:
if x % p == 0:
break
else:
lprimes.append(x)
return lprimes
descendants = [[] for _ in range(maxsum + 1)]
ancestors = [[] for _ in range(maxsum + 1)]
primes = get_primes(maxsum)
for p in primes:
descendants[p].append(p)
for s in range(1, len(descendants) - p):
descendants[s + p] += [p * pr for pr in descendants[s]]
for p in primes + [4]:
descendants[p].pop()
total = 0
for s in range(1, maxsum + 1):
descendants[s].sort()
for d in takewhile(lambda x: x <= maxsum, descendants[s]):
ancestors[d] = ancestors[s] + [s]
print([s], "Level:", len(ancestors[s]))
print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None")
print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None")
if len(descendants[s]):
print(descendants[s])
print()
total += len(descendants[s])
print("Total descendants", total)
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#Component_Pascal
|
Component Pascal
|
MODULE PQueues;
IMPORT StdLog,Boxes;
TYPE
Rank* = POINTER TO RECORD
p-: LONGINT; (* Priority *)
value-: Boxes.Object
END;
PQueue* = POINTER TO RECORD
a: POINTER TO ARRAY OF Rank;
size-: LONGINT;
END;
PROCEDURE NewRank*(p: LONGINT; v: Boxes.Object): Rank;
VAR
r: Rank;
BEGIN
NEW(r);r.p := p;r.value := v;
RETURN r
END NewRank;
PROCEDURE NewPQueue*(cap: LONGINT): PQueue;
VAR
pq: PQueue;
BEGIN
NEW(pq);pq.size := 0;
NEW(pq.a,cap);pq.a[0] := NewRank(MIN(INTEGER),NIL);
RETURN pq
END NewPQueue;
PROCEDURE (pq: PQueue) Push*(r:Rank), NEW;
VAR
i: LONGINT;
BEGIN
INC(pq.size);
i := pq.size;
WHILE r.p < pq.a[i DIV 2].p DO
pq.a[i] := pq.a[i DIV 2];i := i DIV 2
END;
pq.a[i] := r
END Push;
PROCEDURE (pq: PQueue) Pop*(): Rank,NEW;
VAR
r,y: Rank;
i,j: LONGINT;
ok: BOOLEAN;
BEGIN
r := pq.a[1]; (* Priority object *)
y := pq.a[pq.size]; DEC(pq.size); i := 1; ok := FALSE;
WHILE (i <= pq.size DIV 2) & ~ok DO
j := i + 1;
IF (j < pq.size) & (pq.a[i].p > pq.a[j + 1].p) THEN INC(j) END;
IF y.p > pq.a[j].p THEN pq.a[i] := pq.a[j]; i := j ELSE ok := TRUE END
END;
pq.a[i] := y;
RETURN r
END Pop;
PROCEDURE (pq: PQueue) IsEmpty*(): BOOLEAN,NEW;
BEGIN
RETURN pq.size = 0
END IsEmpty;
PROCEDURE Test*;
VAR
pq: PQueue;
r: Rank;
PROCEDURE ShowRank(r:Rank);
BEGIN
StdLog.Int(r.p);StdLog.String(":> ");StdLog.String(r.value.AsString());StdLog.Ln;
END ShowRank;
BEGIN
pq := NewPQueue(128);
pq.Push(NewRank(3,Boxes.NewString("Clear drains")));
pq.Push(NewRank(4,Boxes.NewString("Feed cat")));
pq.Push(NewRank(5,Boxes.NewString("Make tea")));
pq.Push(NewRank(1,Boxes.NewString("Solve RC tasks")));
pq.Push(NewRank(2,Boxes.NewString("Tax return")));
ShowRank(pq.Pop());
ShowRank(pq.Pop());
ShowRank(pq.Pop());
ShowRank(pq.Pop());
ShowRank(pq.Pop());
END Test;
END PQueues.
|
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.
|
#Java
|
Java
|
public class Circle
{
public double[] center;
public double radius;
public Circle(double[] center, double radius)
{
this.center = center;
this.radius = radius;
}
public String toString()
{
return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1],
radius);
}
}
public class ApolloniusSolver
{
/** Solves the Problem of Apollonius (finding a circle tangent to three other
* circles in the plane). The method uses approximately 68 heavy operations
* (multiplication, division, square-roots).
* @param c1 One of the circles in the problem
* @param c2 One of the circles in the problem
* @param c3 One of the circles in the problem
* @param s1 An indication if the solution should be externally or internally
* tangent (+1/-1) to c1
* @param s2 An indication if the solution should be externally or internally
* tangent (+1/-1) to c2
* @param s3 An indication if the solution should be externally or internally
* tangent (+1/-1) to c3
* @return The circle that is tangent to c1, c2 and c3.
*/
public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1,
int s2, int s3)
{
float x1 = c1.center[0];
float y1 = c1.center[1];
float r1 = c1.radius;
float x2 = c2.center[0];
float y2 = c2.center[1];
float r2 = c2.radius;
float x3 = c3.center[0];
float y3 = c3.center[1];
float r3 = c3.radius;
//Currently optimized for fewest multiplications. Should be optimized for
//readability
float v11 = 2*x2 - 2*x1;
float v12 = 2*y2 - 2*y1;
float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2;
float v14 = 2*s2*r2 - 2*s1*r1;
float v21 = 2*x3 - 2*x2;
float v22 = 2*y3 - 2*y2;
float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3;
float v24 = 2*s3*r3 - 2*s2*r2;
float w12 = v12/v11;
float w13 = v13/v11;
float w14 = v14/v11;
float w22 = v22/v21-w12;
float w23 = v23/v21-w13;
float w24 = v24/v21-w14;
float P = -w23/w22;
float Q = w24/w22;
float M = -w12*P-w13;
float N = w14 - w12*Q;
float a = N*N + Q*Q - 1;
float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1;
float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1;
// Find a root of a quadratic equation. This requires the circle centers not
// to be e.g. colinear
float D = b*b-4*a*c;
float rs = (-b-Math.sqrt(D))/(2*a);
float xs = M + N * rs;
float ys = P + Q * rs;
return new Circle(new double[]{xs,ys}, rs);
}
public static void main(final String[] args)
{
Circle c1 = new Circle(new double[]{0,0}, 1);
Circle c2 = new Circle(new double[]{4,0}, 1);
Circle c3 = new Circle(new double[]{2,4}, 2);
// Expects "Circle[x=2.00,y=2.10,r=3.90]" (green circle in image)
System.out.println(solveApollonius(c1,c2,c3,1,1,1));
// Expects "Circle[x=2.00,y=0.83,r=1.17]" (red circle in image)
System.out.println(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.
|
#PARI.2FGP
|
PARI/GP
|
program ScriptName;
var
prog : String;
begin
prog := ParamStr(0);
write('Program: ');
writeln(prog)
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.
|
#Pascal
|
Pascal
|
program ScriptName;
var
prog : String;
begin
prog := ParamStr(0);
write('Program: ');
writeln(prog)
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
|
#Pascal
|
Pascal
|
Program PythagoreanTriples (output);
var
total, prim, maxPeri: int64;
procedure newTri(s0, s1, s2: int64);
var
p: int64;
begin
p := s0 + s1 + s2;
if p <= maxPeri then
begin
inc(prim);
total := total + maxPeri div p;
newTri( s0 + 2*(-s1+s2), 2*( s0+s2) - s1, 2*( s0-s1+s2) + s2);
newTri( s0 + 2*( s1+s2), 2*( s0+s2) + s1, 2*( s0+s1+s2) + s2);
newTri(-s0 + 2*( s1+s2), 2*(-s0+s2) + s1, 2*(-s0+s1+s2) + s2);
end;
end;
begin
maxPeri := 100;
while maxPeri <= 1e10 do
begin
prim := 0;
total := 0;
newTri(3, 4, 5);
writeln('Up to ', maxPeri, ': ', total, ' triples, ', prim, ' primitives.');
maxPeri := maxPeri * 10;
end;
end.
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#Nanoquery
|
Nanoquery
|
exit
exit(0)
|
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.
|
#Neko
|
Neko
|
/*
Program termination, in Neko
*/
var sys_exit = $loader.loadprim("std@sys_exit", 1)
var return_code = 42
if true sys_exit(return_code)
$print("Control flow does not make it this far")
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#Cowgol
|
Cowgol
|
include "cowgol.coh";
# Wilson primality test
sub wilson(n: uint32): (out: uint8) is
out := 0;
if n >= 2 then
var facmod: uint32 := 1;
var ct := n - 1;
while ct > 0 loop
facmod := (facmod * ct) % n;
ct := ct - 1;
end loop;
if facmod + 1 == n then
out := 1;
end if;
end if;
end sub;
# Print primes up to 100 according to Wilson
var i: uint32 := 1;
while i < 100 loop
if wilson(i) == 1 then
print_i32(i);
print_char(' ');
end if;
i := i + 1;
end loop;
print_nl();
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#D
|
D
|
import std.bigint;
import std.stdio;
BigInt fact(long n) {
BigInt f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
bool isPrime(long p) {
if (p <= 1) {
return false;
}
return (fact(p - 1) + 1) % p == 0;
}
void main() {
writeln("Primes less than 100 testing by Wilson's Theorem");
foreach (i; 0 .. 101) {
if (isPrime(i)) {
write(i, ' ');
}
}
writeln;
}
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#Go
|
Go
|
package main
import (
"fmt"
"sort"
)
func sieve(limit uint64) []bool {
limit++
// True denotes composite, false denotes prime.
// We don't bother filling in the even composites.
c := make([]bool, limit)
c[0] = true
c[1] = true
p := uint64(3) // Start from 3.
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func main() {
// sieve up to the 100 millionth prime
sieved := sieve(2038074743)
transMap := make(map[int]int, 19)
i := 2 // last digit of first prime
p := int64(3 - 2) // next prime, -2 since we +=2 first
n := 1
for _, num := range [...]int{1e4, 1e6, 1e8} {
for ; n < num; n++ {
// Set p to next prime by skipping composites.
p += 2
for sieved[p] {
p += 2
}
// Count transition of i -> j.
j := int(p % 10)
transMap[i*10+j]++
i = j
}
reportTransitions(transMap, n)
}
}
func reportTransitions(transMap map[int]int, num int) {
keys := make([]int, 0, len(transMap))
for k := range transMap {
keys = append(keys, k)
}
sort.Ints(keys)
fmt.Println("First", num, "primes. Transitions prime % 10 -> next-prime % 10.")
for _, key := range keys {
count := transMap[key]
freq := float64(count) / float64(num) * 100
fmt.Printf("%d -> %d count: %7d", key/10, key%10, count)
fmt.Printf(" frequency: %4.2f%%\n", freq)
}
fmt.Println()
}
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Ada
|
Ada
|
generic
type Number is private;
Zero : Number;
One : Number;
Two : Number;
with function "+" (X, Y : Number) return Number is <>;
with function "*" (X, Y : Number) return Number is <>;
with function "/" (X, Y : Number) return Number is <>;
with function "mod" (X, Y : Number) return Number is <>;
with function ">" (X, Y : Number) return Boolean is <>;
package Prime_Numbers is
type Number_List is array (Positive range <>) of Number;
function Decompose (N : Number) return Number_List;
function Is_Prime (N : Number) return Boolean;
end Prime_Numbers;
|
http://rosettacode.org/wiki/Polyspiral
|
Polyspiral
|
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
|
#Action.21
|
Action!
|
INCLUDE "H6:REALMATH.ACT"
INT ARRAY SinTab=[
0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83
88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
147 150 154 158 161 165 168 171 175 178 181 184 187 190
193 196 199 202 204 207 210 212 215 217 219 222 224 226
228 230 232 234 236 237 239 241 242 243 245 246 247 248
249 250 251 252 253 254 254 255 255 255 256 256 256 256]
INT FUNC Sin(INT a)
WHILE a<0 DO a==+360 OD
WHILE a>360 DO a==-360 OD
IF a<=90 THEN
RETURN (SinTab(a))
ELSEIF a<=180 THEN
RETURN (SinTab(180-a))
ELSEIF a<=270 THEN
RETURN (-SinTab(a-180))
ELSE
RETURN (-SinTab(360-a))
FI
RETURN (0)
INT FUNC Cos(INT a)
RETURN (Sin(a-90))
PROC DrawSpiral(INT x0,y0)
INT i,angle,x,y,tmp
REAL rx,ry,len,dlen,r1,r2,r3,r256
IntToReal(x0,rx)
IntToReal(y0,ry)
ValR("1.9",len)
ValR("1.14",dlen)
IntToReal(256,r256)
angle=0
Plot(x0,y0)
FOR i=1 TO 150
DO
tmp=Cos(angle)
IntToRealForNeg(tmp,r1)
RealDiv(r1,r256,r2)
RealMult(r2,len,r1)
RealAdd(rx,r1,r2)
RealAssign(r2,rx)
tmp=Sin(angle)
IntToRealForNeg(tmp,r1)
RealDiv(r1,r256,r2)
RealMult(r2,len,r1)
RealAdd(ry,r1,r2)
RealAssign(r2,ry)
x=RealToInt(rx)
y=RealToInt(ry)
DrawTo(x,y)
RealAdd(len,dlen,r1)
RealAssign(r1,len)
angle==+123
IF angle>360 THEN
angle==-360
FI
OD
RETURN
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
Graphics(8+16)
Color=1
COLOR1=$0C
COLOR2=$02
DrawSpiral(160,96)
DO UNTIL CH#$FF OD
CH=$FF
RETURN
|
http://rosettacode.org/wiki/Primality_by_trial_division
|
Primality by trial division
|
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#68000_Assembly
|
68000 Assembly
|
isPrime:
; REG USAGE:
; D0 = input (unsigned 32-bit integer)
; D1 = temp storage for D0
; D2 = candidates for possible factors
; D3 = temp storage for quotient/remainder
; D4 = total count of proper divisors.
MOVEM.L D1-D4,-(SP) ;push data regs except D0
MOVE.L #0,D1
MOVEM.L D1,D2-D4 ;clear regs D1 thru D4
CMP.L #0,D0
BEQ notPrime
CMP.L #1,D0
BEQ notPrime
CMP.L #2,D0
BEQ wasPrime
MOVE.L D0,D1 ;D1 will be used for temp storage.
AND.L #1,D1 ;is D1 even?
BEQ notPrime ;if so, it's not prime!
MOVE.L D0,D1 ;restore D1
MOVE.L #3,D2 ;start with 3
computeFactors:
DIVU D2,D1 ;remainder is in top 2 bytes, quotient in bottom 2.
MOVE.L D1,D3 ;temporarily store into D3 to check the remainder
SWAP D3 ;swap the high and low words of D3. Now bottom 2 bytes contain remainder.
CMP.W #0,D3 ;is the bottom word equal to 0?
BNE D2_Wasnt_A_Divisor ;if not, D2 was not a factor of D1.
ADDQ.L #1,D4 ;increment the count of proper divisors.
CMP.L #2,D4 ;is D4 two or greater?
BCC notPrime ;if so, it's not prime! (Ends early. We'll need to check again if we made it to the end.)
D2_Wasnt_A_Divisor:
MOVE.L D0,D1 ;restore D1.
ADDQ.L #1,D2 ;increment D2
CMP.L D2,D1 ;is D2 now greater than D1?
BLS computeFactors ;if not, loop again
CMP.L #1,D4 ;was there only one factor?
BEQ wasPrime ;if so, D0 was prime.
notPrime:
MOVE.L #0,D0 ;return false
MOVEM.L (SP)+,D1-D4 ;pop D1-D4
RTS
wasPrime:
MOVE.L #1,D0 ;return true
MOVEM.L (SP)+,D1-D4 ;pop D1-D4
RTS
;end of program
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#ALGOL_68
|
ALGOL 68
|
main:
(
# Just get a random price between 0 and 1 #
# srand(time(NIL)); #
REAL price := random;
REAL tops := 0.06;
REAL std val := 0.10;
# Conditionals are a little odd here "(price-0.001 < tops AND
price+0.001 > tops)" is to check if they are equal. Stupid
C floats, right? :) #
WHILE ( price>tops OR (price-0.001 < tops AND price+0.001 > tops) ) AND tops<=1.01
DO
tops+:=0.05;
IF std val < 0.26 THEN
std val +:= 0.08
ELIF std val < 0.50 THEN
std val +:= 0.06
ELSE
std val +:= 0.04
FI;
IF std val > 0.98 THEN
std val := 1.0
FI
OD;
printf(($"Value : "z.2dl,"Converted to standard : "z.2dl$, price, std val))
)
|
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
|
#Common_Lisp
|
Common Lisp
|
(defun proper-divisors-recursive (product &optional (results '(1)))
"(int,list)->list::Function to find all proper divisors of a +ve integer."
(defun smallest-divisor (x)
"int->int::Find the smallest divisor of an integer > 1."
(if (evenp x) 2
(do ((lim (truncate (sqrt x)))
(sd 3 (+ sd 2)))
((or (integerp (/ x sd)) (> sd lim)) (if (> sd lim) x sd)))))
(defun pd-rec (fac)
"(int,int)->nil::Recursive function to find proper divisors of a +ve integer"
(when (not (member fac results))
(push fac results)
(let ((hifac (/ fac (smallest-divisor fac))))
(pd-rec hifac)
(pd-rec (/ product hifac)))))
(pd-rec product)
(butlast (sort (copy-list results) #'<)))
(defun task (method &optional (n 1) (most-pds '(0)))
(dotimes (i 19999)
(let ((npds (length (funcall method (incf n))))
(hiest (car most-pds)))
(when (>= npds hiest)
(if (> npds hiest)
(setf most-pds (list npds (list n)))
(setf most-pds (list npds (cons n (second most-pds))))))))
most-pds)
(defun main ()
(format t "Task 1:Proper Divisors of [1,10]:~%")
(dotimes (i 10) (format t "~A:~A~%" (1+ i) (proper-divisors-recursive (1+ i))))
(format t "Task 2:Count & list of numbers <=20,000 with the most Proper Divisors:~%~A~%"
(task #'proper-divisors-recursive)))
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#Erlang
|
Erlang
|
-module(probabilistic_choice).
-export([test/0]).
-define(TRIES, 1000000).
test() ->
Probs =
[{aleph,1/5},
{beth,1/6},
{gimel,1/7},
{daleth,1/8},
{he,1/9},
{waw,1/10},
{zayin,1/11},
{heth,1759/27720}],
random:seed(now()),
Trials =
[get_choice(Probs,random:uniform()) || _ <- lists:seq(1,?TRIES)],
[{Glyph,Expected,(length([Glyph || Glyph_ <- Trials, Glyph_ == Glyph])/?TRIES)}
|| {Glyph,Expected} <- Probs].
get_choice([{Glyph,_}],_) ->
Glyph;
get_choice([{Glyph,Prob}|T],Ran) ->
case (Ran < Prob) of
true ->
Glyph;
false ->
get_choice(T,Ran - Prob)
end.
|
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
|
Primes - allocate descendants to their ancestors
|
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#Racket
|
Racket
|
#lang racket
(define-syntax-rule (define/mem (name args ...) body ...)
(begin
(define cache (make-hash))
(define (name args ...)
(hash-ref! cache (list args ...) (lambda () body ...)))))
(define (take-last x n)
(drop x (- (length x) n)))
(define (borders x)
(if (> (length x) 5)
(append (take x 2) '(...) (take-last x 2))
x))
(define (add-tail list x)
(reverse (cons x (reverse list))))
|
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
|
Primes - allocate descendants to their ancestors
|
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'.
The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance.
This solution could be compared to the solution that would use the decomposition into primes for all the numbers between 1 and 333.
The problem is to list, for a delimited set of ancestors (from 1 to 99) :
- the total of their own ancestors (LEVEL),
- their own ancestors (ANCESTORS),
- the total of the direct descendants (DESCENDANTS),
- all the direct descendants.
You only have to consider the prime factors < 100.
A grand total of the descendants has to be printed at the end of the list.
The task should be accomplished in a reasonable time-frame.
Example :
46 = 2*23 --> 2+23 = 25, is the parent of 46.
25 = 5*5 --> 5+5 = 10, is the parent of 25.
10 = 2*5 --> 2+5 = 7, is the parent of 10.
7 is a prime factor and, as such, has no parent.
46 has 3 ancestors (7, 10 and 25).
46 has 557 descendants.
The list layout and the output for Parent [46] :
[46] Level: 3
Ancestors: 7, 10, 25
Descendants: 557
129, 205, 246, 493, 518, 529, 740, 806, 888, 999, 1364, 1508, 1748, 2552, 2871, 3128, 3255, 3472, 3519, 3875, 3906, 4263, 4650, 4960, 5075, 5415, 5580, 5776, 5952, 6090, 6279, 6496, 6498, 6696, 6783, 7250, 7308, 7475, 7533, 8075, 8151, 8619, 8700, 8855, 8970, 9280, 9568, 9690, 10115, 10336, 10440, 10626, 10764, 11136, 11495, 11628, 11745, 12103, 12138, 12155, 12528, 12650, 13794, 14094, 14399, 14450, 14586, 15180, 15379, 15778, 16192, 17290, 17303, 17340, 18216, 18496, 20482, 20493, 20570, 20748, 20808, 21658, 21970, 22540, 23409, 24684, 24700, 26026, 26364, 27048, 29260, 29282, 29640, 30429, 30940, 31616, 32200, 33345, 35112, 35568, 36225, 36652, 37128, 37180, 38640, 39501, 40014, 41216, 41769, 41800, 43125, 43470, 44044, 44200, 44616, 46000, 46368, 47025, 49725, 50160, 50193, 51750, 52136, 52164, 52360, 53040, 53504, 55200, 56430, 56576, 58653, 58880, 58905, 59670, 60192, 62100, 62832, 62920, 63648, 66240, 66248, 67716, 69825, 70125, 70656, 70686, 70785, 71604, 74480, 74520, 74529, 74536, 74800, 75504, 79488, 83125, 83790, 83835, 83853, 84150, 84942, 87465, 88725, 89376, 89424, 89760, 93296, 94640, 95744, 99750, 99825, 100548, 100602, 100980, 104125, 104958, 105105, 105625, 106400, 106470, 106480, 107712, 112112, 113568, 118750, 119700, 119790, 121176, 124509, 124950, 125125, 126126, 126750, 127680, 127764, 127776, 133280, 135200, 136192, 136323, 142500, 143640, 143748, 148225, 148750, 149940, 150150, 152000, 152100, 153216, 156065, 159936, 160160, 161595, 162240, 171000, 172368, 173056, 177870, 178500, 178750, 179928, 180180, 182400, 182520, 184877, 187278, 189728, 190400, 192192, 192375, 193914, 194560, 194688, 202419, 205200, 205335, 211750, 212500, 213444, 214200, 214500, 216216, 218880, 219024, 222950, 228480, 228800, 230850, 233472, 240975, 243243, 243712, 246240, 246402, 254100, 255000, 257040, 257400, 262656, 264110, 267540, 271040, 272000, 274176, 274560, 277020, 285376, 286875, 289170, 289575, 292864, 295488, 302500, 304920, 306000, 308448, 308880, 316932, 318500, 321048, 325248, 326400, 329472, 332424, 343035, 344250, 347004, 347490, 348160, 361179, 363000, 365904, 367200, 370656, 373977, 377300, 382200, 387200, 391680, 407680, 408375, 411642, 413100, 416988, 417792, 429975, 435600, 440640, 452760, 455000, 458640, 464640, 470016, 470596, 482944, 489216, 490050, 495616, 495720, 509355, 511875, 515970, 522720, 528768, 539000, 543312, 546000, 550368, 557568, 557685, 582400, 588060, 594864, 606375, 609375, 611226, 614250, 619164, 627264, 646800, 650000, 655200, 669222, 672280, 689920, 698880, 705672, 721875, 727650, 731250, 737100, 745472, 756315, 770000, 776160, 780000, 786240, 793881, 806736, 827904, 832000, 838656, 859375, 866250, 873180, 877500, 884520, 900375, 907578, 924000, 931392, 936000, 943488, 960400, 985600, 995085, 998400, 1031250, 1039500, 1047816, 1053000, 1061424, 1064960, 1071875, 1080450, 1100000, 1108800, 1123200, 1152480, 1178793, 1182720, 1184625, 1194102, 1198080, 1229312, 1237500, 1247400, 1261568, 1263600, 1277952, 1286250, 1296540, 1320000, 1330560, 1347840, 1372000, 1382976, 1403325, 1408000, 1419264, 1421550, 1437696, 1485000, 1496880, 1516320, 1531250, 1543500, 1555848, 1584000, 1596672, 1617408, 1646400, 1670625, 1683990, 1689600, 1705860, 1750329, 1756160, 1782000, 1796256, 1802240, 1819584, 1837500, 1852200, 1900800, 1960000, 1975680, 2004750, 2020788, 2027520, 2047032, 2083725, 2107392, 2138400, 2162688, 2187500, 2205000, 2222640, 2280960, 2302911, 2352000, 2370816, 2405700, 2433024, 2480625, 2500470, 2508800, 2566080, 2625000, 2646000, 2667168, 2737152, 2800000, 2822400, 2886840, 2953125, 2976750, 3000564, 3010560, 3079296, 3125000, 3150000, 3175200, 3211264, 3247695, 3360000, 3386880, 3464208, 3515625, 3543750, 3572100, 3584000, 3612672, 3750000, 3780000, 3810240, 3897234, 4000000, 4032000, 4064256, 4218750, 4252500, 4286520, 4300800, 4500000, 4536000, 4572288, 4587520, 4800000, 4822335, 4838400, 5062500, 5103000, 5120000, 5143824, 5160960, 5400000, 5443200, 5505024, 5740875, 5760000, 5786802, 5806080, 6075000, 6123600, 6144000, 6193152, 6480000, 6531840, 6553600, 6834375, 6889050, 6912000, 6967296, 7290000, 7348320, 7372800, 7776000, 7838208, 7864320, 8201250, 8266860, 8294400, 8388608, 8748000, 8817984, 8847360, 9331200, 9437184, 9841500, 9920232, 9953280, 10497600, 10616832, 11160261, 11197440, 11809800, 11943936, 12597120, 13286025, 13436928, 14171760, 15116544, 15943230, 17006112, 19131876
Some figures :
The biggest descendant number : 3^33 = 5.559.060.566.555.523 (parent 99)
Total Descendants 546.986
|
#Raku
|
Raku
|
my $max = 99;
my @primes = (2 .. $max).grep: *.is-prime;
my %tree;
(1..$max).map: {
%tree{$_}<ancestor> = ();
%tree{$_}<descendants> = {};
};
sub allocate ($n, $i = 0, $sum = 0, $prod = 1) {
return if $n < 4;
for @primes.kv -> $k, $p {
next if $k < $i;
if ($sum + $p) <= $n {
allocate($n, $k, $sum + $p, $prod * $p);
} else {
last if $sum == $prod;
%tree{$sum}<descendants>{$prod} = True;
last if $prod > $max;
%tree{$prod}<ancestor> = %tree{$sum}<ancestor> (|) $sum;
last;
}
}
}
# abbreviate long lists to first and last 5 elements
sub abbrev (@d) { @d < 11 ?? @d !! ( @d.head(5), '...', @d.tail(5) ) }
my @print = flat 1 .. 15, 46, 74, $max;
(1 .. $max).map: -> $term {
allocate($term);
if $term == any( @print ) # print some representative lines
{
my $dn = +%tree{$term}<descendants> // 0;
my $dl = abbrev(%tree{$term}<descendants>.keys.sort( +*) // ());
printf "%2d, %2d Ancestors: %-14s %5d Descendants: %s\n",
$term, %tree{$term}<ancestor>,
"[{ %tree{$term}<ancestor>.keys.sort: +* }],", $dn, "[$dl]";
}
}
say "\nTotal descendants: ",
sum (1..$max).map({ +%tree{$_}<descendants> });
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#D
|
D
|
import std.stdio, std.container, std.array, std.typecons;
void main() {
alias tuple T;
auto heap = heapify([T(3, "Clear drains"),
T(4, "Feed cat"),
T(5, "Make tea"),
T(1, "Solve RC tasks"),
T(2, "Tax return")]);
while (!heap.empty) {
writeln(heap.front);
heap.removeFront();
}
}
|
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.
|
#jq
|
jq
|
def circle:
{"x": .[0], "y": .[1], "r": .[2]};
# Find the interior or exterior Apollonius circle of three circles:
# ap(circle, circle, circle, boolean)
# Specify s as true for interior; false for exterior
def ap(c1; c2; c3; s):
def sign: if s then -. else . end;
(c1.x * c1.x) as $x1sq
| (c1.y * c1.y) as $y1sq
| (c1.r * c1.r) as $r1sq
| (c2.x * c2.x) as $x2sq
| (c2.y * c2.y) as $y2sq
| (c2.r * c2.r) as $r2sq
| (c3.x * c3.x) as $x3sq
| (c3.y * c3.y) as $y3sq
| (c3.r * c3.r) as $r3sq
| (2 * (c2.x - c1.x)) as $v11
| (2 * (c2.y - c1.y)) as $v12
| ($x1sq - $x2sq + $y1sq - $y2sq - $r1sq + $r2sq) as $v13
| (2 * (c2.r - c1.r) | sign) as $v14
| (2 * (c3.x - c2.x)) as $v21
| (2 * (c3.y - c2.y)) as $v22
| ($x2sq - $x3sq + $y2sq - $y3sq - $r2sq + $r3sq) as $v23
| ( 2 * c3.r - c2.r | sign) as $v24
| ($v12 / $v11) as $w12
| ($v13 / $v11) as $w13
| ($v14 / $v11) as $w14
| (($v22 / $v21) - $w12) as $w22
| (($v23 / $v21) - $w13) as $w23
| (($v24 / $v21) - $w14) as $w24
| (-$w23 / $w22) as $p
| ( $w24 / $w22) as $q
| ((-$w12*$p) - $w13) as $m
| ( $w14 - ($w12*$q)) as $n
| ( $n*$n + $q*$q - 1 ) as $a
| (2 * (($m*$n - $n*c1.x + $p*$q - $q*c1.y) + (c1.r|sign))) as $b
| ($x1sq + $m*$m - 2*$m*c1.x + $p*$p + $y1sq - 2*$p*c1.y - $r1sq) as $c
| ( $b*$b - 4*$a*$c ) as $d # discriminant
| (( -$b - (($d|sqrt))) / (2 * $a)) as $rs # root
| [$m + ($n*$rs), $p + ($q*$rs), $rs]
| circle
;
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Perl
|
Perl
|
#!/usr/bin/env perl
use strict;
use warnings;
sub main {
my $program = $0;
print "Program: $program\n";
}
unless(caller) { 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.
|
#Phix
|
Phix
|
with javascript_semantics
string cl2 = command_line()[2]
printf(1,"%s\n",cl2) -- full path
printf(1,"%s\n",get_file_name(cl2)) -- eg test.exw or test.exe or test.htm
printf(1,"%s\n",get_file_base(cl2)) -- eg test
|
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
|
#Perl
|
Perl
|
sub gcd {
my ($n, $m) = @_;
while($n){
my $t = $n;
$n = $m % $n;
$m = $t;
}
return $m;
}
sub tripel {
my $pmax = shift;
my $prim = 0;
my $count = 0;
my $nmax = sqrt($pmax)/2;
for( my $n=1; $n<=$nmax; $n++ ) {
for( my $m=$n+1; (my $p = 2*$m*($m+$n)) <= $pmax; $m+=2 ) {
next unless 1==gcd($m,$n);
$prim++;
$count += int $pmax/$p;
}
}
printf "Max. perimeter: %d, Total: %d, Primitive: %d\n", $pmax, $count, $prim;
}
tripel 10**$_ for 1..8;
|
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.
|
#Nemerle
|
Nemerle
|
using System.Environment
...
when (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.
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref symbols nobinary
extremePrejudice = (1 == 1)
if extremePrejudice then do
exit extremePrejudice
end
return
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#EDSAC_order_code
|
EDSAC order code
|
[Primes by Wilson's Theoem, for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
T51K P64F [address for G parameter: low-level subroutines]
T47K P130F [M parameter: main routine + high-level subroutine]
[======== M parameter: Main routine + high-level subroutine ============]
E25K TM GK
[Editable range of integers to be tested for primality.]
[Integers are stored right-justified, so e.g. 1000 is P500F.]
[0] P500F [lowest]
[1] P550F [highest]
[Constants used with the M parameter]
[2] PD [17-bit 1; also serves as letter P]
[3] K2048F [set letters mode]
[4] #F [set figures mode]
[5] RF [letter R]
[6] IF [letter I]
[7] MF [letter M in letters mode, dot in figures mode]
[8] @F [carriage return]
[9] &F [line feed]
[10] !F [space character]
[11] K4096F [null character]
[Subroutine for testing whether 17-bit integer n is a prime,
using Wilson's Theorem with short cut.]
[Input: n in 6F.]
[Output: 0F holds 0 if n is prime, negative if n is not prime.]
[12] A3F T69@ [plant return link as usual ]
A6F S2F G68@ [acc := n - 2, exit if n < 2]
A2@ T72@ [r := n - 1, clear acc]
T7F [extend n to 35 bits in 6D]
A2@ U71@ U70@ [f := 1; m := 1]
A2F T73@ [m2inc := 3]
[25] A72@ S73@ G44@ [if r < m2inc jump to part 2]
T72@ [dec( r, m2inc)]
A70@ A2@ T70@ [inc( m)]
H71@ V70@ [acc := f*m]
[Note that f and m are held as f/2^16 and m/2^16, so their product is (f*m)/2^32.
We want to store the product as (f*m)/2^34, hence need to shift 2 right]
R1F T4D [shift product and pass to modulo subroutine]
[36] A36@ G38G [call modulo subroutine]
A4F T71@ [f := product modulo n]
A73@ A2F T73@ [inc( m2inc, 2)]
E25@ [always loop back]
[Part 2: Euclid's algorithm]
[44] TF [clear acc]
A6FT74@ [h := n]
[47] S71@ E63@ [if f = 0 then jump to test HCF]
TF [clear acc]
A71@ T6F T7F [f to 6F and extend to 35 bits in 6D]
A74@ T4F T5F [h to 4F and extend to 35 bits in 4D]
[56] A56@ G38G [call subroutine, 4F := h modulo f]
A71@ T74@ [h := f]
A4F T71@ [f := (old h) modulo f]
E47@ [always loop back]
[Here with acc = 0. Test for h = 1]
[63] A74@ S2@ [acc := h - 1]
G68@ [return false if h = 0]
TF SF [acc := 1 - h]
[68] TF [return result in 0F]
[69] ZF [(planted) jump back to caller]
[Variables with names as in Pascal program]
[70] PF [m]
[71] PF [f]
[72] PF [r]
[73] PF [m2inc]
[74] PF [h]
[Subroutine for finding and printing primes between the passed-in limits]
[Input: 4F = minimum value, 5F = maximum value]
[Output: None. 4F and 5F are not preserved.]
[75] A3F T128@ [plant return link as usual]
[Set letters mode, write 'PRIMES ', set figures mode]
O3@ O2@ O5@ O6@ O7@ O124@ O104@ O10@ O4@
A5F T130@ [store maximum value locally]
A4F U129@ [store minimum value locally]
TF [pass minimum value to print subroutine]
A11@ T1F [pass null for leading zeros]
[93] A93@ GG [call print subroutine]
O7@ O7@ [print 2 dots for range]
A130 @TF [pass maximum value to print routine]
[99] A99@ GG [call print subroutine]
O8@ O9@ [print CRLF]
[103] A130@ [load n_max]
[104] S129@ [subtract n; also serves as letter S]
G125@ [exit if n > n_max]
TF [clear acc]
A129 @T6F [pass current n to prime-testing subroutine]
[109] A109@ G12M [call prime-testing subroutine]
AF G120@ [load result, skip printing if n isn't prime]
O10@ [print space]
A129 @TF [pass n to print subroutine]
A11@ T1F [pass null for leading zeros]
[118] A118@ GG [call print subroutine]
[120] TF [clear acc]
A129@ A2@ T129@ [inc(n)]
[124] E103@ [always loop back; also serves as letter E]
[125] O8@ O9@ [print CRLF]
TF [clear acc before return (EDSAC convention)]
[128] ZF [(planted) jump back to caller]
[Variables]
[129] PF [n]
[130] PF [n_max]
[Enter with acc = 0]
[131] A@ T4F [pass lower limit to prime-finding subroutine]
A1@ T5F [pass upper limit to prime-finding subroutine]
[135] A135@ G75M [call prime-finding subroutine]
O11@ [print null to flush printer buffer]
ZF [stop]
[==================== G parameter: Low-level subroutines ====================]
E25K TG
[Subroutine to print non-negative 17-bit integer. Always prints 5 chars.]
[Caller specifies character for leading 0 (typically 0, space or null).]
[Parameters: 0F = integer to be printed (not preserved)]
[1F = character for leading zero (preserved)]
[Workspace: 4F..7F, 38 locations]
[0] GKA3FT34@A1FT7FS35@T6FT4#FAFT4FH36@V4FRDA4#FR1024FH37@E23@O7FA2F
T6FT5FV4#FYFL8FT4#FA5FL1024FUFA6FG16@OFTFT7FA6FG17@ZFP4FZ219DTF
[Subroutine to find X modulo M, where X and M are 35-bit integers.]
[Input: X >= 0 in 4D, M > 0 in 6D.]
[Output: X modulo M in 4D, M preserved in 6D. Does not return the quotient.]
[Workspace: 0F. 27 locations.]
[38] GKA3FT26@A6DT8DA4DRDS8DG12@TFA8DLDE3@TF
A4DS8DG17@T4DTFA6DS8DE26@TFA8DRDT8DE13@EF
[======== M parameter again ============]
E25K TM GK
E131Z [define entry point]
PF [acc = 0 on entry]
[end]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.