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/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Checkpoint is
package FR renames Ada.Numerics.Float_Random;
No_Of_Cubicles: constant Positive := 3;
-- That many workers can work in parallel
No_Of_Workers: constant Positive := 6;
-- That many workers are potentially available
-- some will join the team when others quit the job
type Activity_Array is array(Character) of Boolean;
-- we want to know who is currently working
protected Checkpoint is
entry Deliver;
entry Join (Label : out Character; Tolerance: out Float);
entry Leave(Label : in Character);
private
Signaling : Boolean := False;
Ready_Count : Natural := 0;
Worker_Count : Natural := 0;
Unused_Label : Character := 'A';
Likelyhood_To_Quit: Float := 1.0;
Active : Activity_Array := (others => false);
entry Lodge;
end Checkpoint;
protected body Checkpoint is
entry Join (Label : out Character; Tolerance: out Float)
when not Signaling and Worker_Count < No_Of_Cubicles is
begin
Label := Unused_Label;
Active(Label):= True;
Unused_Label := Character'Succ (Unused_Label);
Worker_Count := Worker_Count + 1;
Likelyhood_To_Quit := Likelyhood_To_Quit / 2.0;
Tolerance := Likelyhood_To_Quit;
end Join;
entry Leave(Label: in Character) when not Signaling is
begin
Worker_Count := Worker_Count - 1;
Active(Label) := False;
end Leave;
entry Deliver when not Signaling is
begin
Ready_Count := Ready_Count + 1;
requeue Lodge;
end Deliver;
entry Lodge when Ready_Count = Worker_Count or Signaling is
begin
if Ready_Count = Worker_Count then
Put("---Sync Point [");
for C in Character loop
if Active(C) then
Put(C);
end if;
end loop;
Put_Line("]---");
end if;
Ready_Count := Ready_Count - 1;
Signaling := Ready_Count /= 0;
end Lodge;
end Checkpoint;
task type Worker;
task body Worker is
Dice : FR.Generator;
Label : Character;
Tolerance : Float;
Shift_End : Time := Clock + 2.0;
-- Trade unions are hard!
begin
FR.Reset (Dice);
Checkpoint.Join (Label, Tolerance);
Put_Line(Label & " joins the team");
loop
Put_Line (Label & " is working");
delay Duration (FR.Random (Dice) * 0.500);
Put_Line (Label & " is ready");
Checkpoint.Deliver;
if FR.Random(Dice) < Tolerance then
Put_Line(Label & " leaves the team");
exit;
elsif Clock >= Shift_End then
Put_Line(Label & " ends shift");
exit;
end if;
end loop;
Checkpoint.Leave(Label);
end Worker;
Set : array (1..No_Of_Workers) of Worker;
begin
null; -- Nothing to do here
end Test_Checkpoint;
|
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #EchoLisp | EchoLisp |
(define my-collection ' ( 🌱 ☀️ ☔️ ))
(set! my-collection (cons '🎥 my-collection))
(set! my-collection (cons '🐧 my-collection))
my-collection
→ (🐧 🎥 🌱 ☀️ ☔️)
;; save it
(local-put 'my-collection)
→ my-collection
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Lambdatalk | Lambdatalk |
{def comb
{def comb.r
{lambda {:m :n :N}
{if {= :m 0}
then {A.new {A.new}}
else {if {= :n :N}
then {A.new}
else {A.concat
{A.map {{lambda {:n :rest} {A.addfirst! :n :rest}} :n}
{comb.r {- :m 1} {+ :n 1} :N}}
{comb.r :m {+ :n 1} :N}}}}}}
{lambda {:m :n}
{comb.r :m 0 :n}}}
-> comb
{comb 3 5}
-> [[0,1,2],[0,1,3],[0,1,4],[0,2,3],[0,2,4],[0,3,4],
[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #PowerShell | PowerShell | # standard if
if (condition) {
# ...
}
# if-then-else
if (condition) {
# ...
} else {
# ...
}
# if-then-elseif-else
if (condition) {
# ...
} elseif (condition2) {
# ...
} else {
# ...
} |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Z80_Assembly | Z80 Assembly | ld hl,&8000 ;This is a comment |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #zig | zig | // This is a normal comment in Zig
/// This is a documentation comment in Zig (for the following line) |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #zkl | zkl | x=1; // comment ala C++
x=2; # ala scripts
/* ala C, these comments are parsed (also ala C) */
/* can /* be */ nested */
#if 0
also ala C (and parsed)
#endif
#<<<#
"here" comment, unparsed
#<<<# |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #Ada | Ada | with Ada.Text_IO, Mod_Inv;
procedure Chin_Rema is
N: array(Positive range <>) of Positive := (3, 5, 7);
A: array(Positive range <>) of Positive := (2, 3, 2);
Tmp: Positive;
Prod: Positive := 1;
Sum: Natural := 0;
begin
for I in N'Range loop
Prod := Prod * N(I);
end loop;
for I in A'Range loop
Tmp := Prod / N(I);
Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp;
end loop;
Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod));
end Chin_Rema; |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #J | J | a=: {{)v
if.3=y do.1729 return.end.
m=. z=. 2^y-4
f=. 6 12,9*2^}.i.y-1
while.do.
uf=.1+f*m
if.*/1 p: uf do. */x:uf return.end.
m=.m+z
end.
}} |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #Java | Java |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class ChernicksCarmichaelNumbers {
public static void main(String[] args) {
for ( long n = 3 ; n < 10 ; n++ ) {
long m = 0;
boolean foundComposite = true;
List<Long> factors = null;
while ( foundComposite ) {
m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);
factors = U(n, m);
foundComposite = false;
for ( long factor : factors ) {
if ( ! isPrime(factor) ) {
foundComposite = true;
break;
}
}
}
System.out.printf("U(%d, %d) = %s = %s %n", n, m, display(factors), multiply(factors));
}
}
private static String display(List<Long> factors) {
return factors.toString().replace("[", "").replace("]", "").replaceAll(", ", " * ");
}
private static BigInteger multiply(List<Long> factors) {
BigInteger result = BigInteger.ONE;
for ( long factor : factors ) {
result = result.multiply(BigInteger.valueOf(factor));
}
return result;
}
private static List<Long> U(long n, long m) {
List<Long> factors = new ArrayList<>();
factors.add(6*m + 1);
factors.add(12*m + 1);
for ( int i = 1 ; i <= n-2 ; i++ ) {
factors.add(((long)Math.pow(2, i)) * 9 * m + 1);
}
return factors;
}
private static final int MAX = 100_000;
private static final boolean[] primes = new boolean[MAX];
private static boolean SIEVE_COMPLETE = false;
private static final boolean isPrimeTrivial(long test) {
if ( ! SIEVE_COMPLETE ) {
sieve();
SIEVE_COMPLETE = true;
}
return primes[(int) test];
}
private static final void sieve() {
// primes
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
// See http://primes.utm.edu/glossary/page.php?sort=StrongPRP
public static final boolean isPrime(long testValue) {
if ( testValue == 2 ) return true;
if ( testValue % 2 == 0 ) return false;
if ( testValue <= MAX ) return isPrimeTrivial(testValue);
long d = testValue-1;
int s = 0;
while ( d % 2 == 0 ) {
s += 1;
d /= 2;
}
if ( testValue < 1373565L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 4759123141L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(7, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 10000000000000000L ) {
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
if ( ! aSrp(24251, s, d, testValue) ) {
return false;
}
return true;
}
// Try 5 "random" primes
if ( ! aSrp(37, s, d, testValue) ) {
return false;
}
if ( ! aSrp(47, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
if ( ! aSrp(73, s, d, testValue) ) {
return false;
}
if ( ! aSrp(83, s, d, testValue) ) {
return false;
}
//throw new RuntimeException("ERROR isPrime: Value too large = "+testValue);
return true;
}
private static final boolean aSrp(int a, int s, long d, long n) {
long modPow = modPow(a, d, n);
//System.out.println("a = "+a+", s = "+s+", d = "+d+", n = "+n+", modpow = "+modPow);
if ( modPow == 1 ) {
return true;
}
int twoExpR = 1;
for ( int r = 0 ; r < s ; r++ ) {
if ( modPow(modPow, twoExpR, n) == n-1 ) {
return true;
}
twoExpR *= 2;
}
return false;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long modPow(long base, long exponent, long modulus) {
long result = 1;
while ( exponent > 0 ) {
if ( exponent % 2 == 1 ) {
if ( result > SQRT || base > SQRT ) {
result = multiply(result, base, modulus);
}
else {
result = (result * base) % modulus;
}
}
exponent >>= 1;
if ( base > SQRT ) {
base = multiply(base, base, modulus);
}
else {
base = (base * base) % modulus;
}
}
return result;
}
// Result is a*b % mod, without overflow.
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
}
|
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #C.2B.2B | C++ | #include <vector>
#include <iostream>
using namespace std;
int chowla(int n)
{
int sum = 0;
for (int i = 2, j; i * i <= n; i++)
if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
vector<bool> sieve(int limit)
{
// True denotes composite, false denotes prime.
// Only interested in odd numbers >= 3
vector<bool> c(limit);
for (int i = 3; i * 3 < limit; i += 2)
if (!c[i] && (chowla(i) == 0))
for (int j = 3 * i; j < limit; j += 2 * i)
c[j] = true;
return c;
}
int main()
{
cout.imbue(locale(""));
for (int i = 1; i <= 37; i++)
cout << "chowla(" << i << ") = " << chowla(i) << "\n";
int count = 1, limit = (int)(1e7), power = 100;
vector<bool> c = sieve(limit);
for (int i = 3; i < limit; i += 2)
{
if (!c[i]) count++;
if (i == power - 1)
{
cout << "Count of primes up to " << power << " = "<< count <<"\n";
power *= 10;
}
}
count = 0; limit = 35000000;
int k = 2, kk = 3, p;
for (int i = 2; ; i++)
{
if ((p = k * kk) > limit) break;
if (chowla(p) == p - 1)
{
cout << p << " is a number that is perfect\n";
count++;
}
k = kk + 1; kk += k;
}
cout << "There are " << count << " perfect numbers <= 35,000,000\n";
return 0;
} |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #J | J | chget=: {{(0;1;1;1) {:: y}}
chset=: {{
'A B'=.;y
'C D'=.B
'E F'=.D
<A;<C;<E;<<.x
}}
ch0=: {{
if.0=#y do.y=.;:'>:' end. NB. replace empty gerund with increment
0 chset y`:6^:2`''
}}
apply=: `:6
chNext=: {{(1+chget y) chset y}}
chAdd=: {{(x +&chget y) chset y}}
chSub=: {{(x -&chget y) chset y}}
chMul=: {{(x *&chget y) chset y}}
chExp=: {{(x ^&chget y) chset y}}
int2ch=: {{y chset ch0 ''}}
ch2int=: chget |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #Java | Java | package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next(ChurchNum n) {
return f -> x -> f.apply(n.apply(f).apply(x));
}
public static ChurchNum plus(ChurchNum a) {
return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
}
public static ChurchNum pow(ChurchNum m) {
return n -> m.apply(n);
}
public static ChurchNum mult(ChurchNum a) {
return b -> f -> x -> b.apply(a.apply(f)).apply(x);
}
public static ChurchNum toChurchNum(int n) {
if (n <= 0) {
return zero();
}
return next(toChurchNum(n - 1));
}
public static int toInt(ChurchNum c) {
AtomicInteger counter = new AtomicInteger(0);
ChurchNum funCounter = f -> {
counter.incrementAndGet();
return f;
};
plus(zero()).apply(c).apply(funCounter).apply(x -> x);
return counter.get();
}
public static void main(String[] args) {
ChurchNum zero = zero();
ChurchNum three = next(next(next(zero)));
ChurchNum four = next(next(next(next(zero))));
System.out.println("3+4=" + toInt(plus(three).apply(four))); // prints 7
System.out.println("4+3=" + toInt(plus(four).apply(three))); // prints 7
System.out.println("3*4=" + toInt(mult(three).apply(four))); // prints 12
System.out.println("4*3=" + toInt(mult(four).apply(three))); // prints 12
// exponentiation. note the reversed order!
System.out.println("3^4=" + toInt(pow(four).apply(three))); // prints 81
System.out.println("4^3=" + toInt(pow(three).apply(four))); // prints 64
System.out.println(" 8=" + toInt(toChurchNum(8))); // prints 8
}
} |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #Delphi | Delphi | program SampleClass;
{$APPTYPE CONSOLE}
type
TMyClass = class
private
FSomeField: Integer; // by convention, fields are usually private and exposed as properties
public
constructor Create;
destructor Destroy; override;
procedure SomeMethod;
property SomeField: Integer read FSomeField write FSomeField;
end;
constructor TMyClass.Create;
begin
FSomeField := -1
end;
destructor TMyClass.Destroy;
begin
// free resources, etc
inherited Destroy;
end;
procedure TMyClass.SomeMethod;
begin
// do something
end;
var
lMyClass: TMyClass;
begin
lMyClass := TMyClass.Create;
try
lMyClass.SomeField := 99;
lMyClass.SomeMethod();
finally
lMyClass.Free;
end;
end. |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Plain_English | Plain English | To run:
Start up.
Show some example Cistercian numbers.
Wait for the escape key.
Shut down.
To show some example Cistercian numbers:
Put the screen's left plus 1 inch into the context's spot's x.
Clear the screen to the lightest gray color.
Use the black color.
Use the fat pen.
Draw 0.
Draw 1.
Draw 20.
Draw 300.
Draw 4000.
Draw 5555.
Draw 6789.
Draw 9394.
Refresh the screen.
The mirror flag is a flag.
To draw a Cistercian number:
Split the Cistercian number into some thousands and some hundreds and some tens and some ones.
Stroke zero.
Set the mirror flag.
Stroke the ones.
Clear the mirror flag.
Stroke the tens.
Turn around.
Stroke the hundreds.
Set the mirror flag.
Stroke the thousands.
Turn around.
Label the Cistercian number.
Move the context's spot right 1 inch.
To label a Cistercian number:
Save the context.
Move down the half stem plus the small stem.
Imagine a box with the context's spot and the context's spot.
Draw "" then the Cistercian number in the center of the box with the dark gray color.
Restore the context.
Some tens are a number.
Some ones are a number.
To split a number into some thousands and some hundreds and some tens and some ones:
Divide the number by 10 giving a quotient and a remainder.
Put the remainder into the ones.
Divide the quotient by 10 giving another quotient and another remainder.
Put the other remainder into the tens.
Divide the other quotient by 10 giving a third quotient and a third remainder.
Put the third remainder into the hundreds.
Divide the third quotient by 10 giving a fourth quotient and a fourth remainder.
Put the fourth remainder into the thousands.
The small stem is a length equal to 1/6 inch.
The half stem is a length equal to 1/2 inch.
The tail is a length equal to 1/3 inch.
The slanted tail is a length equal to 6/13 inch.
To stroke a number:
Save the context.
If the number is 1, stroke one.
If the number is 2, stroke two.
If the number is 3, stroke three.
If the number is 4, stroke four.
If the number is 5, stroke five.
If the number is 6, stroke six.
If the number is 7, stroke seven.
If the number is 8, stroke eight.
If the number is 9, stroke nine.
Restore the context.
To turn home:
If the mirror flag is set, turn right; exit.
Turn left.
To turn home some fraction of the way:
If the mirror flag is set, turn right the fraction; exit.
Turn left the fraction.
To stroke zero:
Save the context.
Stroke the half stem.
Turn around.
Move the half stem.
Stroke the half stem.
Restore the context.
To stroke one:
Move the half stem.
Turn home.
Stroke the tail.
To stroke two:
Move the small stem.
Turn home.
Stroke the tail.
To stroke three:
Move the half stem.
Turn home 3/8 of the way.
Stroke the slanted tail.
To stroke four:
Move the small stem.
Turn home 1/8 of the way.
Stroke the slanted tail.
To stroke five:
Stroke 1.
Stroke 4.
To stroke six:
Move the half stem.
Turn home.
Move the tail.
Turn home.
Stroke the tail.
To stroke seven:
Stroke 1.
Stroke 6.
To stroke eight:
Stroke 2.
Stroke 6.
To stroke nine:
Stroke 1.
Stroke 8. |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Python | Python | # -*- coding: utf-8 -*-
"""
Some UTF-8 chars used:
‾ 8254 203E ‾ OVERLINE
┃ 9475 2503 BOX DRAWINGS HEAVY VERTICAL
╱ 9585 2571 BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT
╲ 9586 2572 BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT
◸ 9720 25F8 UPPER LEFT TRIANGLE
◹ 9721 25F9 UPPER RIGHT TRIANGLE
◺ 9722 25FA LOWER LEFT TRIANGLE
◻ 9723 25FB WHITE MEDIUM SQUARE
◿ 9727 25FF LOWER RIGHT TRIANGLE
"""
#%% digit sections
def _init():
"digit sections for forming numbers"
digi_bits = """
#0 1 2 3 4 5 6 7 8 9
#
. ‾ _ ╲ ╱ ◸ .| ‾| _| ◻
#
. ‾ _ ╱ ╲ ◹ |. |‾ |_ ◻
#
. _ ‾ ╱ ╲ ◺ .| _| ‾| ◻
#
. _ ‾ ╲ ╱ ◿ |. |_ |‾ ◻
""".strip()
lines = [[d.replace('.', ' ') for d in ln.strip().split()]
for ln in digi_bits.strip().split('\n')
if '#' not in ln]
formats = '<2 >2 <2 >2'.split()
digits = [[f"{dig:{f}}" for dig in line]
for f, line in zip(formats, lines)]
return digits
_digits = _init()
#%% int to 3-line strings
def _to_digits(n):
assert 0 <= n < 10_000 and int(n) == n
return [int(digit) for digit in f"{int(n):04}"][::-1]
def num_to_lines(n):
global _digits
d = _to_digits(n)
lines = [
''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])),
''.join((_digits[0][ 0], '┃', _digits[0][ 0])),
''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])),
]
return lines
def cjoin(c1, c2, spaces=' '):
return [spaces.join(by_row) for by_row in zip(c1, c2)]
#%% main
if __name__ == '__main__':
#n = 6666
#print(f"Arabic {n} to Cistercian:\n")
#print('\n'.join(num_to_lines(n)))
for pow10 in range(4):
step = 10 ** pow10
print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n')
lines = num_to_lines(step)
for n in range(step*2, step*10, step):
lines = cjoin(lines, num_to_lines(n))
print('\n'.join(lines))
numbers = [0, 5555, 6789, 6666]
print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n')
lines = num_to_lines(numbers[0])
for n in numbers[1:]:
lines = cjoin(lines, num_to_lines(n))
print('\n'.join(lines)) |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #FreeBASIC | FreeBASIC |
Dim As Integer i, j
Dim As Double minDist = 1^30
Dim As Double x(9), y(9), dist, mini, minj
Data 0.654682, 0.925557
Data 0.409382, 0.619391
Data 0.891663, 0.888594
Data 0.716629, 0.996200
Data 0.477721, 0.946355
Data 0.925092, 0.818220
Data 0.624291, 0.142924
Data 0.211332, 0.221507
Data 0.293786, 0.691701
Data 0.839186, 0.728260
For i = 0 To 9
Read x(i), y(i)
Next i
For i = 0 To 8
For j = i+1 To 9
dist = (x(i) - x(j))^2 + (y(i) - y(j))^2
If dist < minDist Then
minDist = dist
mini = i
minj = j
End If
Next j
Next i
Print "El par más cercano es "; mini; " y "; minj; " a una distancia de "; Sqr(minDist)
End
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #M2000_Interpreter | M2000 Interpreter |
Dim Base 0, A(10)
For i=0 to 9 {
a(i)=lambda i -> i**2
}
For i=0 to 9 {
Print a(i)()
}
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Maple | Maple | > L := map( i -> (() -> i^2), [seq](1..10) ):
> seq( L[i](),i=1..10);
1, 4, 9, 16, 25, 36, 49, 64, 81, 100
> L[4]();
16
|
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #REXX | REXX | /*REXX program finds & displays circular primes (with a title & in a horizontal format).*/
parse arg N hp . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 19 /* " " " " " " */
if hp=='' | hp=="," then hip= 1000000 /* " " " " " " */
call genP /*gen primes up to hp (200,000). */
q= 024568 /*digs that most circular P can't have.*/
found= 0; $= /*found: circular P count; $: a list.*/
do j=1 until found==N; p= @.j /* [↓] traipse through all the primes.*/
if p>9 & verify(p, q, 'M')>0 then iterate /*Does J contain forbidden digs? Skip.*/
if \circP(p) then iterate /*Not circular? Then skip this number.*/
found= found + 1 /*bump the count of circular primes. */
$= $ p /*add this prime number ──► $ list. */
end /*j*/ /*at this point, $ has a leading blank.*/
say center(' first ' found " circular primes ", 79, '─')
say strip($)
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
circP: procedure expose @. !.; parse arg x 1 ox /*obtain a prime number to be examined.*/
do length(x)-1; parse var x f 2 y /*parse X number, rotating the digits*/
x= y || f /*construct a new possible circular P. */
if x<ox then return 0 /*is number < the original? ¬ circular*/
if \!.x then return 0 /* " " not prime? ¬ circular*/
end /*length(x)···*/
return 1 /*passed all tests, X is a circular P.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19 /*assign Ps; #Ps*/
!.= 0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1 /* " primality*/
#= 8; sq.#= @.# **2 /*number of primes so far; prime square*/
do j=@.#+4 by 2 to hip; parse var j '' -1 _ /*get last decimal digit of J. */
if _==5 then iterate; if j// 3==0 then iterate; if j// 7==0 then iterate
if j//11==0 then iterate; if j//13==0 then iterate; if j//17==0 then iterate
do k=8 while sq.k<=j /*divide by some generated odd primes. */
if j // @.k==0 then iterate j /*Is J divisible by P? Then not prime*/
end /*k*/ /* [↓] a prime (J) has been found. */
#= #+1; !.j= 1; sq.#= j*j; @.#= j /*bump P cnt; assign P to @. and !. */
end /*j*/; return |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #AWK | AWK |
# syntax: GAWK -f CIRCLES_OF_GIVEN_RADIUS_THROUGH_TWO_POINTS.AWK
# converted from PL/I
BEGIN {
split("0.1234,0,0.1234,0.1234,0.1234",m1x,",")
split("0.9876,2,0.9876,0.9876,0.9876",m1y,",")
split("0.8765,0,0.1234,0.8765,0.1234",m2x,",")
split("0.2345,0,0.9876,0.2345,0.9876",m2y,",")
leng = split("2,1,2,0.5,0",r,",")
print(" x1 y1 x2 y2 r cir1x cir1y cir2x cir2y")
print("------- ------- ------- ------- ---- ------- ------- ------- -------")
for (i=1; i<=leng; i++) {
printf("%7.4f %7.4f %7.4f %7.4f %4.2f %s\n",m1x[i],m1y[i],m2x[i],m2y[i],r[i],main(m1x[i],m1y[i],m2x[i],m2y[i],r[i]))
}
exit(0)
}
function main(m1x,m1y,m2x,m2y,r, bx,by,pb,x,x1,y,y1) {
if (r == 0) { return("radius of zero gives no circles") }
x = (m2x - m1x) / 2
y = (m2y - m1y) / 2
bx = m1x + x
by = m1y + y
pb = sqrt(x^2 + y^2)
if (pb == 0) { return("coincident points give infinite circles") }
if (pb > r) { return("points are too far apart for the given radius") }
cb = sqrt(r^2 - pb^2)
x1 = y * cb / pb
y1 = x * cb / pb
return(sprintf("%7.4f %7.4f %7.4f %7.4f",bx-x1,by+y1,bx+x1,by-y1))
}
|
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #AppleScript | AppleScript | on run
-- TRADITIONAL STRINGS ---------------------------------------------------
-- ts :: Array Int (String, String) -- 天干 tiangan – 10 heavenly stems
set ts to zip(chars("甲乙丙丁戊己庚辛壬癸"), ¬
|words|("jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi"))
-- ds :: Array Int (String, String) -- 地支 dizhi – 12 terrestrial branches
set ds to zip(chars("子丑寅卯辰巳午未申酉戌亥"), ¬
|words|("zĭ chŏu yín măo chén sì wŭ wèi shēn yŏu xū hài"))
-- ws :: Array Int (String, String, String) -- 五行 wuxing – 5 elements
set ws to zip3(chars("木火土金水"), ¬
|words|("mù huǒ tǔ jīn shuǐ"), ¬
|words|("wood fire earth metal water"))
-- xs :: Array Int (String, String, String) -- 十二生肖 shengxiao – 12 symbolic animals
set xs to zip3(chars("鼠牛虎兔龍蛇馬羊猴鸡狗豬"), ¬
|words|("shǔ niú hǔ tù lóng shé mǎ yáng hóu jī gǒu zhū"), ¬
|words|("rat ox tiger rabbit dragon snake horse goat monkey rooster dog pig"))
-- ys :: Array Int (String, String) -- 阴阳 yinyang
set ys to zip(chars("阳阴"), |words|("yáng yīn"))
-- TRADITIONAL CYCLES ----------------------------------------------------
script cycles
on |λ|(y)
set iYear to y - 4
set iStem to iYear mod 10
set iBranch to iYear mod 12
set {hStem, pStem} to item (iStem + 1) of ts
set {hBranch, pBranch} to item (iBranch + 1) of ds
set {hElem, pElem, eElem} to item ((iStem div 2) + 1) of ws
set {hAnimal, pAnimal, eAnimal} to item (iBranch + 1) of xs
set {hYinyang, pYinyang} to item ((iYear mod 2) + 1) of ys
{{show(y), hStem & hBranch, hElem, hAnimal, hYinyang}, ¬
{"", pStem & pBranch, pElem, pAnimal, pYinyang}, ¬
{"", show((iYear mod 60) + 1) & "/60", eElem, eAnimal, ""}}
end |λ|
end script
-- FORMATTING ------------------------------------------------------------
-- fieldWidths :: [[Int]]
set fieldWidths to {{6, 10, 7, 8, 3}, {6, 11, 8, 8, 4}, {6, 11, 8, 8, 4}}
script showYear
script widthStringPairs
on |λ|(nscs)
set {ns, cs} to nscs
zip(ns, cs)
end |λ|
end script
script justifiedRow
on |λ|(row)
script
on |λ|(ns)
set {n, s} to ns
justifyLeft(n, space, s)
end |λ|
end script
concat(map(result, row))
end |λ|
end script
on |λ|(y)
unlines(map(justifiedRow, ¬
map(widthStringPairs, ¬
zip(fieldWidths, |λ|(y) of cycles))))
end |λ|
end script
-- TEST OUTPUT -----------------------------------------------------------
intercalate("\n\n", map(showYear, {1935, 1938, 1968, 1972, 1976, 1984, 2017}))
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- chars :: String -> [String]
on chars(s)
characters of s
end chars
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- justifyLeft :: Int -> Char -> Text -> Text
on justifyLeft(n, cFiller, strText)
if n > length of strText then
text 1 thru n of (strText & replicate(n, cFiller))
else
strText
end if
end justifyLeft
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- minimum :: [a] -> a
on minimum(xs)
script min
on |λ|(a, x)
if x < a or a is missing value then
x
else
a
end if
end |λ|
end script
foldl(min, missing value, xs)
end minimum
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- show :: a -> String
on show(e)
set c to class of e
if c = list then
script serialized
on |λ|(v)
show(v)
end |λ|
end script
"[" & intercalate(", ", map(serialized, e)) & "]"
else if c = record then
script showField
on |λ|(kv)
set {k, ev} to kv
"\"" & k & "\":" & show(ev)
end |λ|
end script
"{" & intercalate(", ", ¬
map(showField, zip(allKeys(e), allValues(e)))) & "}"
else if c = date then
"\"" & iso8601Z(e) & "\""
else if c = text then
"\"" & e & "\""
else if (c = integer or c = real) then
e as text
else if c = class then
"null"
else
try
e as text
on error
("«" & c as text) & "»"
end try
end if
end show
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines
-- words :: String -> [String]
on |words|(s)
words of s
end |words|
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
repeat with i from 1 to lng
set end of lst to {item i of xs, item i of ys}
end repeat
return lst
end zip
-- zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]
on zip3(xs, ys, zs)
script
on |λ|(x, i)
[x, item i of ys, item i of zs]
end |λ|
end script
map(result, items 1 thru ¬
minimum({length of xs, length of ys, length of zs}) of xs)
end zip3 |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #6502_Assembly | 6502 Assembly | LDA $D011 ;screen control register 1
AND #%00100000 ;bit 5 clear = text mode, bit 5 set = gfx mode
BEQ isTerminal |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;
procedure Test_tty is
begin
if Isatty(Fileno(Stdout)) = 0 then
Put_Line(Standard_Error, "stdout is not a tty.");
else
Put_Line(Standard_Error, "stdout is a tty.");
end if;
end Test_tty; |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square root of
A
{\displaystyle A}
, as described in Cholesky decomposition.
In a 3x3 example, we have to solve the following system of equations:
A
=
(
a
11
a
21
a
31
a
21
a
22
a
32
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
l
11
l
21
l
31
0
l
22
l
32
0
0
l
33
)
≡
L
L
T
=
(
l
11
2
l
21
l
11
l
31
l
11
l
21
l
11
l
21
2
+
l
22
2
l
31
l
21
+
l
32
l
22
l
31
l
11
l
31
l
21
+
l
32
l
22
l
31
2
+
l
32
2
+
l
33
2
)
{\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}}
We can see that for the diagonal elements (
l
k
k
{\displaystyle l_{kk}}
) of
L
{\displaystyle L}
there is a calculation pattern:
l
11
=
a
11
{\displaystyle l_{11}={\sqrt {a_{11}}}}
l
22
=
a
22
−
l
21
2
{\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}}
l
33
=
a
33
−
(
l
31
2
+
l
32
2
)
{\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}}
or in general:
l
k
k
=
a
k
k
−
∑
j
=
1
k
−
1
l
k
j
2
{\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}}
For the elements below the diagonal (
l
i
k
{\displaystyle l_{ik}}
, where
i
>
k
{\displaystyle i>k}
) there is also a calculation pattern:
l
21
=
1
l
11
a
21
{\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}}
l
31
=
1
l
11
a
31
{\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}}
l
32
=
1
l
22
(
a
32
−
l
31
l
21
)
{\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})}
which can also be expressed in a general formula:
l
i
k
=
1
l
k
k
(
a
i
k
−
∑
j
=
1
k
−
1
l
i
j
l
k
j
)
{\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)}
Task description
The task is to implement a routine which will return a lower Cholesky factor
L
{\displaystyle L}
for every given symmetric, positive definite nxn matrix
A
{\displaystyle A}
. You should then test it on the following two examples and include your output.
Example 1:
25 15 -5 5 0 0
15 18 0 --> 3 3 0
-5 0 11 -1 1 3
Example 2:
18 22 54 42 4.24264 0.00000 0.00000 0.00000
22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000
54 86 174 134 12.72792 3.04604 1.64974 0.00000
42 62 134 106 9.89949 1.62455 1.84971 1.39262
Note
The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. | #BBC_BASIC | BBC BASIC | DIM m1(2,2)
m1() = 25, 15, -5, \
\ 15, 18, 0, \
\ -5, 0, 11
PROCcholesky(m1())
PROCprint(m1())
PRINT
@% = &2050A
DIM m2(3,3)
m2() = 18, 22, 54, 42, \
\ 22, 70, 86, 62, \
\ 54, 86, 174, 134, \
\ 42, 62, 134, 106
PROCcholesky(m2())
PROCprint(m2())
END
DEF PROCcholesky(a())
LOCAL i%, j%, k%, l(), s
DIM l(DIM(a(),1),DIM(a(),2))
FOR i% = 0 TO DIM(a(),1)
FOR j% = 0 TO i%
s = 0
FOR k% = 0 TO j%-1
s += l(i%,k%) * l(j%,k%)
NEXT
IF i% = j% THEN
l(i%,j%) = SQR(a(i%,i%) - s)
ELSE
l(i%,j%) = (a(i%,j%) - s) / l(j%,j%)
ENDIF
NEXT j%
NEXT i%
a() = l()
ENDPROC
DEF PROCprint(a())
LOCAL row%, col%
FOR row% = 0 TO DIM(a(),1)
FOR col% = 0 TO DIM(a(),2)
PRINT a(row%,col%);
NEXT
PRINT
NEXT row%
ENDPROC |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square root of
A
{\displaystyle A}
, as described in Cholesky decomposition.
In a 3x3 example, we have to solve the following system of equations:
A
=
(
a
11
a
21
a
31
a
21
a
22
a
32
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
l
11
l
21
l
31
0
l
22
l
32
0
0
l
33
)
≡
L
L
T
=
(
l
11
2
l
21
l
11
l
31
l
11
l
21
l
11
l
21
2
+
l
22
2
l
31
l
21
+
l
32
l
22
l
31
l
11
l
31
l
21
+
l
32
l
22
l
31
2
+
l
32
2
+
l
33
2
)
{\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}}
We can see that for the diagonal elements (
l
k
k
{\displaystyle l_{kk}}
) of
L
{\displaystyle L}
there is a calculation pattern:
l
11
=
a
11
{\displaystyle l_{11}={\sqrt {a_{11}}}}
l
22
=
a
22
−
l
21
2
{\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}}
l
33
=
a
33
−
(
l
31
2
+
l
32
2
)
{\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}}
or in general:
l
k
k
=
a
k
k
−
∑
j
=
1
k
−
1
l
k
j
2
{\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}}
For the elements below the diagonal (
l
i
k
{\displaystyle l_{ik}}
, where
i
>
k
{\displaystyle i>k}
) there is also a calculation pattern:
l
21
=
1
l
11
a
21
{\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}}
l
31
=
1
l
11
a
31
{\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}}
l
32
=
1
l
22
(
a
32
−
l
31
l
21
)
{\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})}
which can also be expressed in a general formula:
l
i
k
=
1
l
k
k
(
a
i
k
−
∑
j
=
1
k
−
1
l
i
j
l
k
j
)
{\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)}
Task description
The task is to implement a routine which will return a lower Cholesky factor
L
{\displaystyle L}
for every given symmetric, positive definite nxn matrix
A
{\displaystyle A}
. You should then test it on the following two examples and include your output.
Example 1:
25 15 -5 5 0 0
15 18 0 --> 3 3 0
-5 0 11 -1 1 3
Example 2:
18 22 54 42 4.24264 0.00000 0.00000 0.00000
22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000
54 86 174 134 12.72792 3.04604 1.64974 0.00000
42 62 134 106 9.89949 1.62455 1.84971 1.39262
Note
The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double *cholesky(double *A, int n) {
double *L = (double*)calloc(n * n, sizeof(double));
if (L == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
for (int j = 0; j < (i+1); j++) {
double s = 0;
for (int k = 0; k < j; k++)
s += L[i * n + k] * L[j * n + k];
L[i * n + j] = (i == j) ?
sqrt(A[i * n + i] - s) :
(1.0 / L[j * n + j] * (A[i * n + j] - s));
}
return L;
}
void show_matrix(double *A, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%2.5f ", A[i * n + j]);
printf("\n");
}
}
int main() {
int n = 3;
double m1[] = {25, 15, -5,
15, 18, 0,
-5, 0, 11};
double *c1 = cholesky(m1, n);
show_matrix(c1, n);
printf("\n");
free(c1);
n = 4;
double m2[] = {18, 22, 54, 42,
22, 70, 86, 62,
54, 86, 174, 134,
42, 62, 134, 106};
double *c2 = cholesky(m2, n);
show_matrix(c2, n);
free(c2);
return 0;
} |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, and Bernard the day (of the month) of birth.
1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
3) Albert: Then I also know when Cheryl's birthday is.
Task
Write a computer program to deduce, by successive elimination, Cheryl's birthday.
Related task
Sum and Product Puzzle
References
Wikipedia article of the same name.
Tuple Relational Calculus
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type Months is
(January, February, March, April, May, June, July, August, September,
November, December);
type day_num is range 1 .. 31;
type birthdate is record
Month : Months;
Day : day_num;
Active : Boolean;
end record;
type birthday_list is array (Positive range <>) of birthdate;
Possible_birthdates : birthday_list :=
((May, 15, True), (May, 16, True), (May, 19, True), (June, 17, True),
(June, 18, True), (July, 14, True), (July, 16, True), (August, 14, True),
(August, 15, True), (August, 17, True));
procedure print_answer is
begin
for the_day of Possible_birthdates loop
if the_day.Active then
Put_Line (the_day.Month'Image & "," & the_day.Day'Image);
end if;
end loop;
end print_answer;
procedure print_remaining is
count : Natural := 0;
begin
for date of Possible_birthdates loop
if date.Active then
count := count + 1;
end if;
end loop;
Put_Line (count'Image & " remaining.");
end print_remaining;
-- the month cannot have a unique day
procedure first_pass is
count : Natural;
begin
for first_day of Possible_birthdates loop
count := 0;
for next_day of Possible_birthdates loop
if first_day.Day = next_day.Day then
count := count + 1;
end if;
end loop;
if count = 1 then
for the_day of Possible_birthdates loop
if the_day.Active and then first_day.Month = the_day.Month then
the_day.Active := False;
end if;
end loop;
end if;
end loop;
end first_pass;
-- the day must now be unique
procedure second_pass is
count : Natural;
begin
for first_day of Possible_birthdates loop
if first_day.Active then
count := 0;
for next_day of Possible_birthdates loop
if next_day.Active then
if next_day.Day = first_day.Day then
count := count + 1;
end if;
end if;
end loop;
if count > 1 then
for next_day of Possible_birthdates loop
if next_day.Active and then next_day.Day = first_day.Day then
next_day.Active := False;
end if;
end loop;
end if;
end if;
end loop;
end second_pass;
-- the month must now be unique
procedure third_pass is
count : Natural;
begin
for first_day of Possible_birthdates loop
if first_day.Active then
count := 0;
for next_day of Possible_birthdates loop
if next_day.Active and then next_day.Month = first_day.Month
then
count := count + 1;
end if;
end loop;
if count > 1 then
for next_day of Possible_birthdates loop
if next_day.Active and then next_day.Month = first_day.Month
then
next_day.Active := False;
end if;
end loop;
end if;
end if;
end loop;
end third_pass;
begin
print_remaining;
first_pass;
print_remaining;
second_pass;
print_remaining;
third_pass;
print_answer;
end Main; |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"TIMERLIB"
nWorkers% = 3
DIM tID%(nWorkers%)
tID%(1) = FN_ontimer(10, PROCworker1, 1)
tID%(2) = FN_ontimer(11, PROCworker2, 1)
tID%(3) = FN_ontimer(12, PROCworker3, 1)
DEF PROCworker1 : PROCtask(1) : ENDPROC
DEF PROCworker2 : PROCtask(2) : ENDPROC
DEF PROCworker3 : PROCtask(3) : ENDPROC
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask(worker%)
PRIVATE cnt%()
DIM cnt%(nWorkers%)
CASE cnt%(worker%) OF
WHEN 0:
cnt%(worker%) = RND(30)
PRINT "Worker "; worker% " starting (" ;cnt%(worker%) " ticks)"
WHEN -1:
OTHERWISE:
cnt%(worker%) -= 1
IF cnt%(worker%) = 0 THEN
PRINT "Worker "; worker% " ready and waiting"
cnt%(worker%) = -1
PROCcheckpoint
cnt%(worker%) = 0
ENDIF
ENDCASE
ENDPROC
DEF PROCcheckpoint
PRIVATE checked%, sync%
IF checked% = 0 sync% = FALSE
checked% += 1
WHILE NOT sync%
WAIT 0
IF checked% = nWorkers% THEN
sync% = TRUE
PRINT "--Sync Point--"
ENDIF
ENDWHILE
checked% -= 1
ENDPROC
DEF PROCcleanup
LOCAL I%
FOR I% = 1 TO nWorkers%
PROC_killtimer(tID%(I%))
NEXT
ENDPROC |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
/* this is the checkpoint */
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
/* this stops jobless thread from exiting early and killing workers */
#pragma omp barrier
}
return 0;
} |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Elena | Elena |
// Weak array
var stringArr := Array.allocate(5);
stringArr[0] := "string";
// initialized array
var intArray := new int[]{1, 2, 3, 4, 5};
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Kotlin | Kotlin | class Combinations(val m: Int, val n: Int) {
private val combination = IntArray(m)
init {
generate(0)
}
private fun generate(k: Int) {
if (k >= m) {
for (i in 0 until m) print("${combination[i]} ")
println()
}
else {
for (j in 0 until n)
if (k == 0 || j > combination[k - 1]) {
combination[k] = j
generate(k + 1)
}
}
}
}
fun main(args: Array<String>) {
Combinations(3, 5)
} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Prolog | Prolog | go :- write('Hello, World!'), nl. |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Zoea | Zoea |
program comments # this program does nothing
# zoea supports single line comments starting with a '#' char
/*
zoea also supports
multi line
comments
*/
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Zoea_Visual | Zoea Visual |
(* this is a comment *)
(*
and this is a
multiline comment
(* with a nested comment *)
*)
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #zonnon | zonnon |
(* this is a comment *)
(*
and this is a
multiline comment
(* with a nested comment *)
*)
|
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #Arturo | Arturo | mulInv: function [a0, b0][
[a b x0]: @[a0 b0 0]
result: 1
if b = 1 -> return result
while [a > 1][
q: a / b
a: a % b
tmp: a
a: b
b: tmp
result: result - q * x0
tmp: x0
x0: result
result: tmp
]
if result < 0 -> result: result + b0
return result
]
chineseRemainder: function [N, A][
prod: 1
s: 0
loop N 'x -> prod: prod * x
loop.with:'i N 'x [
p: prod / x
s: s + (mulInv p x) * p * A\[i]
]
return s % prod
]
print chineseRemainder [3 5 7] [2 3 2] |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #Julia | Julia | using Primes
function trial_pretest(k::UInt64)
if ((k % 3)==0 || (k % 5)==0 || (k % 7)==0 || (k % 11)==0 ||
(k % 13)==0 || (k % 17)==0 || (k % 19)==0 || (k % 23)==0)
return (k <= 23)
end
return true
end
function gcd_pretest(k::UInt64)
if (k <= 107)
return true
end
gcd(29*31*37*41*43*47*53*59*61*67, k) == 1 &&
gcd(71*73*79*83*89*97*101*103*107, k) == 1
end
function is_chernick(n::Int64, m::UInt64)
t = 9*m
if (!trial_pretest(6*m + 1))
return false
end
if (!trial_pretest(12*m + 1))
return false
end
for i in 1:n-2
if (!trial_pretest((t << i) + 1))
return false
end
end
if (!gcd_pretest(6*m + 1))
return false
end
if (!gcd_pretest(12*m + 1))
return false
end
for i in 1:n-2
if (!gcd_pretest((t << i) + 1))
return false
end
end
if (!isprime(6*m + 1))
return false
end
if (!isprime(12*m + 1))
return false
end
for i in 1:n-2
if (!isprime((t << i) + 1))
return false
end
end
return true
end
function chernick_carmichael(n::Int64, m::UInt64)
prod = big(1)
prod *= 6*m + 1
prod *= 12*m + 1
for i in 1:n-2
prod *= ((big(9)*m)<<i) + 1
end
prod
end
function cc_numbers(from, to)
for n in from:to
multiplier = 1
if (n > 4) multiplier = 1 << (n-4) end
if (n > 5) multiplier *= 5 end
m = UInt64(multiplier)
while true
if (is_chernick(n, m))
println("a(", n, ") = ", chernick_carmichael(n, m))
break
end
m += multiplier
end
end
end
cc_numbers(3, 10) |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[PrimeFactorCounts, U]
PrimeFactorCounts[n_Integer] := Total[FactorInteger[n][[All, 2]]]
U[n_, m_] := (6 m + 1) (12 m + 1) Product[2^i 9 m + 1, {i, 1, n - 2}]
FindFirstChernickCarmichaelNumber[n_Integer?Positive] :=
Module[{step, i, m, formula, value},
step = Ceiling[2^(n - 4)];
If[n > 5, step *= 5];
i = step;
formula = U[n, m];
PrintTemporary[Dynamic[i]];
While[True,
value = formula /. m -> i;
If[PrimeFactorCounts[value] == n,
Break[];
];
i += step
];
{i, value}
]
FindFirstChernickCarmichaelNumber[3]
FindFirstChernickCarmichaelNumber[4]
FindFirstChernickCarmichaelNumber[5]
FindFirstChernickCarmichaelNumber[6]
FindFirstChernickCarmichaelNumber[7]
FindFirstChernickCarmichaelNumber[8]
FindFirstChernickCarmichaelNumber[9] |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #Nim | Nim | import strutils, sequtils
import bignum
const
Max = 10
Factors: array[3..Max, int] = [1, 1, 2, 4, 8, 16, 32, 64] # 1 for n=3 then 2^(n-4).
FirstPrimes = [3, 5, 7, 11, 13, 17, 19, 23]
#---------------------------------------------------------------------------------------------------
iterator factors(n, m: Natural): Natural =
## Yield the factors of U(n, m).
yield 6 * m + 1
yield 12 * m + 1
var k = 2
for _ in 1..(n - 2):
yield 9 * k * m + 1
inc k, k
#---------------------------------------------------------------------------------------------------
proc mayBePrime(n: int): bool =
## First primality test.
if n < 23: return true
for p in FirstPrimes:
if n mod p == 0:
return false
result = true
#---------------------------------------------------------------------------------------------------
proc isChernick(n, m: Natural): bool =
## Check if U(N, m) if a Chernick-Carmichael number.
# Use the first and quick test.
for factor in factors(n, m):
if not factor.mayBePrime():
return false
# Use the slow probability test (need to use a big int).
for factor in factors(n, m):
if probablyPrime(newInt(factor), 25) == 0:
return false
result = true
#---------------------------------------------------------------------------------------------------
proc a(n: Natural): tuple[m: Natural, factors: seq[Natural]] =
## For a given "n", find the smallest Charnick-Carmichael number.
var m: Natural = 0
var incr = (if n >= 5: 5 else: 1) * Factors[n] # For n >= 5, a(n) is a multiple of 5.
while true:
inc m, incr
if isChernick(n, m):
return (m, toSeq(factors(n, m)))
#———————————————————————————————————————————————————————————————————————————————————————————————————
import strformat
for n in 3..Max:
let (m, factors) = a(n)
stdout.write fmt"a({n}) = U({n}, {m}) = "
var s = ""
for factor in factors:
s.addSep(" × ")
s.add($factor)
stdout.write s, '\n' |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #CLU | CLU | % Chowla's function
chowla = proc (n: int) returns (int)
sum: int := 0
i: int := 2
while i*i <= n do
if n//i = 0 then
sum := sum + i
j: int := n/i
if i ~= j then
sum := sum + j
end
end
i := i + 1
end
return(sum)
end chowla
% A number is prime iff chowla(n) is 0
prime = proc (n: int) returns (bool)
return(chowla(n) = 0)
end prime
% A number is perfect iff chowla(n) equals n-1
perfect = proc (n: int) returns (bool)
return(chowla(n) = n-1)
end perfect
start_up = proc ()
LIMIT = 35000000
po: stream := stream$primary_output()
% Show chowla(1) through chowla(37)
for i: int in int$from_to(1, 37) do
stream$putl(po, "chowla(" || int$unparse(i) || ") = "
|| int$unparse(chowla(i)))
end
% Count primes up to powers of 10
pow10: int := 2 % start with 100
primecount: int := 1 % assume 2 is prime, then test only odd numbers
candidate: int := 3
while pow10 <= 7 do
if candidate >= 10**pow10 then
stream$putl(po, "There are "
|| int$unparse(primecount)
|| " primes up to "
|| int$unparse(10**pow10))
pow10 := pow10 + 1
end
if prime(candidate) then primecount := primecount + 1 end
candidate := candidate + 2
end
% Find perfect numbers up to 35 million
perfcount: int := 0
k: int := 2
kk: int := 3
while true do
n: int := k * kk
if n >= LIMIT then break end
if perfect(n) then
perfcount := perfcount + 1
stream$putl(po, int$unparse(n) || " is a perfect number.")
end
k := kk + 1
kk := kk + k
end
stream$putl(po, "There are " || int$unparse(perfcount) ||
" perfect numbers < 35,000,000.")
end start_up |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #Cowgol | Cowgol | include "cowgol.coh";
sub chowla(n: uint32): (sum: uint32) is
sum := 0;
var i: uint32 := 2;
while i*i <= n loop
if n % i == 0 then
sum := sum + i;
var j := n / i;
if i != j then
sum := sum + j;
end if;
end if;
i := i + 1;
end loop;
end sub;
var n: uint32 := 1;
while n <= 37 loop
print("chowla(");
print_i32(n);
print(") = ");
print_i32(chowla(n));
print("\n");
n := n + 1;
end loop;
n := 2;
var power: uint32 := 100;
var count: uint32 := 0;
while n <= 10000000 loop
if chowla(n) == 0 then
count := count + 1;
end if;
if n % power == 0 then
print("There are ");
print_i32(count);
print(" primes < ");
print_i32(power);
print_nl();
power := power * 10;
end if;
n := n + 1;
end loop;
count := 0;
const LIMIT := 35000000;
var k: uint32 := 2;
var kk: uint32 := 3;
loop
n := k * kk;
if n > LIMIT then break; end if;
if chowla(n) == n-1 then
print_i32(n);
print(" is a perfect number.\n");
count := count + 1;
end if;
k := kk + 1;
kk := kk + k;
end loop;
print("There are ");
print_i32(count);
print(" perfect numbers < ");
print_i32(LIMIT);
print_nl(); |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #JavaScript | JavaScript | (() => {
'use strict';
// ----------------- CHURCH NUMERALS -----------------
const churchZero = f =>
identity;
const churchSucc = n =>
f => compose(f)(n(f));
const churchAdd = m =>
n => f => compose(n(f))(m(f));
const churchMult = m =>
n => f => n(m(f));
const churchExp = m =>
n => n(m);
const intFromChurch = n =>
n(succ)(0);
const churchFromInt = n =>
compose(
foldl(compose)(identity)
)(
replicate(n)
);
// Or, by explicit recursion:
const churchFromInt_ = x => {
const go = i =>
0 === i ? (
churchZero
) : churchSucc(go(pred(i)));
return go(x);
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
const [cThree, cFour] = map(churchFromInt)([3, 4]);
return map(intFromChurch)([
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
]);
};
// --------------------- GENERIC ---------------------
// compose (>>>) :: (a -> b) -> (b -> c) -> a -> c
const compose = f =>
g => x => f(g(x));
// foldl :: (a -> b -> a) -> a -> [b] -> a
const foldl = f =>
a => xs => [...xs].reduce(
(x, y) => f(x)(y),
a
);
// identity :: a -> a
const identity = x => x;
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f
// to each element of xs.
// (The image of xs under f).
xs => [...xs].map(f);
// pred :: Enum a => a -> a
const pred = x =>
x - 1;
// replicate :: Int -> a -> [a]
const replicate = n =>
// n instances of x.
x => Array.from({
length: n
}, () => x);
// succ :: Enum a => a -> a
const succ = x =>
1 + x;
// MAIN ---
console.log(JSON.stringify(main()));
})(); |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #DM | DM | s |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #Dragon | Dragon | class run{
func val(){
showln 10+20
}
}
|
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Raku | Raku | my @line-segments = (0, 0, 0, 100),
(0, 0, 35, 0), (0, 35, 35, 35), (0, 0, 35, 35), (0, 35, 35, 0), ( 35, 0, 35, 35),
(0, 0,-35, 0), (0, 35,-35, 35), (0, 0,-35, 35), (0, 35,-35, 0), (-35, 0,-35, 35),
(0,100, 35,100), (0, 65, 35, 65), (0,100, 35, 65), (0, 65, 35,100), ( 35, 65, 35,100),
(0,100,-35,100), (0, 65,-35, 65), (0,100,-35, 65), (0, 65,-35,100), (-35, 65,-35,100);
my @components = map {@line-segments[$_]}, |((0, 5, 10, 15).map: -> $m {
|((0,), (1,), (2,), (3,), (4,), (1,4), (5,), (1,5), (2,5), (1,2,5)).map: {$_ »+» $m}
});
my $out = 'Cistercian-raku.svg'.IO.open(:w);
$out.say: # insert header
q|<svg width="875" height="470" style="stroke:black;" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" style="fill:white;"/>|;
my $hs = 50; # horizontal spacing
my $vs = 25; # vertical spacing
for flat ^10, 20, 300, 4000, 5555, 6789, 9394, (^10000).pick(14) -> $cistercian {
$out.say: |@components[0].map: { # draw zero / base vertical bar
qq|<line x1="{.[0] + $hs}" y1="{.[1] + $vs}" x2="{.[2] + $hs}" y2="{.[3] + $vs}"/>|
};
my @orders-of-magnitude = $cistercian.polymod(10 xx *);
for @orders-of-magnitude.kv -> $order, $value {
next unless $value; # skip zeros, already drew zero bar
last if $order > 3; # truncate too large integers
# draw the component line segments
$out.say: join "\n", @components[$order * 10 + $value].map: {
qq|<line x1="{.[0] + $hs}" y1="{.[1] + $vs}" x2="{.[2] + $hs}" y2="{.[3] + $vs}"/>|
}
}
# insert the decimal number below
$out.say: qq|<text x="{$hs - 5}" y="{$vs + 120}">{$cistercian}</text>|;
if ++$ %% 10 { # next row
$hs = -35;
$vs += 150;
}
$hs += 85; # increment horizontal spacing
}
$out.say: q|</svg>|; # insert footer |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
type xy struct {
x, y float64
}
const n = 1000
const scale = 100.
func d(p1, p2 xy) float64 {
return math.Hypot(p2.x-p1.x, p2.y-p1.y)
}
func main() {
rand.Seed(time.Now().Unix())
points := make([]xy, n)
for i := range points {
points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
}
p1, p2 := closestPair(points)
fmt.Println(p1, p2)
fmt.Println("distance:", d(p1, p2))
}
func closestPair(points []xy) (p1, p2 xy) {
if len(points) < 2 {
panic("at least two points expected")
}
min := 2 * scale
for i, q1 := range points[:len(points)-1] {
for _, q2 := range points[i+1:] {
if dq := d(q1, q2); dq < min {
p1, p2 = q1, q2
min = dq
}
}
}
return
} |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Function[i, i^2 &] /@ Range@10
->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &}
%[[2]][]
->4 |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Nemerle | Nemerle | using System.Console;
module Closures
{
Main() : void
{
def f(x) { fun() { x ** 2 } }
def funcs = $[f(x) | x in $[0 .. 10]].ToArray(); // using array for easy indexing
WriteLine($"$(funcs[4]())");
WriteLine($"$(funcs[2]())");
}
} |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Ring | Ring |
see "working..." + nl
see "First 19 circular numbers are:" + nl
n = 0
row = 0
Primes = []
while row < 19
n++
flag = 1
nStr = string(n)
lenStr = len(nStr)
for m = 1 to lenStr
leftStr = left(nStr,m)
rightStr = right(nStr,lenStr-m)
strOk = rightStr + leftStr
nOk = number(strOk)
ind = find(Primes,nOk)
if ind < 1 and strOk != nStr
add(Primes,nOk)
ok
if not isprimeNumber(nOk) or ind > 0
flag = 0
exit
ok
next
if flag = 1
row++
see "" + n + " "
if row%5 = 0
see nl
ok
ok
end
see nl + "done..." + nl
func isPrimeNumber(num)
if (num <= 1) return 0 ok
if (num % 2 = 0) and (num != 2) return 0 ok
for i = 2 to sqrt(num)
if (num % i = 0) return 0 ok
next
return 1
|
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Ruby | Ruby | require 'gmp'
require 'prime'
candidate_primes = Enumerator.new do |y|
DIGS = [1,3,7,9]
[2,3,5,7].each{|n| y << n.to_s}
(2..).each do |size|
DIGS.repeated_permutation(size) do |perm|
y << perm.join if (perm == min_rotation(perm)) && GMP::Z(perm.join).probab_prime? > 0
end
end
end
def min_rotation(ar) = Array.new(ar.size){|n| ar.rotate(n)}.min
def circular?(num_str)
chars = num_str.chars
return GMP::Z(num_str).probab_prime? > 0 if chars.all?("1")
chars.size.times.all? do
GMP::Z(chars.rotate!.join).probab_prime? > 0
# chars.rotate!.join.to_i.prime?
end
end
puts "First 19 circular primes:"
puts candidate_primes.lazy.select{|cand| circular?(cand)}.take(19).to_a.join(", "),""
puts "First 5 prime repunits:"
reps = Prime.each.lazy.select{|pr| circular?("1"*pr)}.take(5).to_a
puts reps.map{|r| "R" + r.to_s}.join(", "), ""
[5003, 9887, 15073, 25031].each {|rep| puts "R#{rep} circular_prime ? #{circular?("1"*rep)}" }
|
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #BASIC256 | BASIC256 |
function twoCircles(x1, y1, x2, y2, radio)
if x1 = x2 and y1 = y2 then #Si los puntos coinciden
if radio = 0 then #a no ser que radio=0
print "Los puntos son los mismos "
return ""
else
print "Hay cualquier número de círculos a través de un solo punto ("; x1; ", "; y1; ") de radio "; int(radio)
return ""
end if
end if
r2 = sqr((x1-x2)^2+(y1-y2)^2) / 2 #distancia media entre puntos
if radio < r2 then
print "Los puntos están demasiado separados ("; 2*r2; ") - no hay círculos de radio "; int(radio)
return ""
end if
#si no, calcular dos centros
cx = (x1+x2) / 2 #punto medio
cy = (y1+y2) / 2
#debe moverse desde el punto medio a lo largo de la perpendicular en dd2
dd2 = sqr(radio^2 - r2^2) #distancia perpendicular
dx1 = x2-cx #vector al punto medio
dy1 = y2-cy
dx = 0-dy1 / r2*dd2 #perpendicular:
dy = dx1 / r2*dd2 #rotar y escalar
print " -> Circulo 1 ("; cx+dy; ", "; cy+dx; ")" #dos puntos, con (+)
print " -> Circulo 2 ("; cx-dy; ", "; cy-dx; ")" #y (-)
return ""
end function
# p1 p2 radio
x1 = 0.1234 : y1 = 0.9876 : x2 = 0.8765 : y2 = 0.2345 : radio = 2.0
print "Puntos "; "("; x1; ","; y1; "), ("; x2; ","; y2; ")"; ", Radio "; int(radio)
print twoCircles (x1, y1, x2, y2, radio)
x1 = 0.0000 : y1 = 2.0000 : x2 = 0.0000 : y2 = 0.0000 : radio = 1.0
print "Puntos "; "("; x1; ","; y1; "), ("; x2; ","; y2; ")"; ", Radio "; int(radio)
print twoCircles (x1, y1, x2, y2, radio)
x1 = 0.1234 : y1 = 0.9876 : x2 = 0.12345 : y2 = 0.9876 : radio = 2.0
print "Puntos "; "("; x1; ","; y1; "), ("; x2; ","; y2; ")"; ", Radio "; int(radio)
print twoCircles (x1, y1, x2, y2, radio)
x1 = 0.1234 : y1 = 0.9876 : x2 = 0.8765 : y2 = 0.2345 : radio = 0.5
print "Puntos "; "("; x1; ","; y1; "), ("; x2; ","; y2; ")"; ", Radio "; int(radio)
print twoCircles (x1, y1, x2, y2, radio)
x1 = 0.1234 : y1 = 0.9876 : x2 = 1234 : y2 = 0.9876 : radio = 0.0
print "Puntos "; "("; x1; ","; y1; "), ("; x2; ","; y2; ")"; ", Radio "; int(radio)
print twoCircles (x1, y1, x2, y2, radio)
end
|
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #AutoHotkey | AutoHotkey | Chinese_zodiac(year){
Animal := StrSplit("Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig", ",")
AnimalCh := StrSplit("鼠牛虎兔龍蛇馬羊猴鸡狗豬")
AnimalName := StrSplit("shǔ,niú,hǔ,tù,lóng,shé,mǎ,yáng,hóu,jī,gǒu,zhū", ",")
Element := StrSplit("Wood,Fire,Earth,Metal,Water", ",")
ElementCh := StrSplit("木火土金水")
ElementName := StrSplit("mù,huǒ,tǔ,jīn,shuǐ", ",")
StemCh := StrSplit("甲乙丙丁戊己庚辛壬癸")
StemName := StrSplit("jiă,yĭ,bĭng,dīng,wù,jĭ,gēng,xīn,rén,gŭi", ",")
BranchCh := StrSplit("子丑寅卯辰巳午未申酉戌亥")
BranchName := StrSplit("zĭ,chŏu,yín,măo,chén,sì,wŭ,wèi,shēn,yŏu,xū,hài", ",")
Mod10 := Mod(year-4, 10)+1
Mod12 := Mod(year-4, 12)+1
A := Animal[Mod12],
Ac := AnimalCh[Mod12]
An := AnimalName[Mod12]
E := Element[Floor(Mod(year-4, 10)/2+1)]
Ec := ElementCh[Floor(Mod(year-4, 10)/2+1)]
En := ElementName[Floor(Mod(year-4, 10)/2+1)]
YY := Mod(year-4, 2)=1 ? "yīn 阴" : "yáng 阳"
Yr := Mod(year-4, 60)+1 "/60"
S := StemCh[Mod10]
Sn := StemName[Mod10]
B := BranchCh[Mod12]
Bn := BranchName[Mod12]
return year "`t" S B " " Sn "-" Bn " `t" E " " Ec " " En "`t" A " " Ac " " An "`t" YY " " Yr
} |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #C | C | #include <unistd.h> // for isatty()
#include <stdio.h> // for fileno()
int main()
{
puts(isatty(fileno(stdout))
? "stdout is tty"
: "stdout is not tty");
return 0;
} |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #C.23 | C# | using System;
namespace CheckTerminal {
class Program {
static void Main(string[] args) {
Console.WriteLine("Stdout is tty: {0}", Console.IsOutputRedirected);
}
}
} |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #C.2B.2B | C++ | #if _WIN32
#include <io.h>
#define ISATTY _isatty
#define FILENO _fileno
#else
#include <unistd.h>
#define ISATTY isatty
#define FILENO fileno
#endif
#include <iostream>
int main() {
if (ISATTY(FILENO(stdout))) {
std::cout << "stdout is a tty\n";
} else {
std::cout << "stdout is not a tty\n";
}
return 0;
} |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square root of
A
{\displaystyle A}
, as described in Cholesky decomposition.
In a 3x3 example, we have to solve the following system of equations:
A
=
(
a
11
a
21
a
31
a
21
a
22
a
32
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
l
11
l
21
l
31
0
l
22
l
32
0
0
l
33
)
≡
L
L
T
=
(
l
11
2
l
21
l
11
l
31
l
11
l
21
l
11
l
21
2
+
l
22
2
l
31
l
21
+
l
32
l
22
l
31
l
11
l
31
l
21
+
l
32
l
22
l
31
2
+
l
32
2
+
l
33
2
)
{\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}}
We can see that for the diagonal elements (
l
k
k
{\displaystyle l_{kk}}
) of
L
{\displaystyle L}
there is a calculation pattern:
l
11
=
a
11
{\displaystyle l_{11}={\sqrt {a_{11}}}}
l
22
=
a
22
−
l
21
2
{\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}}
l
33
=
a
33
−
(
l
31
2
+
l
32
2
)
{\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}}
or in general:
l
k
k
=
a
k
k
−
∑
j
=
1
k
−
1
l
k
j
2
{\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}}
For the elements below the diagonal (
l
i
k
{\displaystyle l_{ik}}
, where
i
>
k
{\displaystyle i>k}
) there is also a calculation pattern:
l
21
=
1
l
11
a
21
{\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}}
l
31
=
1
l
11
a
31
{\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}}
l
32
=
1
l
22
(
a
32
−
l
31
l
21
)
{\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})}
which can also be expressed in a general formula:
l
i
k
=
1
l
k
k
(
a
i
k
−
∑
j
=
1
k
−
1
l
i
j
l
k
j
)
{\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)}
Task description
The task is to implement a routine which will return a lower Cholesky factor
L
{\displaystyle L}
for every given symmetric, positive definite nxn matrix
A
{\displaystyle A}
. You should then test it on the following two examples and include your output.
Example 1:
25 15 -5 5 0 0
15 18 0 --> 3 3 0
-5 0 11 -1 1 3
Example 2:
18 22 54 42 4.24264 0.00000 0.00000 0.00000
22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000
54 86 174 134 12.72792 3.04604 1.64974 0.00000
42 62 134 106 9.89949 1.62455 1.84971 1.39262
Note
The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cholesky
{
class Program
{
/// <summary>
/// This is example is written in C#, and compiles with .NET Framework 4.0
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
double[,] test1 = new double[,]
{
{25, 15, -5},
{15, 18, 0},
{-5, 0, 11},
};
double[,] test2 = new double[,]
{
{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106},
};
double[,] chol1 = Cholesky(test1);
double[,] chol2 = Cholesky(test2);
Console.WriteLine("Test 1: ");
Print(test1);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 1: ");
Print(chol1);
Console.WriteLine("");
Console.WriteLine("Test 2: ");
Print(test2);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 2: ");
Print(chol2);
}
public static void Print(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
{
string s = "";
for (int c = 0; c < n; c++)
{
s += a[r, c].ToString("f5").PadLeft(9) + ",";
}
sb.AppendLine(s);
}
Console.WriteLine(sb.ToString());
}
/// <summary>
/// Returns the lower Cholesky Factor, L, of input matrix A.
/// Satisfies the equation: L*L^T = A.
/// </summary>
/// <param name="a">Input matrix must be square, symmetric,
/// and positive definite. This method does not check for these properties,
/// and may produce unexpected results of those properties are not met.</param>
/// <returns></returns>
public static double[,] Cholesky(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
double[,] ret = new double[n, n];
for (int r = 0; r < n; r++)
for (int c = 0; c <= r; c++)
{
if (c == r)
{
double sum = 0;
for (int j = 0; j < c; j++)
{
sum += ret[c, j] * ret[c, j];
}
ret[c, c] = Math.Sqrt(a[c, c] - sum);
}
else
{
double sum = 0;
for (int j = 0; j < c; j++)
sum += ret[r, j] * ret[c, j];
ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);
}
}
return ret;
}
}
} |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;
procedure Test_tty is
begin
if Isatty(Fileno(Stdin)) = 0 then
Put_Line(Standard_Error, "stdin is not a tty.");
else
Put_Line(Standard_Error, "stdin is a tty.");
end if;
end Test_tty; |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #BaCon | BaCon | terminal = isatty(0)
PRINT terminal |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #C | C | #include <unistd.h> //for isatty()
#include <stdio.h> //for fileno()
int main(void)
{
puts(isatty(fileno(stdin))
? "stdin is tty"
: "stdin is not tty");
return 0;
} |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, and Bernard the day (of the month) of birth.
1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
3) Albert: Then I also know when Cheryl's birthday is.
Task
Write a computer program to deduce, by successive elimination, Cheryl's birthday.
Related task
Sum and Product Puzzle
References
Wikipedia article of the same name.
Tuple Relational Calculus
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
property M : 1 -- Month
property D : 2 -- Day
on run
-- The MONTH with only one remaining day
-- among the DAYs with unique months,
-- EXCLUDING months with unique days,
-- in Cheryl's list:
showList(uniquePairing(M, ¬
uniquePairing(D, ¬
monthsWithUniqueDays(false, ¬
map(composeList({tupleFromList, |words|, toLower}), ¬
splitOn(", ", ¬
"May 15, May 16, May 19, June 17, June 18, " & ¬
"July 14, July 16, Aug 14, Aug 15, Aug 17"))))))
--> "[('july', '16')]"
end run
-- QUERY FUNCTIONS ----------------------------------------
-- monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]
on monthsWithUniqueDays(blnInclude, xs)
set _months to map(my fst, uniquePairing(D, xs))
script uniqueDay
on |λ|(md)
set bln to elem(fst(md), _months)
if blnInclude then
bln
else
not bln
end if
end |λ|
end script
filter(uniqueDay, xs)
end monthsWithUniqueDays
-- uniquePairing :: DatePart -> [(M, D)] -> [(M, D)]
on uniquePairing(dp, xs)
script go
property f : my mReturn(item dp of {my fst, my snd})
on |λ|(md)
set dct to f's |λ|(md)
script unique
on |λ|(k)
set mb to lookupDict(k, dct)
if Nothing of mb then
false
else
1 = length of (Just of mb)
end if
end |λ|
end script
set uniques to filter(unique, keys(dct))
script found
on |λ|(tpl)
elem(f's |λ|(tpl), uniques)
end |λ|
end script
filter(found, xs)
end |λ|
end script
bindPairs(xs, go)
end uniquePairing
-- bindPairs :: [(M, D)] -> ((Dict Text [Text], Dict Text [Text])
-- -> [(M, D)]) -> [(M, D)]
on bindPairs(xs, f)
tell mReturn(f)
|λ|(Tuple(dictFromPairs(xs), ¬
dictFromPairs(map(my swap, xs))))
end tell
end bindPairs
-- dictFromPairs :: [(M, D)] -> Dict Text [Text]
on dictFromPairs(mds)
set gps to groupBy(|on|(my eq, my fst), ¬
sortBy(comparing(my fst), mds))
script kv
on |λ|(gp)
Tuple(fst(item 1 of gp), map(my snd, gp))
end |λ|
end script
mapFromList(map(kv, gps))
end dictFromPairs
-- LIBRARY GENERICS ---------------------------------------
-- comparing :: (a -> b) -> (a -> a -> Ordering)
on comparing(f)
script
on |λ|(a, b)
tell mReturn(f)
set fa to |λ|(a)
set fb to |λ|(b)
if fa < fb then
-1
else if fa > fb then
1
else
0
end if
end tell
end |λ|
end script
end comparing
-- composeList :: [(a -> a)] -> (a -> a)
on composeList(fs)
script
on |λ|(x)
script
on |λ|(f, a)
mReturn(f)'s |λ|(a)
end |λ|
end script
foldr(result, x, fs)
end |λ|
end script
end composeList
-- drop :: Int -> [a] -> [a]
-- drop :: Int -> String -> String
on drop(n, xs)
set c to class of xs
if c is not script then
if c is not string then
if n < length of xs then
items (1 + n) thru -1 of xs
else
{}
end if
else
if n < length of xs then
text (1 + n) thru -1 of xs
else
""
end if
end if
else
take(n, xs) -- consumed
return xs
end if
end drop
-- dropAround :: (a -> Bool) -> [a] -> [a]
-- dropAround :: (Char -> Bool) -> String -> String
on dropAround(p, xs)
dropWhile(p, dropWhileEnd(p, xs))
end dropAround
-- dropWhile :: (a -> Bool) -> [a] -> [a]
-- dropWhile :: (Char -> Bool) -> String -> String
on dropWhile(p, xs)
set lng to length of xs
set i to 1
tell mReturn(p)
repeat while i ≤ lng and |λ|(item i of xs)
set i to i + 1
end repeat
end tell
drop(i - 1, xs)
end dropWhile
-- dropWhileEnd :: (a -> Bool) -> [a] -> [a]
-- dropWhileEnd :: (Char -> Bool) -> String -> String
on dropWhileEnd(p, xs)
set i to length of xs
tell mReturn(p)
repeat while i > 0 and |λ|(item i of xs)
set i to i - 1
end repeat
end tell
take(i, xs)
end dropWhileEnd
-- elem :: Eq a => a -> [a] -> Bool
on elem(x, xs)
considering case
xs contains x
end considering
end elem
-- enumFromToInt :: Int -> Int -> [Int]
on enumFromToInt(M, n)
if M ≤ n then
set lst to {}
repeat with i from M to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromToInt
-- eq (==) :: Eq a => a -> a -> Bool
on eq(a, b)
a = b
end eq
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- foldr :: (a -> b -> b) -> b -> [a] -> b
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
-- fst :: (a, b) -> a
on fst(tpl)
if class of tpl is record then
|1| of tpl
else
item 1 of tpl
end if
end fst
-- Typical usage: groupBy(on(eq, f), xs)
-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
on groupBy(f, xs)
set mf to mReturn(f)
script enGroup
on |λ|(a, x)
if length of (active of a) > 0 then
set h to item 1 of active of a
else
set h to missing value
end if
if h is not missing value and mf's |λ|(h, x) then
{active:(active of a) & {x}, sofar:sofar of a}
else
{active:{x}, sofar:(sofar of a) & {active of a}}
end if
end |λ|
end script
if length of xs > 0 then
set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, rest of xs)
if length of (active of dct) > 0 then
sofar of dct & {active of dct}
else
sofar of dct
end if
else
{}
end if
end groupBy
-- insertMap :: Dict -> String -> a -> Dict
on insertMap(rec, k, v)
tell (current application's NSMutableDictionary's ¬
dictionaryWithDictionary:rec)
its setValue:v forKey:(k as string)
return it as record
end tell
end insertMap
-- intercalateS :: String -> [String] -> String
on intercalateS(sep, xs)
set {dlm, my text item delimiters} to {my text item delimiters, sep}
set s to xs as text
set my text item delimiters to dlm
return s
end intercalateS
-- Just :: a -> Maybe a
on Just(x)
{type:"Maybe", Nothing:false, Just:x}
end Just
-- keys :: Dict -> [String]
on keys(rec)
(current application's NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list
end keys
-- lookupDict :: a -> Dict -> Maybe b
on lookupDict(k, dct)
set ca to current application
set v to (ca's NSDictionary's dictionaryWithDictionary:dct)'s objectForKey:k
if v ≠ missing value then
Just(item 1 of ((ca's NSArray's arrayWithObject:v) as list))
else
Nothing()
end if
end lookupDict
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- mapFromList :: [(k, v)] -> Dict
on mapFromList(kvs)
set tpl to unzip(kvs)
script
on |λ|(x)
x as string
end |λ|
end script
(current application's NSDictionary's ¬
dictionaryWithObjects:(|2| of tpl) ¬
forKeys:map(result, |1| of tpl)) as record
end mapFromList
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Nothing :: Maybe a
on Nothing()
{type:"Maybe", Nothing:true}
end Nothing
-- e.g. sortBy(|on|(compare, |length|), ["epsilon", "mu", "gamma", "beta"])
-- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
on |on|(f, g)
script
on |λ|(a, b)
tell mReturn(g) to set {va, vb} to {|λ|(a), |λ|(b)}
tell mReturn(f) to |λ|(va, vb)
end |λ|
end script
end |on|
-- partition :: predicate -> List -> (Matches, nonMatches)
-- partition :: (a -> Bool) -> [a] -> ([a], [a])
on partition(f, xs)
tell mReturn(f)
set ys to {}
set zs to {}
repeat with x in xs
set v to contents of x
if |λ|(v) then
set end of ys to v
else
set end of zs to v
end if
end repeat
end tell
Tuple(ys, zs)
end partition
-- show :: a -> String
on show(e)
set c to class of e
if c = list then
showList(e)
else if c = record then
set mb to lookupDict("type", e)
if Nothing of mb then
showDict(e)
else
script
on |λ|(t)
if "Either" = t then
set f to my showLR
else if "Maybe" = t then
set f to my showMaybe
else if "Ordering" = t then
set f to my showOrdering
else if "Ratio" = t then
set f to my showRatio
else if class of t is text and t begins with "Tuple" then
set f to my showTuple
else
set f to my showDict
end if
tell mReturn(f) to |λ|(e)
end |λ|
end script
tell result to |λ|(Just of mb)
end if
else if c = date then
"\"" & showDate(e) & "\""
else if c = text then
"'" & e & "'"
else if (c = integer or c = real) then
e as text
else if c = class then
"null"
else
try
e as text
on error
("«" & c as text) & "»"
end try
end if
end show
-- showList :: [a] -> String
on showList(xs)
"[" & intercalateS(", ", map(my show, xs)) & "]"
end showList
-- showTuple :: Tuple -> String
on showTuple(tpl)
set ca to current application
script
on |λ|(n)
set v to (ca's NSDictionary's dictionaryWithDictionary:tpl)'s objectForKey:(n as string)
if v ≠ missing value then
unQuoted(show(item 1 of ((ca's NSArray's arrayWithObject:v) as list)))
else
missing value
end if
end |λ|
end script
"(" & intercalateS(", ", map(result, enumFromToInt(1, length of tpl))) & ")"
end showTuple
-- snd :: (a, b) -> b
on snd(tpl)
if class of tpl is record then
|2| of tpl
else
item 2 of tpl
end if
end snd
-- Enough for small scale sorts.
-- Use instead sortOn :: Ord b => (a -> b) -> [a] -> [a]
-- which is equivalent to the more flexible sortBy(comparing(f), xs)
-- and uses a much faster ObjC NSArray sort method
-- sortBy :: (a -> a -> Ordering) -> [a] -> [a]
on sortBy(f, xs)
if length of xs > 1 then
set h to item 1 of xs
set f to mReturn(f)
script
on |λ|(x)
f's |λ|(x, h) ≤ 0
end |λ|
end script
set lessMore to partition(result, rest of xs)
sortBy(f, |1| of lessMore) & {h} & ¬
sortBy(f, |2| of lessMore)
else
xs
end if
end sortBy
-- splitOn :: String -> String -> [String]
on splitOn(pat, src)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, pat}
set xs to text items of src
set my text item delimiters to dlm
return xs
end splitOn
-- swap :: (a, b) -> (b, a)
on swap(ab)
if class of ab is record then
Tuple(|2| of ab, |1| of ab)
else
{item 2 of ab, item 1 of ab}
end if
end swap
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to xs's |λ|()
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- toLower :: String -> String
on toLower(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- tupleFromList :: [a] -> (a, a ...)
on tupleFromList(xs)
set lng to length of xs
if 1 < lng then
if 2 < lng then
set strSuffix to lng as string
else
set strSuffix to ""
end if
script kv
on |λ|(a, x, i)
insertMap(a, (i as string), x)
end |λ|
end script
foldl(kv, {type:"Tuple" & strSuffix}, xs) & {length:lng}
else
missing value
end if
end tupleFromList
-- unQuoted :: String -> String
on unQuoted(s)
script p
on |λ|(x)
--{34, 39} contains id of x
34 = id of x
end |λ|
end script
dropAround(p, s)
end unQuoted
-- unzip :: [(a,b)] -> ([a],[b])
on unzip(xys)
set xs to {}
set ys to {}
repeat with xy in xys
set end of xs to |1| of xy
set end of ys to |2| of xy
end repeat
return Tuple(xs, ys)
end unzip
-- words :: String -> [String]
on |words|(s)
set ca to current application
(((ca's NSString's stringWithString:(s))'s ¬
componentsSeparatedByCharactersInSet:(ca's ¬
NSCharacterSet's whitespaceAndNewlineCharacterSet()))'s ¬
filteredArrayUsingPredicate:(ca's ¬
NSPredicate's predicateWithFormat:"0 < length")) as list
end |words| |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #C.2B.2B | C++ | #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
} |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Elixir | Elixir | empty_list = []
list = [1,2,3,4,5]
length(list) #=> 5
[0 | list] #=> [0,1,2,3,4,5]
hd(list) #=> 1
tl(list) #=> [2,3,4,5]
Enum.at(list,3) #=> 4
list ++ [6,7] #=> [1,2,3,4,5,6,7]
list -- [4,2] #=> [1,3,5] |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Lobster | Lobster | import std
// combi is an itertor that solves the Combinations problem for iota arrays as stated
def combi(m, n, f):
let c = map(n): _
while true:
f(c)
var i = n-1
c[i] = c[i] + 1
if c[i] > m - 1:
while c[i] >= m - n + i:
i -= 1
if i < 0: return
c[i] = c[i] + 1
while i < n-1:
c[i+1] = c[i] + 1
i += 1
combi(5, 3): print(_) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #PureBasic | PureBasic | If a = 0
Debug "a = 0"
ElseIf a > 0
Debug "a > 0"
Else
Debug "a < 0"
EndIf |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #AWK | AWK | # Usage: GAWK -f CHINESE_REMAINDER_THEOREM.AWK
BEGIN {
len = split("3 5 7", n)
len = split("2 3 2", a)
printf("%d\n", chineseremainder(n, a, len))
}
function chineseremainder(n, a, len, p, i, prod, sum) {
prod = 1
sum = 0
for (i = 1; i <= len; i++)
prod *= n[i]
for (i = 1; i <= len; i++) {
p = prod / n[i]
sum += a[i] * mulinv(p, n[i]) * p
}
return sum % prod
}
function mulinv(a, b, b0, t, q, x0, x1) {
# returns x where (a * x) % b == 1
b0 = b
x0 = 0
x1 = 1
if (b == 1)
return 1
while (a > 1) {
q = int(a / b)
t = b
b = a % b
a = t
t = x0
x0 = x1 - q * x0
x1 = t
}
if (x1 < 0)
x1 += b0
return x1
} |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #PARI.2FGP | PARI/GP |
cherCar(n)={
my(C=vector(n));C[1]=6; C[2]=12; for(g=3,n,C[g]=2^(g-2)*9);
my(i=1); my(N(g)=while(i<=n&ispseudoprime(g*C[i]+1),i=i+1); return(i>n));
i=1; my(G(g)=while(i<=n&isprime(g*C[i]+1),i=i+1); return(i>n));
i=1; if(n>4,i=2^(n-4)); if(n>5,i=i*5); my(m=i); while(!(N(m)&G(m)),m=m+i);
printf("cherCar(%d): m = %d\n",n,m)}
for(x=3,9,cherCar(x))
|
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #D | D | import std.stdio;
int chowla(int n) {
int sum;
for (int i = 2, j; i * i <= n; ++i) {
if (n % i == 0) {
sum += i + (i == (j = n / i) ? 0 : j);
}
}
return sum;
}
bool[] sieve(int limit) {
// True denotes composite, false denotes prime.
// Only interested in odd numbers >= 3
auto c = new bool[limit];
for (int i = 3; i * 3 < limit; i += 2) {
if (!c[i] && (chowla(i) == 0)) {
for (int j = 3 * i; j < limit; j += 2 * i) {
c[j] = true;
}
}
}
return c;
}
void main() {
foreach (i; 1..38) {
writefln("chowla(%d) = %d", i, chowla(i));
}
int count = 1;
int limit = cast(int)1e7;
int power = 100;
bool[] c = sieve(limit);
for (int i = 3; i < limit; i += 2) {
if (!c[i]) {
count++;
}
if (i == power - 1) {
writefln("Count of primes up to %10d = %d", power, count);
power *= 10;
}
}
count = 0;
limit = 350_000_000;
int k = 2;
int kk = 3;
int p;
for (int i = 2; ; ++i) {
p = k * kk;
if (p > limit) {
break;
}
if (chowla(p) == p - 1) {
writefln("%10d is a number that is perfect", p);
count++;
}
k = kk + 1;
kk += k;
}
writefln("There are %d perfect numbers <= 35,000,000", count);
} |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #jq | jq | def church(f; $x; $m):
if $m == 0 then .
elif $m == 1 then $x|f
else church(f; $x; $m - 1)
end; |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #Julia | Julia |
id(x) = x -> x
zero() = x -> id(x)
add(m) = n -> (f -> (x -> n(f)(m(f)(x))))
mult(m) = n -> (f -> (x -> n(m(f))(x)))
exp(m) = n -> n(m)
succ(i::Int) = i + 1
succ(cn) = f -> (x -> f(cn(f)(x)))
church2int(cn) = cn(succ)(0)
int2church(n) = n < 0 ? throw("negative Church numeral") : (n == 0 ? zero() : succ(int2church(n - 1)))
function runtests()
church3 = int2church(3)
church4 = int2church(4)
println("Church 3 + Church 4 = ", church2int(add(church3)(church4)))
println("Church 3 * Church 4 = ", church2int(mult(church3)(church4)))
println("Church 4 ^ Church 3 = ", church2int(exp(church4)(church3)))
println("Church 3 ^ Church 4 = ", church2int(exp(church3)(church4)))
end
runtests()
|
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #DWScript | DWScript | type
TMyClass = class
private
FSomeField: Integer; // by convention, fields are usually private and exposed as properties
public
constructor Create;
begin
FSomeField := -1;
end;
procedure SomeMethod;
property SomeField: Integer read FSomeField write FSomeField;
end;
procedure TMyClass.SomeMethod;
begin
// do something
end;
var lMyClass: TMyClass;
lMyClass := new TMyClass; // can also use TMyClass.Create
lMyClass.SomeField := 99;
lMyClass.SomeMethod; |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #REXX | REXX | /*REXX program displays a (non-negative 4-digit) integer in Cistercian (monk) numerals.*/
parse arg m /*obtain optional arguments from the CL*/
if m='' | m="," then m= 0 1 20 300 4000 5555 6789 9393 /*Not specified? Use defaults.*/
$.=; nnn= words(m)
do j=1 for nnn; z= word(m, j) /*process each of the numbers. */
if \datatype(z, 'W') then call serr "number isn't numeric: " z
if \datatype(z, 'N') then call serr "number isn't an integer: " z
z= z / 1 /*normalize the number: 006 5.0 +4 */
if z<0 then call serr "number can't be negative: " z
if z>9999 then call serr "number is too large (>9,999): " z
call monk z / 1 /*create the Cistercian quad numeral. */
end /*j*/
call show /*display " " " " */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: parse arg @x,@y; return @.@x.@y /*return a value from the point (@x,@y)*/
quad: parse arg #; if #\==0 then interpret 'call' #; return /*build a numeral.*/
serr: say '***error*** ' arg(1); exit 13 /*issue error msg.*/
app: do r= 9 for 10 by -1; do c=-5 for 11; $.r= $.r||@.c.r; end; $.r=$.r b5; end; return
eye: do a=0 for 10; @.0.a= '│'; end; return /*build an "eye" glyph (vertical axis).*/
p: do k=1 by 3 until k>arg(); x= arg(k); y= arg(k+1); @.x.y= arg(k+2); end; return
sect: do q=1 for 4; call quad s.q; end; return /*build a Cistercian numeral character.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
monk: parse arg n; n= right(n, 4, 0); @.= ' ' /*zero─fill N; blank─out numeral grid.*/
b4= left('', 4); b5= b4" "; $.11= $.11 || b4 || n || b4 || b5; call eye
parse var n s.4 2 s.3 3 s.2 4 s.1; call sect; call nice; call app; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
nice: if @(-1, 9)=='─' then call p 0, 9, "┐"; if @(1,9)=='─' then call p 0, 9, "┌"
if @(-1, 9)=='─' & @(1,9)=='─' then call p 0, 9, "┬"
if @(-1, 0)=='─' then call p 0, 0, "┘"; if @(1,0)=='─' then call p 0, 0, "└"
if @(-1, 0)=='─' & @(1,0)=='─' then call p 0, 0, "┴"
do i=4 to 5
if @(-1, i)=='─' then call p 0, i, "┤"; if @(1,i)=='─' then call p 0, i, "├"
if @(-1, i)=='─' & @(1,i)=="─" then call p 0, i, "┼"
end /*i*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do jj= 11 for 10+2 by -1; say strip($.jj, 'T') /*display 1 row at a time.*/
if jj==5 then do 3; say strip( copies(b5'│'b5 b5, nnn), 'T'); end
end /*r*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
1: ?= '─'; if q==1 then call p 1, 9, ?, 2, 9, ?, 3, 9, ?, 4, 9, ?, 5, 9, ?
if q==2 then call p -1, 9, ?, -2, 9, ?, -3, 9, ?, -4, 9, ?, -5, 9, ?
if q==3 then call p 1, 0, ?, 2, 0, ?, 3, 0, ?, 4, 0, ?, 5, 0, ?
if q==4 then call p -1, 0, ?, -2, 0, ?, -3, 0, ?, -4, 0, ?, -5, 0, ?; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
2: ?= '─'; if q==1 then call p 1, 5, ?, 2, 5, ?, 3, 5, ?, 4, 5, ?, 5, 5, ?
if q==2 then call p -1, 5, ?, -2, 5, ?, -3, 5, ?, -4, 5, ?, -5, 5, ?
if q==3 then call p 1, 4, ?, 2, 4, ?, 3, 4, ?, 4, 4, ?, 5, 4, ?
if q==4 then call p -1, 4, ?, -2, 4, ?, -3, 4, ?, -4, 4, ?, -5, 4, ?; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
3: ?= '\'; if q==1 then call p 1, 9, ?, 2, 8, ?, 3, 7, ?, 4, 6, ?, 5, 5, ?
?= '/'; if q==2 then call p -1, 9, ?, -2, 8, ?, -3, 7, ?, -4, 6, ?, -5, 5, ?
?= '/'; if q==3 then call p 1, 0, ?, 2, 1, ?, 3, 2, ?, 4, 3, ?, 5, 4, ?
?= '\'; if q==4 then call p -5, 4, ?, -4, 3, ?, -3, 2, ?, -2, 1, ?, -1, 0, ?; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
4: ?= '/'; if q==1 then call p 1, 5, ?, 2, 6, ?, 3, 7, ?, 4, 8, ?, 5, 9, ?
?= '\'; if q==2 then call p -5, 9, ?, -4, 8, ?, -3, 7, ?, -2, 6, ?, -1, 5, ?
?= '\'; if q==3 then call p 1, 4, ?, 2, 3, ?, 3, 2, ?, 4, 1, ?, 5, 0, ?
?= '/'; if q==4 then call p -5, 0, ?, -4, 1, ?, -3, 2, ?, -2, 3, ?, -1, 4, ?; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
5: ?= '/'; if q==1 then call p 1, 5, ?, 2, 6, ?, 3, 7, ?, 4, 8, ?
?= '\'; if q==2 then call p -4, 8, ?, -3, 7, ?, -2, 6, ?, -1, 5, ?
?= '\'; if q==3 then call p 1, 4, ?, 2, 3, ?, 3, 2, ?, 4, 1, ?
?= '/'; if q==4 then call p -4, 1, ?, -3, 2, ?, -2, 3, ?, -1, 4, ?; call 1; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
6: ?= '│'; if q==1 then call p 5, 9, ?, 5, 8, ?, 5, 7, ?, 5, 6, ?, 5, 5, ?
if q==2 then call p -5, 9, ?, -5, 8, ?, -5, 7, ?, -5, 6, ?, -5, 5, ?
if q==3 then call p 5, 0, ?, 5, 1, ?, 5, 2, ?, 5, 3, ?, 5, 4, ?
if q==4 then call p -5, 0, ?, -5, 1, ?, -5, 2, ?, -5, 3, ?, -5, 4, ?; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
7: call 1; call 6; if q==1 then call p 5, 9, '┐'
if q==2 then call p -5, 9, '┌'
if q==3 then call p 5, 0, '┘'
if q==4 then call p -5, 0, '└'; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
8: call 2; call 6; if q==1 then call p 5, 5, '┘'
if q==2 then call p -5, 5, '└'
if q==3 then call p 5, 4, '┐'
if q==4 then call p -5, 4, '┌'; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
9: call 1; call 2; call 6; if q==1 then call p 5, 5, '┘', 5, 9, "┐"
if q==2 then call p -5, 5, '└', -5, 9, "┌"
if q==3 then call p 5, 0, '┘', 5, 4, "┐"
if q==4 then call p -5, 0, '└', -5, 4, "┌"; return |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #Groovy | Groovy | class Point {
final Number x, y
Point(Number x = 0, Number y = 0) { this.x = x; this.y = y }
Number distance(Point that) { ((this.x - that.x)**2 + (this.y - that.y)**2)**0.5 }
String toString() { "{x:${x}, y:${y}}" }
} |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Nim | Nim | var funcs: seq[proc(): int] = @[]
for i in 0..9:
(proc =
let x = i
funcs.add(proc (): int = x * x))()
for i in 0..8:
echo "func[", i, "]: ", funcs[i]() |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Objeck | Objeck | use Collection.Generic;
class Capture {
function : Main(args : String[]) ~ Nil {
funcs := Vector->New()<FuncHolder<IntHolder> >;
for(i := 0; i < 10; i += 1;) {
funcs->AddBack(FuncHolder->New(\() ~ IntHolder : () => i * i)<IntHolder>);
};
each(i : funcs) {
func := funcs->Get(i)->Get()<IntHolder>;
func()->Get()->PrintLine();
};
}
}
|
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Rust | Rust | // [dependencies]
// rug = "1.8"
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n % p == 0 {
return false;
}
p += 2;
if n % p == 0 {
return false;
}
p += 4;
}
true
}
fn cycle(n: u32) -> u32 {
let mut m: u32 = n;
let mut p: u32 = 1;
while m >= 10 {
p *= 10;
m /= 10;
}
m + 10 * (n % p)
}
fn is_circular_prime(p: u32) -> bool {
if !is_prime(p) {
return false;
}
let mut p2: u32 = cycle(p);
while p2 != p {
if p2 < p || !is_prime(p2) {
return false;
}
p2 = cycle(p2);
}
true
}
fn test_repunit(digits: usize) {
use rug::{integer::IsPrime, Integer};
let repunit = "1".repeat(digits);
let bignum = Integer::from_str_radix(&repunit, 10).unwrap();
if bignum.is_probably_prime(10) != IsPrime::No {
println!("R({}) is probably prime.", digits);
} else {
println!("R({}) is not prime.", digits);
}
}
fn main() {
use rug::{integer::IsPrime, Integer};
println!("First 19 circular primes:");
let mut count = 0;
let mut p: u32 = 2;
while count < 19 {
if is_circular_prime(p) {
if count > 0 {
print!(", ");
}
print!("{}", p);
count += 1;
}
p += 1;
}
println!();
println!("Next 4 circular primes:");
let mut repunit: u32 = 1;
let mut digits: usize = 1;
while repunit < p {
repunit = 10 * repunit + 1;
digits += 1;
}
let mut bignum = Integer::from(repunit);
count = 0;
while count < 4 {
if bignum.is_probably_prime(15) != IsPrime::No {
if count > 0 {
print!(", ");
}
print!("R({})", digits);
count += 1;
}
digits += 1;
bignum = bignum * 10 + 1;
}
println!();
test_repunit(5003);
test_repunit(9887);
test_repunit(15073);
test_repunit(25031);
test_repunit(35317);
test_repunit(49081);
} |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Scala | Scala | object CircularPrimes {
def main(args: Array[String]): Unit = {
println("First 19 circular primes:")
var p = 2
var count = 0
while (count < 19) {
if (isCircularPrime(p)) {
if (count > 0) {
print(", ")
}
print(p)
count += 1
}
p += 1
}
println()
println("Next 4 circular primes:")
var repunit = 1
var digits = 1
while (repunit < p) {
repunit = 10 * repunit + 1
digits += 1
}
var bignum = BigInt.apply(repunit)
count = 0
while (count < 4) {
if (bignum.isProbablePrime(15)) {
if (count > 0) {
print(", ")
}
print(s"R($digits)")
count += 1
}
digits += 1
bignum = bignum * 10
bignum = bignum + 1
}
println()
testRepunit(5003)
testRepunit(9887)
testRepunit(15073)
testRepunit(25031)
}
def isPrime(n: Int): Boolean = {
if (n < 2) {
return false
}
if (n % 2 == 0) {
return n == 2
}
if (n % 3 == 0) {
return n == 3
}
var p = 5
while (p * p <= n) {
if (n % p == 0) {
return false
}
p += 2
if (n % p == 0) {
return false
}
p += 4
}
true
}
def cycle(n: Int): Int = {
var m = n
var p = 1
while (m >= 10) {
p *= 10
m /= 10
}
m + 10 * (n % p)
}
def isCircularPrime(p: Int): Boolean = {
if (!isPrime(p)) {
return false
}
var p2 = cycle(p)
while (p2 != p) {
if (p2 < p || !isPrime(p2)) {
return false
}
p2 = cycle(p2)
}
true
}
def testRepunit(digits: Int): Unit = {
val ru = repunit(digits)
if (ru.isProbablePrime(15)) {
println(s"R($digits) is probably prime.")
} else {
println(s"R($digits) is not prime.")
}
}
def repunit(digits: Int): BigInt = {
val ch = Array.fill(digits)('1')
BigInt.apply(new String(ch))
}
} |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #C | C | #include<stdio.h>
#include<math.h>
typedef struct{
double x,y;
}point;
double distance(point p1,point p2)
{
return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
void findCircles(point p1,point p2,double radius)
{
double separation = distance(p1,p2),mirrorDistance;
if(separation == 0.0)
{
radius == 0.0 ? printf("\nNo circles can be drawn through (%.4f,%.4f)",p1.x,p1.y):
printf("\nInfinitely many circles can be drawn through (%.4f,%.4f)",p1.x,p1.y);
}
else if(separation == 2*radius)
{
printf("\nGiven points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius %.4f",(p1.x+p2.x)/2,(p1.y+p2.y)/2,radius);
}
else if(separation > 2*radius)
{
printf("\nGiven points are farther away from each other than a diameter of a circle with radius %.4f",radius);
}
else
{
mirrorDistance =sqrt(pow(radius,2) - pow(separation/2,2));
printf("\nTwo circles are possible.");
printf("\nCircle C1 with center (%.4f,%.4f), radius %.4f and Circle C2 with center (%.4f,%.4f), radius %.4f",(p1.x+p2.x)/2 + mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 + mirrorDistance*(p2.x-p1.x)/separation,radius,(p1.x+p2.x)/2 - mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 - mirrorDistance*(p2.x-p1.x)/separation,radius);
}
}
int main()
{
int i;
point cases[] =
{ {0.1234, 0.9876}, {0.8765, 0.2345},
{0.0000, 2.0000}, {0.0000, 0.0000},
{0.1234, 0.9876}, {0.1234, 0.9876},
{0.1234, 0.9876}, {0.8765, 0.2345},
{0.1234, 0.9876}, {0.1234, 0.9876}
};
double radii[] = {2.0,1.0,2.0,0.5,0.0};
for(i=0;i<5;i++)
{
printf("\nCase %d)",i+1);
findCircles(cases[2*i],cases[2*i+1],radii[i]);
}
return 0;
}
|
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #AWK | AWK |
# syntax: GAWK -f CHINESE_ZODIAC.AWK
BEGIN {
print("year element animal aspect")
split("Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig",animal_arr,",")
split("Wood,Fire,Earth,Metal,Water",element_arr,",")
n = split("1935,1938,1968,1972,1976,1984,1985,2017",year_arr,",")
for (i=1; i<=n; i++) {
year = year_arr[i]
element = element_arr[int((year-4)%10/2)+1]
animal = animal_arr[(year-4)%12+1]
yy = (year%2 == 0) ? "Yang" : "Yin"
printf("%4d %-7s %-7s %s\n",year,element,animal,yy)
}
exit(0)
}
|
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #11l | 11l | fs:is_file(‘input.txt’)
fs:is_file(‘/input.txt’)
fs:is_dir(‘docs’)
fs:is_dir(‘/docs’) |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #COBOL | COBOL | *>
*> istty, check id fd 0 is a tty
*> Tectonics: cobc -xj istty.cob
*> echo "test" | ./istty
*>
identification division.
program-id. istty.
data division.
working-storage section.
01 rc usage binary-long.
procedure division.
sample-main.
call "isatty" using by value 0 returning rc
display "fd 0 tty: " rc
call "isatty" using by value 1 returning rc
display "fd 1 tty: " rc upon syserr
call "isatty" using by value 2 returning rc
display "fd 2 tty: " rc
goback.
end program istty. |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Common_Lisp | Common Lisp | (with-open-stream (s *standard-output*)
(format T "stdout is~:[ not~;~] a terminal~%"
(interactive-stream-p s))) |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Crystal | Crystal | File.new("testfile").tty? #=> false
File.new("/dev/tty").tty? #=> true
STDOUT.tty? #=> true |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #D | D | import std.stdio;
extern(C) int isatty(int);
void main() {
writeln("Stdout is tty: ", stdout.fileno.isatty == 1);
} |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square root of
A
{\displaystyle A}
, as described in Cholesky decomposition.
In a 3x3 example, we have to solve the following system of equations:
A
=
(
a
11
a
21
a
31
a
21
a
22
a
32
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
l
11
l
21
l
31
0
l
22
l
32
0
0
l
33
)
≡
L
L
T
=
(
l
11
2
l
21
l
11
l
31
l
11
l
21
l
11
l
21
2
+
l
22
2
l
31
l
21
+
l
32
l
22
l
31
l
11
l
31
l
21
+
l
32
l
22
l
31
2
+
l
32
2
+
l
33
2
)
{\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}}
We can see that for the diagonal elements (
l
k
k
{\displaystyle l_{kk}}
) of
L
{\displaystyle L}
there is a calculation pattern:
l
11
=
a
11
{\displaystyle l_{11}={\sqrt {a_{11}}}}
l
22
=
a
22
−
l
21
2
{\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}}
l
33
=
a
33
−
(
l
31
2
+
l
32
2
)
{\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}}
or in general:
l
k
k
=
a
k
k
−
∑
j
=
1
k
−
1
l
k
j
2
{\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}}
For the elements below the diagonal (
l
i
k
{\displaystyle l_{ik}}
, where
i
>
k
{\displaystyle i>k}
) there is also a calculation pattern:
l
21
=
1
l
11
a
21
{\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}}
l
31
=
1
l
11
a
31
{\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}}
l
32
=
1
l
22
(
a
32
−
l
31
l
21
)
{\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})}
which can also be expressed in a general formula:
l
i
k
=
1
l
k
k
(
a
i
k
−
∑
j
=
1
k
−
1
l
i
j
l
k
j
)
{\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)}
Task description
The task is to implement a routine which will return a lower Cholesky factor
L
{\displaystyle L}
for every given symmetric, positive definite nxn matrix
A
{\displaystyle A}
. You should then test it on the following two examples and include your output.
Example 1:
25 15 -5 5 0 0
15 18 0 --> 3 3 0
-5 0 11 -1 1 3
Example 2:
18 22 54 42 4.24264 0.00000 0.00000 0.00000
22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000
54 86 174 134 12.72792 3.04604 1.64974 0.00000
42 62 134 106 9.89949 1.62455 1.84971 1.39262
Note
The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. | #C.2B.2B | C++ | #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
out << std::fixed << std::setprecision(5);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(9) << a(row, column);
}
out << '\n';
}
}
template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
matrix<scalar_type> result(n, n);
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < i; ++k) {
scalar_type value = input(i, k);
for (size_t j = 0; j < k; ++j)
value -= result(i, j) * result(k, j);
result(i, k) = value/result(k, k);
}
scalar_type value = input(i, i);
for (size_t j = 0; j < i; ++j)
value -= result(i, j) * result(i, j);
result(i, i) = std::sqrt(value);
}
return result;
}
void print_cholesky_factor(const matrix<double>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Cholesky factor:\n";
print(std::cout, cholesky_factor(matrix));
}
int main() {
matrix<double> matrix1(3, 3,
{{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}});
print_cholesky_factor(matrix1);
matrix<double> matrix2(4, 4,
{{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}});
print_cholesky_factor(matrix2);
return 0;
} |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #COBOL | COBOL | *>
*> istty, check id fd 0 is a tty
*> Tectonics: cobc -xj istty.cob
*> echo "test" | ./istty
*>
identification division.
program-id. istty.
data division.
working-storage section.
01 rc usage binary-long.
procedure division.
sample-main.
call "isatty" using by value 0 returning rc
display "fd 0 tty: " rc
call "isatty" using by value 1 returning rc
display "fd 1 tty: " rc upon syserr
call "isatty" using by value 2 returning rc
display "fd 2 tty: " rc
goback.
end program istty. |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Common_Lisp | Common Lisp | (with-open-stream (s *standard-input*)
(format T "stdin is~:[ not~;~] a terminal~%"
(interactive-stream-p s))) |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Crystal | Crystal | File.new("testfile").tty? #=> false
File.new("/dev/tty").tty? #=> true
STDIN.tty? #=> true |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #D | D | import std.stdio;
extern(C) int isatty(int);
void main() {
if (isatty(0))
writeln("Input comes from tty.");
else
writeln("Input doesn't come from tty.");
} |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, and Bernard the day (of the month) of birth.
1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
3) Albert: Then I also know when Cheryl's birthday is.
Task
Write a computer program to deduce, by successive elimination, Cheryl's birthday.
Related task
Sum and Product Puzzle
References
Wikipedia article of the same name.
Tuple Relational Calculus
| #Arturo | Arturo | dates: [
[May 15] [May 16] [May 19]
[June 17] [June 18]
[July 14] [July 16]
[August 14] [August 15] [August 17]
]
print ["possible dates:" dates]
print "\n(1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too."
print "\t-> meaning: the month cannot have a unique day"
dates: filter dates 'd [
in? d\0 map select dates 'dd [
1 = size select dates 'pd -> pd\1=dd\1
] 'dd -> dd\0
]
print ["\t-> remaining:" dates]
print "\n(2) Bernard: At first I don't know when Cheryl's birthday is, but I know now."
print "\t-> meaning: the day must be unique"
dates: select dates 'd [
1 = size select dates 'pd -> pd\1=d\1
]
print ["\t-> remaining:" dates]
print "\n(3) Albert: Then I also know when Cheryl's birthday is."
print "\t-> meaning: the month must be unique"
dates: select dates 'd [
1 = size select dates 'pd -> pd\0=d\0
]
print ["\t-> remaining:" dates]
print ["\nCheryl's birthday:" first dates] |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #Clojure | Clojure | (ns checkpoint.core
(:gen-class)
(:require [clojure.core.async :as async :refer [go <! >! <!! >!! alts! close!]]
[clojure.string :as string]))
(defn coordinate [ctl-ch resp-ch combine]
(go
(<! (async/timeout 2000)) ;delay a bit to allow worker setup
(loop [members {}, received {}] ;maps by in-channel of out-channels & received data resp.
(let [rcvd-count (count received)
release #(doseq [outch (vals members)] (go (>! outch %)))
received (if (and (pos? rcvd-count) (= rcvd-count (count members)))
(do (-> received vals combine release) {})
received)
[v ch] (alts! (cons ctl-ch (keys members)))]
;receive a message on ctrl-ch or any member input channel
(if (= ch ctl-ch)
(let [[op inch outch] v] ;only a Checkpoint (see below) sends on ctl-ch
(condp = op
:join (do (>! resp-ch :ok)
(recur (assoc members inch outch) received))
:part (do (>! resp-ch :ok)
(close! inch) (close! outch)
(recur (dissoc members inch) (dissoc received inch)))
:exit :exit))
(if (nil? v) ;is the channel closed?
(do
(close! (get members ch))
(recur (dissoc members ch) (dissoc received ch)))
(recur members (assoc received ch v))))))))
(defprotocol ICheckpoint
(join [this])
(part [this inch outch]))
(deftype Checkpoint [ctl-ch resp-ch sync]
ICheckpoint
(join [this]
(let [inch (async/chan), outch (async/chan 1)]
(go
(>! ctl-ch [:join inch outch])
(<! resp-ch)
[inch outch])))
(part [this inch outch]
(go
(>! ctl-ch [:part inch outch]))))
(defn checkpoint [combine]
(let [ctl-ch (async/chan), resp-ch (async/chan 1)]
(->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine))))
(defn worker
([ckpt repeats] (worker ckpt repeats (fn [& args] nil)))
([ckpt repeats mon]
(go
(let [[send recv] (<! (join ckpt))]
(doseq [n (range repeats)]
(<! (async/timeout (rand-int 5000)))
(>! send n) (mon "sent" n)
(<! recv) (mon "recvd"))
(part ckpt send recv)))))
(defn -main
[& args]
(let [ckpt (checkpoint identity)
monitor (fn [id]
(fn [& args] (println (apply str "worker" id ":" (string/join " " args)))))]
(worker ckpt 10 (monitor 1))
(worker ckpt 10 (monitor 2))))
|
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Factor | Factor | USING: assocs deques dlists lists lists.lazy sequences sets ;
! ===fixed-size sequences===
{ 1 2 "foo" 3 } ! array
[ 1 2 3 + * ] ! quotation
"Hello, world!" ! string
B{ 1 2 3 } ! byte array
?{ f t t } ! bit array
! Add an element to a fixed-size sequence
{ 1 2 3 } 4 suffix ! { 1 2 3 4 }
! Append a sequence to a fixed-size sequence
{ 1 2 3 } { 4 5 6 } append ! { 1 2 3 4 5 6 }
! Sequences are sets
{ 1 1 2 3 } { 2 5 7 8 } intersect ! { 2 }
! Strings are just arrays of code points
"Hello" { } like ! { 72 101 108 108 111 }
{ 72 101 108 108 111 } "" like ! "Hello"
! ===resizable sequences===
V{ 1 2 "foo" 3 } ! vector
BV{ 1 2 255 } ! byte vector
SBUF" Hello, world!" ! string buffer
! Add an element to a resizable sequence by mutation
V{ 1 2 3 } 4 suffix! ! V{ 1 2 3 4 }
! Append a sequence to a resizable sequence by mutation
V{ 1 2 3 } { 4 5 6 } append! ! V{ 1 2 3 4 5 6 }
! Sequences are stacks
V{ 1 2 3 } pop ! 3
! ===associative mappings===
{ { "hamburger" 150 } { "soda" 99 } { "fries" 99 } } ! alist
H{ { 1 "a" } { 2 "b" } } ! hash table
! Add a key-value pair to an assoc
3 "c" H{ { 1 "a" } { 2 "b" } } [ set-at ] keep
! H{ { 1 "a" } { 2 "b" } { "c" 3 } }
! ===linked lists===
T{ cons-state f 1 +nil+ } ! literal list syntax
T{ cons-state { car 1 } { cdr +nil+ } } ! literal list syntax
! with car 1 and cdr nil
! One method of manually constructing a list
1 2 3 4 +nil+ cons cons cons cons
1 2 2list ! convenience word for list construction
! T{ cons-state
! { car 1 }
! { cdr T{ cons-state { car 2 } { cdr +nil+ } } }
! }
{ 1 2 3 4 } sequence>list ! make a list from a sequence
0 lfrom ! a lazy list from 0 to infinity
0 [ 2 + ] lfrom-by ! a lazy list of all even numbers >= 0.
DL{ 1 2 3 } ! double linked list / deque
3 DL{ 1 2 } [ push-front ] keep ! DL{ 3 1 2 }
3 DL{ 1 2 } [ push-back ] keep ! DL{ 1 2 3 }
! Factor also comes with disjoint sets, interval maps, heaps,
! boxes, directed graphs, locked I/O buffers, trees, and more! |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Logo | Logo | to comb :n :list
if :n = 0 [output [[]]]
if empty? :list [output []]
output sentence map [sentence first :list ?] comb :n-1 bf :list ~
comb :n bf :list
end
print comb 3 [0 1 2 3 4] |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Python | Python | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
boz() |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #Bracmat | Bracmat | ( ( mul-inv
= a b b0 q x0 x1
. !arg:(?a.?b:?b0)
& ( !b:1
| 0:?x0
& 1:?x1
& whl
' ( !a:>1
& (!b.mod$(!a.!b):?q.!x1+-1*!q*!x0.!x0)
: (?a.?b.?x0.?x1)
)
& ( !x1:<0&!b0+!x1
| !x1
)
)
)
& ( chinese-remainder
= n a as p ns ni prod sum
. !arg:(?n.?a)
& 1:?prod
& 0:?sum
& !n:?ns
& whl'(!ns:%?ni ?ns&!prod*!ni:?prod)
& !n:?ns
& !a:?as
& whl
' ( !ns:%?ni ?ns
& !as:%?ai ?as
& div$(!prod.!ni):?p
& !sum+!ai*mul-inv$(!p.!ni)*!p:?sum
)
& mod$(!sum.!prod):?arg
& !arg
)
& 3 5 7:?n
& 2 3 2:?a
& put$(str$(chinese-remainder$(!n.!a) \n))
); |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #C | C | #include <stdio.h>
// returns x where (a * x) % b == 1
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
} |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #Perl | Perl | use 5.020;
use warnings;
use ntheory qw/:all/;
use experimental qw/signatures/;
sub chernick_carmichael_factors ($n, $m) {
(6*$m + 1, 12*$m + 1, (map { (1 << $_) * 9*$m + 1 } 1 .. $n-2));
}
sub chernick_carmichael_number ($n, $callback) {
my $multiplier = ($n > 4) ? (1 << ($n-4)) : 1;
for (my $m = 1 ; ; ++$m) {
my @f = chernick_carmichael_factors($n, $m * $multiplier);
next if not vecall { is_prime($_) } @f;
$callback->(@f);
last;
}
}
foreach my $n (3..9) {
chernick_carmichael_number($n, sub (@f) { say "a($n) = ", vecprod(@f) });
} |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #Phix | Phix | with javascript_semantics
function chernick_carmichael_factors(integer n, m)
sequence res = {6*m + 1, 12*m + 1}
for i=1 to n-2 do
res &= power(2,i) * 9*m + 1
end for
return res
end function
include mpfr.e
mpz p = mpz_init()
function m_prime(atom a)
mpz_set_d(p,a)
return mpz_prime(p)
end function
function is_chernick_carmichael(integer n, m)
return iff(n==2 ? m_prime(6*m + 1) and m_prime(12*m + 1)
: m_prime(power(2,n-2) * 9*m + 1) and
is_chernick_carmichael(n-1, m))
end function
function chernick_carmichael_number(integer n)
integer m = iff(n>4 ? power(2,n-4) : 1), mm = m
while not is_chernick_carmichael(n, mm) do mm += m end while
return {chernick_carmichael_factors(n, mm),mm}
end function
for n=3 to 9 do
{sequence f, integer m} = chernick_carmichael_number(n)
mpz_set_si(p,1)
for i=1 to length(f) do
mpz_mul_d(p,p,f[i])
f[i] = sprintf("%d",f[i])
end for
printf(1,"U(%d,%d): %s = %s\n",{n,m,mpz_get_str(p),join(f," * ")})
end for
|
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #Delphi | Delphi | func chowla(n) {
var sum = 0
var i = 2
var j = 0
while i * i <= n {
if n % i == 0 {
j = n / i
var app = if i == j {
0
} else {
j
}
sum += i + app
}
i += 1
}
return sum
}
func sieve(limit) {
var c = Array.Empty(limit)
var i = 3
while i * 3 < limit {
if !c[i] && (chowla(i) == 0) {
var j = 3 * i
while j < limit {
c[j] = true
j += 2 * i
}
}
i += 2
}
return c
}
for i in 1..37 {
print("chowla(\(i)) = \(chowla(i))")
}
var count = 1
var limit = 10000000
var power = 100
var c = sieve(limit)
var i = 3
while i < limit {
if !c[i] {
count += 1
}
if i == power - 1 {
print("Count of primes up to \(power) = \(count)")
power *= 10
}
i += 2
}
count = 0
limit = 35000000
var k = 2
var kk = 3
var p
i = 2
while true {
p = k * kk
if p > limit {
break
}
if chowla(p) == p - 1 {
print("\(p) is a number that is perfect")
count += 1
}
k = kk + 1
kk += k
}
print("There are \(count) perfect numbers <= 35,000,000") |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #Dyalect | Dyalect | func chowla(n) {
var sum = 0
var i = 2
var j = 0
while i * i <= n {
if n % i == 0 {
j = n / i
var app = if i == j {
0
} else {
j
}
sum += i + app
}
i += 1
}
return sum
}
func sieve(limit) {
var c = Array.Empty(limit)
var i = 3
while i * 3 < limit {
if !c[i] && (chowla(i) == 0) {
var j = 3 * i
while j < limit {
c[j] = true
j += 2 * i
}
}
i += 2
}
return c
}
for i in 1..37 {
print("chowla(\(i)) = \(chowla(i))")
}
var count = 1
var limit = 10000000
var power = 100
var c = sieve(limit)
var i = 3
while i < limit {
if !c[i] {
count += 1
}
if i == power - 1 {
print("Count of primes up to \(power) = \(count)")
power *= 10
}
i += 2
}
count = 0
limit = 35000000
var k = 2
var kk = 3
var p
i = 2
while true {
p = k * kk
if p > limit {
break
}
if chowla(p) == p - 1 {
print("\(p) is a number that is perfect")
count += 1
}
k = kk + 1
kk += k
}
print("There are \(count) perfect numbers <= 35,000,000") |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #Lambdatalk | Lambdatalk |
{def succ {lambda {:n :f :x} {:f {:n :f :x}}}}
{def add {lambda {:n :m :f :x} {{:n :f} {:m :f :x}}}}
{def mul {lambda {:n :m :f} {:m {:n :f}}}}
{def power {lambda {:n :m} {:m :n}}}
{def church {lambda {:n} {{:n {+ {lambda {:x} {+ :x 1}}}} 0}}}
{def zero {lambda {:f :x} :x}}
{def three {succ {succ {succ zero}}}}
{def four {succ {succ {succ {succ zero}}}}}
3+4 = {church {add {three} {four}}} -> 7
3*4 = {church {mul {three} {four}}} -> 12
3^4 = {church {power {three} {four}}} -> 81
4^3 = {church {power {four} {three}}} -> 64
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.