[User]
A triangular number is a count of objects arranged into an equilateral triangle.
Much like how a square number is a count of objects arranged into a square.

The *nth* triangular number is the sum of the first **n** non-negative integers.

T

n
=

∑

k
=
1

n
k
=
1
+
2
+
3
+
⋯
+
n
{\displaystyle {\displaystyle T\_{n}=\sum \_{k=1}^{n}k=1+2+3+\dotsb +n}}

Triangular numbers may be calculated by the explicit formulas:

T

n
=

n
(
n
+
1
)
2
=

(

n
+
1
2

)
{\displaystyle {\displaystyle T\_{n}={\frac {n(n+1)}{2}}={n+1 \choose 2}}}

where

(

n
+
1
2

)
{\displaystyle {\displaystyle \textstyle {n+1 \choose 2}}}
 is the binomial coefficient "n plus one choose two".

Analogous to square roots, we may also calculate a triangular root. Numbers that have an integer triangular
root are triangular numbers.

The real triangular root of a number *x* may be found using:

n
=

8
x
+
1
−
1
2
{\displaystyle {\displaystyle n={\frac {{\sqrt {8x+1}}-1}{2}}}}

Similar to how cubic numbers are square numbers extended into a third dimension,
triangular numbers extended into a third dimension are known as tetrahedral numbers.

The *nth* tetrahedral number is the sum of the first **n** triangular numbers.

T

e

n
=

∑

k
=
1

n

T

k
{\displaystyle {\displaystyle Te\_{n}=\sum \_{k=1}^{n}T\_{k}}}

Or, may be calculated directly:

T

e

n
=

n
(
n
+
1
)
(
n
+
2
)
6
=

n

3
¯

3
!
=

(

n
+
2
3

)
{\displaystyle {\displaystyle Te\_{n}={\frac {n(n+1)(n+2)}{6}}={\frac {n^{\overline {3}}}{3!}}={\binom {n+2}{3}}}}
 (Binomial "n plus two choose three".)

One may find the real tetrahedral root of *x* using the formula:

n
=

3
x
+

9

x

2
−

1
27

3
+

3
x
−

9

x

2
−

1
27

3
−
1
{\displaystyle {\displaystyle n={\sqrt[{3}]{3x+{\sqrt {9{x^{2}}-{\frac {1}{27}}}}}}+{\sqrt[{3}]{3x-{\sqrt {9{x^{2}}-{\frac {1}{27}}}}}}-1}}

*Depending on the math precision of your particular language, may need to be rounded to the nearest 1e-16 or so.*

Extending into a fourth dimension we get pentatopic numbers.

Again, the *nth* pentatope is the sum of the first **n** tetrahedral numbers,

P

n
=

∑

k
=
1

n
T

e

k
{\displaystyle {\displaystyle P\_{n}=\sum \_{k=1}^{n}Te\_{k}}}

or explicitly:

P

n
=

n
(
n
+
1
)
(
n
+
2
)
(
n
+
3
)
24
=

(

n
+
3
4

)
{\displaystyle {\displaystyle P\_{n}={\frac {n(n+1)(n+2)(n+3)}{24}}={\binom {n+3}{4}}}}
 (Binomial "n plus three choose four".)

The pentatopic real root of *x* may be found using:

n
=

5
+
4

24
x
+
1
−
3
2
.
{\displaystyle {\displaystyle n={\frac {{\sqrt {5+4{\sqrt {24x+1}}}}-3}{2}}.}}

In general, these all belong to the class figurate numbers as they are
based on **r** dimensional geometric figures. Sometimes they are referred to as **r-simplex**
numbers. In geometry a simplex is the simplest possible **r-dimensional**
object.

You may easily extend to an arbitrary dimension **r** using binomials. Each term **n** in dimension **r** is

r

n
=

(

n
+
r
−
1
r

)
{\displaystyle {\displaystyle r\_{n}={\binom {n+r-1}{r}}}}

There is no known general formula to find higher r-simplex roots.

Task

* Find and display the first 30 triangular numbers (**r** = 2).
* Find and display the first 30 tetrahedral numbers (**r** = 3).
* Find and display the first 30 pentatopic numbers (**r** = 4).
* Find and display the first 30 12-simplex numbers (**r** = 12).
* Find and display the triangular root, the tetrahedral root, and the pentatopic root for the integers:
  + 7140
  + 21408696
  + 26728085384
  + 14545501785001

See also

* Wikipedia: Triangular numbers * Wikipedia: Tetrahedral numbers * Wikipedia: Pentatopic numbers * Wikipedia: Figurate numbers * Wikipedia: Simplex(geometry) * OEIS:A000217 - Triangular numbers: a(n) = binomial(n+1,2) * OEIS:A000292 - Tetrahedral numbers: a(n) = binomial(n+2,3) * OEIS:A000332 - Pentatope numbers: a(n) = binomial(n+3,4) * Related task: Evaluate binomial coefficients * Related task: Pascal's triangle

[Assistant]
```
use Math::Root:ver<0.0.4>;

sub binomial { [×] ($^n … 0) Z/ 1 .. $^p }

sub polytopic (Int $r, @range) { @range.map: { binomial $_ + $r - 1, $r } }

sub display (@values) {
    my $c = @values.max.chars;
    @values.batch(6)».fmt("%{$c}d").join: "\n";
}

for 2, 'triangular', 3, 'tetrahedral', 4, 'pentatopic', 12, '12-simplex'
  -> $r, $name { say "\nFirst 30 $name numbers:\n" ~ display polytopic $r, ^30 }

say '';

my \ε = FatRat.new: 1, 10**24;

for 7140, 21408696, 26728085384, 14545501785001 {
  say qq:to/R/;
  Roots of $_:
    triangular-root: {.&triangular-root.round:  ε}
   tetrahedral-root: {.&tetrahedral-root.round: ε}
    pentatopic-root: {.&pentatopic-root.round:  ε}
  R
}

```

Output:

```
First 30 triangular numbers:
  0   1   3   6  10  15
 21  28  36  45  55  66
 78  91 105 120 136 153
171 190 210 231 253 276
300 325 351 378 406 435

First 30 tetrahedral numbers:
   0    1    4   10   20   35
  56   84  120  165  220  286
 364  455  560  680  816  969
1140 1330 1540 1771 2024 2300
2600 2925 3276 3654 4060 4495

First 30 pentatopic numbers:
    0     1     5    15    35    70
  126   210   330   495   715  1001
 1365  1820  2380  3060  3876  4845
 5985  7315  8855 10626 12650 14950
17550 20475 23751 27405 31465 35960

First 30 12-simplex numbers:
         0          1         13         91        455       1820
      6188      18564      50388     125970     293930     646646
   1352078    2704156    5200300    9657700   17383860   30421755
  51895935   86493225  141120525  225792840  354817320  548354040
 834451800 1251677700 1852482996 2707475148 3910797436 5586853480

Roots of 7140:
  triangular-root: 119
 tetrahedral-root: 34
  pentatopic-root: 18.876646615928006607901783

Roots of 21408696:
  triangular-root: 6543
 tetrahedral-root: 503.56182697463651404819613
  pentatopic-root: 149.060947375265867484387575

Roots of 26728085384:
  triangular-root: 231205.405565255836957291031961
 tetrahedral-root: 5432
  pentatopic-root: 893.442456751684869888466212

Roots of 14545501785001:
  triangular-root: 5393607.158145172316497304724655
 tetrahedral-root: 44355.777384073256052620916903
  pentatopic-root: 4321
```


[User]
Task

If your language has a library or built-in functions for trigonometry, show examples of:

:   :   * sine
        * cosine
        * tangent
        * inverses   (of the above)

using the same angle in radians and degrees.

For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).

For the inverse functions,   use the same number and convert its answer to radians and degrees.

If your language does not have trigonometric functions available or only has some available,   write functions to calculate the functions based on any   known approximation or identity.

[Assistant]
(formerly Perl 6) Borrow the degree to radian routine from here.

**Works with**: Rakudo version 2020.12

```
# 20210212 Updated Raku programming solution

sub postfix:<°>    (\ᵒ) { ᵒ × τ / 360 }

sub postfix:<㎭🡆°> (\ᶜ) { ᶜ / π × 180 }

say sin π/3 ;
say sin 60° ;

say cos π/4 ;
say cos 45° ;

say tan π/6 ;
say tan 30° ;

( asin(3.sqrt/2), acos(1/sqrt 2), atan(1/sqrt 3) )».&{ .say and .㎭🡆°.say }

```

Output:

```
0.8660254037844386
0.8660254037844386
0.7071067811865476
0.7071067811865476
0.5773502691896257
0.5773502691896257
1.0471975511965976
60
0.7853981633974484
45.00000000000001
0.5235987755982989
30.000000000000004

```


[User]
Task

Numbers   **n**   such that the three numbers   **n-1**,   **n+3**,   and   **n+5**   are all prime,   where   **n < 6,000.**

[Assistant]
A weird combination of Cousin primes and Twin primes that are siblings, but known by their neighbor.... I shall dub these Alabama primes.

```
say "{.[0]+1}: ",$_ for grep *.all.is-prime, ^6000 .race.map: { $_-1, $_+3, $_+5 };

```

Output:

```
8: (7 11 13)
14: (13 17 19)
38: (37 41 43)
68: (67 71 73)
98: (97 101 103)
104: (103 107 109)
194: (193 197 199)
224: (223 227 229)
278: (277 281 283)
308: (307 311 313)
458: (457 461 463)
614: (613 617 619)
824: (823 827 829)
854: (853 857 859)
878: (877 881 883)
1088: (1087 1091 1093)
1298: (1297 1301 1303)
1424: (1423 1427 1429)
1448: (1447 1451 1453)
1484: (1483 1487 1489)
1664: (1663 1667 1669)
1694: (1693 1697 1699)
1784: (1783 1787 1789)
1868: (1867 1871 1873)
1874: (1873 1877 1879)
1994: (1993 1997 1999)
2084: (2083 2087 2089)
2138: (2137 2141 2143)
2378: (2377 2381 2383)
2684: (2683 2687 2689)
2708: (2707 2711 2713)
2798: (2797 2801 2803)
3164: (3163 3167 3169)
3254: (3253 3257 3259)
3458: (3457 3461 3463)
3464: (3463 3467 3469)
3848: (3847 3851 3853)
4154: (4153 4157 4159)
4514: (4513 4517 4519)
4784: (4783 4787 4789)
5228: (5227 5231 5233)
5414: (5413 5417 5419)
5438: (5437 5441 5443)
5648: (5647 5651 5653)
5654: (5653 5657 5659)
5738: (5737 5741 5743)
```


[User]
In algebra, a max tropical semiring (also called a max-plus algebra) is the semiring
(ℝ ∪ -Inf, ⊕, ⊗) containing the ring of real numbers ℝ augmented by negative infinity,
the max function (returns the greater of two real numbers), and addition.

In max tropical algebra, x ⊕ y = max(x, y) and x ⊗ y = x + y. The identity for ⊕
is -Inf (the max of any number with -infinity is that number), and the identity for ⊗ is 0.

Task

* Define functions or, if the language supports the symbols as operators, operators for ⊕ and ⊗ that fit the above description. If the language does not support ⊕ and ⊗ as operators but allows overloading operators for a new object type, you may instead overload + and \* for a new min tropical albrbraic type. If you cannot overload operators in the language used, define ordinary functions for the purpose.

Show that 2 ⊗ -2 is 0, -0.001 ⊕ -Inf is -0.001, 0 ⊗ -Inf is -Inf, 1.5 ⊕ -1 is 1.5, and -0.5 ⊗ 0 is -0.5.

* Define exponentiation as serial ⊗, and in general that a to the power of b is a \* b, where a is a real number and b must be a positive integer. Use either ↑ or similar up arrow or the carat ^, as an exponentiation operator if this can be used to overload such "exponentiation" in the language being used. Calculate 5 ↑ 7 using this definition.

* Max tropical algebra is distributive, so that

```
  a ⊗ (b ⊕ c) equals a ⊗ b ⊕ b ⊗ c,

```

where ⊗ has precedence over ⊕. Demonstrate that 5 ⊗ (8 ⊕ 7) equals 5 ⊗ 8 ⊕ 5 ⊗ 7.

* If the language used does not support operator overloading, you may use ordinary function names such as tropicalAdd(x, y) and tropicalMul(x, y).

See also
:   * [Tropical algebra] * [Tropical geometry review article] * [Operator overloading]

[Assistant]
No need to overload, define our own operators with whatever precedence level we want. Here we're setting precedence equivalent to existing operators.

```
sub infix:<⊕> (Real $a, Real $b) is equiv(&[+]) { $a max $b }
sub infix:<⊗> (Real $a, Real $b) is equiv(&[×]) { $a + $b }
sub infix:<↑> (Real $a,  Int $b where * ≥ 0) is equiv(&[**]) { [⊗] $a xx $b }

use Test;

is-deeply(      2 ⊗ -2,        0, '2 ⊗ -2 == 0' );
is-deeply( -0.001 ⊕ -Inf, -0.001, '-0.001 ⊕ -Inf == -0.001' );
is-deeply(      0 ⊗ -Inf,   -Inf, '0 ⊗ -Inf == -Inf' );
is-deeply(    1.5 ⊕ -1,      1.5, '1.5 ⊕ -1 == 1.5' );
is-deeply(   -0.5 ⊗ 0,      -0.5, '-0.5 ⊗ 0 == -0.5' );
is-deeply(      5 ↑ 7,        35, '5 ↑ 7 == 35' );
is-deeply( 5 ⊗ (8 ⊕ 7),  5 ⊗ 8 ⊕ 5 ⊗ 7, '5 ⊗ (8 ⊕ 7) == 5 ⊗ 8 ⊕ 5 ⊗ 7');
is-deeply( 5 ↑ 7 ⊕ 6 ↑ 6,     36, '5 ↑ 7 ⊕ 6 ↑ 6 == 36');

```

Output:

```
ok 1 - 2 ⊗ -2 == 0
ok 2 - -0.001 ⊕ -Inf == -0.001
ok 3 - 0 ⊗ -Inf == -Inf
ok 4 - 1.5 ⊕ -1 == 1.5
ok 5 - -0.5 ⊗ 0 == -0.5
ok 6 - 5 ↑ 7 == 35
ok 7 - 5 ⊗ (8 ⊕ 7) == 5 ⊗ 8 ⊕ 5 ⊗ 7
ok 8 - 5 ↑ 7 ⊕ 6 ↑ 6 == 36
```


[User]
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.

Examples

The number **997** is called a *left-truncatable prime* as the numbers **997**, **97**, and **7** are all prime.

The number **7393** is a *right-truncatable prime* as the numbers **7393**, **739**, **73**, and **7** formed by removing digits from its right are also prime.

No zeroes are allowed in truncatable primes.

Task

The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).

Related tasks

* Find largest left truncatable prime in a given base
* Sieve of Eratosthenes

See also

* Truncatable Prime from MathWorld.]

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2024.12

You May Attempt This Online.

```
constant ltp = [2, 3, 5, 7], {
    last if .not;
    [ ((1..9) X~ @$_).grep: &is-prime ]
} ... *;

constant rtp = [2, 3, 5, 7], {
    last if .not;
    [ (@$_ X~ (1,3,7,9)).grep: &is-prime ]
} ... *;

say "Largest ltp < 1e6 = ", ltp[5][*-1];
say "Largest rtp < 1e6 = ", rtp[5][*-1];
say "Largest possible ltp = ", ltp.eager.flat.tail;
say "Largest possible rtp = ", rtp.eager.flat.tail;

```

Output:

```
Largest ltp < 1e6 = 998443
Largest rtp < 1e6 = 739399
Largest possible ltp = 357686312646216567629137
Largest possible rtp = 73939133
```


[User]
Task

Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).

Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.

If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.

On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.

This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.07

```
use NativeCall;

sub truncate(Str, int32 --> int32) is native {*}

sub MAIN (Str $file, Int $to) {
    given $file.IO {
        .e        or die "$file doesn't exist";
        .w        or die "$file isn't writable";
        .s >= $to or die "$file is not big enough to truncate";
    }
    truncate($file, $to) == 0 or die "Truncation was unsuccessful";
}

```

The external `truncate` routine could be replaced with the following line (in which case no need for `NativeCall`):

```
spurt $file, slurp($file).substr($to);

```


[User]
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.

Task

1. Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function.
    (One can assume that the user input is correct).
2. Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function.
3. Either reverse-polish or infix notation expressions are allowed.

Related tasks

* Boolean values
* Ternary logic

See also

* Wolfram MathWorld entry on truth tables.
* some "truth table" examples from Google.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.01

```
use MONKEY-SEE-NO-EVAL;

sub MAIN ($x) {
    my @n = $x.comb(/<ident>/);
    my &fun = EVAL "-> {('\\' «~« @n).join(',')} \{ [{ (|@n,"so $x").join(',') }] \}";

    say (|@n,$x).join("\t");
    .join("\t").say for map &fun, flat map { .fmt("\%0{+@n}b").comb».Int».so }, 0 ..^ 2**@n;
    say '';
}

```

Output:

```
$ truthtable 'A ^ B'
A   B   A ^ B
False   False   False
False   True    True
True    False   True
True    True    False

$ truthtable 'foo & bar | baz'
foo bar baz foo & bar | baz
False   False   False   False
False   False   True    True
False   True    False   False
False   True    True    True
True    False   False   False
True    False   True    True
True    True    False   True
True    True    True    True

$ truthtable 'Jim & (Spock ^ Bones) | Scotty'
Jim Spock   Bones   Scotty  Jim & (Spock ^ Bones) | Scotty
False   False   False   False   False
False   False   False   True    True
False   False   True    False   False
False   False   True    True    True
False   True    False   False   False
False   True    False   True    True
False   True    True    False   False
False   True    True    True    True
True    False   False   False   False
True    False   False   True    True
True    False   True    False   True
True    False   True    True    True
True    True    False   False   True
True    True    False   True    True
True    True    True    False   False
True    True    True    True    True
```


[User]
Introduction

Jeff Tupper, in his 2001 paper "Reliable Two-Dimensional Graphing Methods for Mathematical Formulae with Two Free Variables", shows a set of methods to graph equations and inequalities with two variables in the cartesian plane.

One of the examples of the paper, refers to the inequality:

1
2
<

⌊

m
o
d

(

⌊

y
17
⌋

2

−
17
⌊
x
⌋
−

m
o
d

(

⌊
y
⌋
,
17
)
,
2
)
⌋
{\displaystyle {\frac {1}{2}}<\left\lfloor \mathrm {mod} \left(\left\lfloor {\frac {y}{17}}\right\rfloor 2^{-17\lfloor x\rfloor -\mathrm {mod} \left(\lfloor y\rfloor ,17\right)},2\right)\right\rfloor }

That inequality, once plotted in the range 0 ≤ x ≤ 106 and k ≤ y ≤ k + 17 for k = 960, 939, 379, 918, 958, 884, 971, 672, 962, 127, 852, 754, 715, 004, 339, 660, 129, 306, 651, 505, 519, 271, 702, 802, 395, 266, 424, 689, 642, 842, 174, 350, 718, 121, 267, 153, 782, 770, 623, 355, 993, 237, 280, 874, 144, 307, 891, 325, 963, 941, 337, 723, 487, 857, 735, 749, 823, 926, 629, 715, 517, 173, 716, 995, 165, 232, 890, 538, 221, 612, 403, 238, 855, 866, 184, 013, 235, 585, 136, 048, 828, 693, 337, 902, 491, 454, 229, 288, 667, 081, 096, 184, 496, 091, 705, 183, 454, 067, 827, 731, 551, 705, 405, 381, 627, 380, 967, 602, 565, 625, 016, 981, 482, 083, 418, 783, 163, 849, 115, 590, 225, 610, 003, 652, 351, 370, 343, 874, 461, 848, 378, 737, 238, 198, 224, 849, 863, 465, 033, 159, 410, 054, 974, 700, 593, 138, 339, 226, 497, 249, 461, 751, 545, 728, 366, 702, 369, 745, 461, 014, 655, 997, 933, 798, 537, 483, 143, 786, 841, 806, 593, 422, 227, 898, 388, 722, 980, 000, 748, 404, 719 produces a drawing that visually mimics the inequality itself, hence it is called self-referential.

Although the inequality is intended to be drawn on the continuum of the cartesian plane, the drawing can be performed iterating over the integer values of both the horizontal and vertical ranges.

Task

Make a drawing of the Tupper's formula, either using text, a matrix or creating an image.

This task requires arbitrary precision integer operations. If your language does not intrinsically support that, you can use a library.

Epilogue

The value of k is an encoding of the bitmap of the image, therefore any 17-width bitmap can be produced, using its associated encoded value as k.

References

:   * Wikipedia: Tupper's self-referential formula
    * Tupper, Jeff. "Reliable Two-Dimensional Graphing Methods for Mathematical Formulae with Two Free Variables"

[Assistant]
```
# 20240802 Raku programming solution

my ( \H, \W, \N ) = 17, 106, 4858450636189713423582095962494202044581400587983244549483093085061934704708809928450644769865524364849997247024915119110411605739177407856919754326571855442057210445735883681829823754139634338225199452191651284348332905131193199953502413758765239264874613394906870130562295813219481113685339535565290850023875092856892694555974281546386510730049106723058933586052544096664351265349363643957125565695936815184334857605266940161251266951421550539554519153785457525756590740540157929001765967965480064427829131488548259914721248506352686630476300;

for N+H-1 ... N -> \y {
   say [~] ^W .map: { (y div H) div 2**(H * $_ + y % H) % 2 ?? '█' !! ' ' }
}

```

You may Attempt This Online!


[User]
This puzzle is borrowed from   math-frolic.blogspot.

Given the following twelve statements, which of them are true?

```
 1.  This is a numbered list of twelve statements.
 2.  Exactly 3 of the last 6 statements are true.
 3.  Exactly 2 of the even-numbered statements are true.
 4.  If statement 5 is true, then statements 6 and 7 are both true.
 5.  The 3 preceding statements are all false.
 6.  Exactly 4 of the odd-numbered statements are true.
 7.  Either statement 2 or 3 is true, but not both.
 8.  If statement 7 is true, then 5 and 6 are both true.
 9.  Exactly 3 of the first 6 statements are true.
10.  The next two statements are both true.
11.  Exactly 1 of statements 7, 8 and 9 are true.
12.  Exactly 4 of the preceding statements are true.

```

Task

When you get tired of trying to figure it out in your head,
write a program to solve it, and print the correct answer or answers.

Extra credit

Print out a table of near misses, that is, solutions that are contradicted by only a single statement.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.07

```
sub infix:<→> ($protasis, $apodosis) { !$protasis or $apodosis }

my @tests =
    { .end == 12 and all(.[1..12]) === any(True, False) },
    { 3 == [+] .[7..12] },
    { 2 == [+] .[2,4...12] },
    { .[5] → all .[6,7] },
    { none .[2,3,4] },
    { 4 == [+] .[1,3...11] },
    { one .[2,3] },
    { .[7] → all .[5,6] },
    { 3 == [+] .[1..6] },
    { all .[11,12] },
    { one .[7,8,9] },
    { 4 == [+] .[1..11] },
;

my @solutions;
my @misses;

for [X] (True, False) xx 12 {
    my @assert = Nil, |$_;
    my @result = Nil, |@tests.map({ ?.(@assert) });
    my @true = @assert.grep(?*, :k);
    my @cons = (@assert Z=== @result).grep(!*, :k);
    given @cons {
        when 0 { push @solutions, "<{@true}> is consistent."; }
        when 1 { push @misses, "<{@true}> implies { "¬" if !@result[~$_] }$_." }
    }
}

.say for @solutions;
say "";
say "Near misses:";
.say for @misses;

```

Output:

```
<1 3 4 6 7 11> is consistent.

Near misses:
<1 2 4 7 8 9> implies ¬8.
<1 2 4 7 9 10> implies ¬10.
<1 2 4 7 9 12> implies ¬12.
<1 3 4 6 7 9> implies ¬9.
<1 3 4 8 9> implies 7.
<1 4 6 8 9> implies ¬6.
<1 4 8 10 11 12> implies ¬12.
<1 4> implies 8.
<1 5 6 9 11> implies 8.
<1 5 8 10 11 12> implies ¬12.
<1 5 8 11> implies 12.
<1 5 8> implies 11.
<1 5> implies 8.
<4 8 10 11 12> implies 1.
<5 8 10 11 12> implies 1.
<5 8 11> implies 1.
```


[User]
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:

:   :   1. P1   and   P2   are primes
        2. P1  +  **2**   =   P2

Task

Write a program that displays the number of **pairs of twin primes** that can be found under a user-specified number

(P1 < *user-specified number* & P2 < *user-specified number*).

Extension
:   :   1. Find all twin prime pairs under 100000, 10000000 and 1000000000.
        2. What is the time complexity of the program? Are there ways to reduce computation time?

Examples

```
> Search Size: 100
> 8 twin prime pairs.

```

```
> Search Size: 1000
> 35 twin prime pairs.

```

Also see

* The OEIS entry: A001097: Twin primes.
* The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.
* The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.
* The OEIS entry: A007508: Number of twin prime pairs below 10^n.

[Assistant]
**Works with**: Rakudo version 2020.07

```
use Lingua::EN::Numbers;

use Math::Primesieve;

my $p = Math::Primesieve.new;

printf "Twin prime pairs less than %17s: %s\n", comma(10**$_), comma $p.count(10**$_, :twins) for 1 .. 12;
say (now - INIT now).round(.01) ~ ' seconds';

```

Output:

```
Twin prime pairs less than                10: 2
Twin prime pairs less than               100: 8
Twin prime pairs less than             1,000: 35
Twin prime pairs less than            10,000: 205
Twin prime pairs less than           100,000: 1,224
Twin prime pairs less than         1,000,000: 8,169
Twin prime pairs less than        10,000,000: 58,980
Twin prime pairs less than       100,000,000: 440,312
Twin prime pairs less than     1,000,000,000: 3,424,506
Twin prime pairs less than    10,000,000,000: 27,412,679
Twin prime pairs less than   100,000,000,000: 224,376,048
Twin prime pairs less than 1,000,000,000,000: 1,870,585,220
6.89 seconds
```


[User]
Task

Write a program that displays twin primes under 10.000.000 whose sum is a square number.

[Assistant]
Updated for updated task requirements. Trivial to find the squares that are sums of twin primes less than 1e7. (First 69.) Also find the largest square less than 1e12 (#4288) (Not sure why, but that seems to be a popular "stretch" task, and the largest matching *root* less than 1e7, that when squared is a sum of two twin primes. (#29,996) Added some timing info as well. Timing is going to be system dependent. This task is ridiculously parallelizable. Run on a 16 core Ryzen 7950X.

```
use List::Divvy;

my @tps = lazy (^Inf).hyper(:1000batch).map({next if $_%2; (my $s = .², $_, $s+>1)}).grep:
  {(.[2]-1).is-prime && (.[2]+1).is-prime};

{
    state $c;
    say "{++$c}: {.[1]}² ({.[0]}) == {.[2]-1} + {.[2]+1}"
} for @tps.&before({.[2] > 1e7});

say "{(now - INIT now).round(.001)} seconds elapsed\n";

{
    my $s =  @tps[$_];
    say "{1+$_}: {$s[1]}² ({$s[0]}) == {$s[2]-1} + {$s[2]+1}";
} for @tps.&before({.[0] > 1e12}).elems - 1, @tps.first({.[1] > 1e7},:k) - 1;

say "\n{(now - INIT now).round(.001)} total seconds elapsed\n";

```

Output:

```
1: 6² (36) == 17 + 19
2: 12² (144) == 71 + 73
3: 42² (1764) == 881 + 883
4: 48² (2304) == 1151 + 1153
5: 72² (5184) == 2591 + 2593
6: 84² (7056) == 3527 + 3529
7: 90² (8100) == 4049 + 4051
8: 174² (30276) == 15137 + 15139
9: 204² (41616) == 20807 + 20809
10: 264² (69696) == 34847 + 34849
11: 306² (93636) == 46817 + 46819
12: 372² (138384) == 69191 + 69193
13: 408² (166464) == 83231 + 83233
14: 456² (207936) == 103967 + 103969
15: 474² (224676) == 112337 + 112339
16: 546² (298116) == 149057 + 149059
17: 594² (352836) == 176417 + 176419
18: 600² (360000) == 179999 + 180001
19: 642² (412164) == 206081 + 206083
20: 750² (562500) == 281249 + 281251
21: 852² (725904) == 362951 + 362953
22: 882² (777924) == 388961 + 388963
23: 936² (876096) == 438047 + 438049
24: 972² (944784) == 472391 + 472393
25: 978² (956484) == 478241 + 478243
26: 1038² (1077444) == 538721 + 538723
27: 1140² (1299600) == 649799 + 649801
28: 1212² (1468944) == 734471 + 734473
29: 1272² (1617984) == 808991 + 808993
30: 1386² (1920996) == 960497 + 960499
31: 1470² (2160900) == 1080449 + 1080451
32: 1512² (2286144) == 1143071 + 1143073
33: 1518² (2304324) == 1152161 + 1152163
34: 1584² (2509056) == 1254527 + 1254529
35: 1770² (3132900) == 1566449 + 1566451
36: 1836² (3370896) == 1685447 + 1685449
37: 1902² (3617604) == 1808801 + 1808803
38: 1980² (3920400) == 1960199 + 1960201
39: 1986² (3944196) == 1972097 + 1972099
40: 2130² (4536900) == 2268449 + 2268451
41: 2196² (4822416) == 2411207 + 2411209
42: 2256² (5089536) == 2544767 + 2544769
43: 2262² (5116644) == 2558321 + 2558323
44: 2316² (5363856) == 2681927 + 2681929
45: 2382² (5673924) == 2836961 + 2836963
46: 2652² (7033104) == 3516551 + 3516553
47: 2688² (7225344) == 3612671 + 3612673
48: 2718² (7387524) == 3693761 + 3693763
49: 2772² (7683984) == 3841991 + 3841993
50: 2814² (7918596) == 3959297 + 3959299
51: 2886² (8328996) == 4164497 + 4164499
52: 2946² (8678916) == 4339457 + 4339459
53: 2988² (8928144) == 4464071 + 4464073
54: 3012² (9072144) == 4536071 + 4536073
55: 3096² (9585216) == 4792607 + 4792609
56: 3282² (10771524) == 5385761 + 5385763
57: 3366² (11329956) == 5664977 + 5664979
58: 3498² (12236004) == 6118001 + 6118003
59: 3558² (12659364) == 6329681 + 6329683
60: 3582² (12830724) == 6415361 + 6415363
61: 3738² (13972644) == 6986321 + 6986323
62: 3786² (14333796) == 7166897 + 7166899
63: 3936² (15492096) == 7746047 + 7746049
64: 3948² (15586704) == 7793351 + 7793353
65: 4032² (16257024) == 8128511 + 8128513
66: 4170² (17388900) == 8694449 + 8694451
67: 4200² (17640000) == 8819999 + 8820001
68: 4314² (18610596) == 9305297 + 9305299
69: 4416² (19501056) == 9750527 + 9750529
0.027 seconds elapsed

4288: 999684² (999368099856) == 499684049927 + 499684049929
29996: 9999450² (99989000302500) == 49994500151249 + 49994500151251

71.494 total seconds elapsed

```


[User]
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:

> A revolver handgun has a revolving cylinder with six chambers for bullets.
>
> It is loaded with the following procedure:
>
> 1. Check the first chamber to the right of the trigger for a bullet. If a bullet
> is seen, the cylinder is rotated one chamber clockwise and the next chamber
> checked until an empty chamber is found.
>
> 2. A cartridge containing a bullet is placed in the empty chamber.
>
> 3. The cylinder is then rotated one chamber clockwise.
>
> To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
> a random position from 1 to 6 chamber rotations clockwise from its starting position.
>
> When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
> counterclockwise from the loading position.
>
> The gun is unloaded by removing all cartridges from the cylinder.
>
> According to the legend, a suicidal Russian imperial military officer plays a game of Russian
> roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
> If the gun fires with a trigger pull, this is considered a successful suicide.
>
> The cylinder is always spun before the first shot, but it may or may not be spun after putting
> in the first bullet and may or may not be spun after taking the first shot.
>
> Which of the following situations produces the highest probability of suicide?
>
> A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
>
> B. Spinning the cylinder after loading the first bullet only.
>
> C. Spinning the cylinder after firing the first shot only.
>
> D. Not spinning the cylinder either after loading the first bullet or after the first shot.
>
> E. The probability is the same for all cases.

Task

1. Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
2. Show the results as a percentage of deaths for each type of scenario.
3. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.

Reference

Youtube video on the Russian 1895 Nagant revolver [[1]]

[Assistant]
```
unit sub MAIN ($shots = 6);

my @cyl;

sub load () {
    @cyl.=rotate(-1) while @cyl[1];
    @cyl[1] = 1;
    @cyl.=rotate(-1);
}

sub spin () { @cyl.=rotate: (^@cyl).pick }

sub fire () { @cyl.=rotate; @cyl[0] }

sub LSLSFSF {
    @cyl = 0 xx $shots;
    load, spin, load, spin;
    return 1 if fire;
    spin;
    fire
}

sub LSLSFF {
    @cyl = 0 xx $shots;
    load, spin, load, spin;
    fire() || fire
}

sub LLSFSF {
    @cyl = 0 xx $shots;
    load, load, spin;
    return 1 if fire;
    spin;
    fire
}

sub LLSFF {
    @cyl = 0 xx $shots;
    load, load, spin;
    fire() || fire
}

my %revolver;
my $trials = 100000;

for ^$trials {
    %revolver<LSLSFSF> += LSLSFSF;
    %revolver<LSLSFF>  += LSLSFF;
    %revolver<LLSFSF>  += LLSFSF;
    %revolver<LLSFF>   += LLSFF;
}

say "{.fmt('%7s')}: %{(%revolver{$_} / $trials × 100).fmt('%.2f')}"
  for <LSLSFSF LSLSFF LLSFSF LLSFF>

```

Sample output (default; 6 shooter):

```
LSLSFSF: %55.37
 LSLSFF: %58.30
 LLSFSF: %55.42
  LLSFF: %50.29

```

Though if you go and look at the Wikipedia article for the 1895 Nagant revolver mentioned in the task reference section, you'll see it is actually a **7** shot revolver... so, run again with 7 chambers:

`raku roulette.raku 7`

Sample output (7 shooter):

```
LSLSFSF: %49.29
 LSLSFF: %51.14
 LLSFSF: %48.74
  LLSFF: %43.08
```

Or, how about a Ruger GP100 10 round revolver?

`raku roulette.raku 10`

Sample output (10 shooter):

```
LSLSFSF: %36.00
 LSLSFF: %37.00
 LLSFSF: %36.13
  LLSFF: %29.77
```

Doesn't change the answers, B (LSLSFF) is definitely the worst most likely choice in all cases.


[User]
Task

Find and display   (here on this page)   positive integers, n, whose base 2 representation is the concatenation of two identical binary strings,

where    **n** <   1,00010 **(one thousand).**

For each such integer, show its decimal and binary forms.

[Assistant]
```
my @cat = (1..*).map: { :2([~] .base(2) xx 2) };
say "{+$_} matching numbers\n{.batch(5)».map({$_ ~ .base(2).fmt('(%s)')})».fmt('%15s').join: "\n"}\n"
    given @cat[^(@cat.first: * > 1000, :k)];

```

Output:

```
30 matching numbers
          3(11)        10(1010)        15(1111)      36(100100)      45(101101)
     54(110110)      63(111111)   136(10001000)   153(10011001)   170(10101010)
  187(10111011)   204(11001100)   221(11011101)   238(11101110)   255(11111111)
528(1000010000) 561(1000110001) 594(1001010010) 627(1001110011) 660(1010010100)
693(1010110101) 726(1011010110) 759(1011110111) 792(1100011000) 825(1100111001)
858(1101011010) 891(1101111011) 924(1110011100) 957(1110111101) 990(1111011110)
```


[User]
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.

Task

Given a sorted array of integers (with possibly duplicates), is it possible to find a pair of integers from that array that sum up to a given sum? If so, return indices of the two integers or an empty array if not. The solution is not necessarily unique.

Example

Given numbers = [0, 2, 11, 19, 90], sum = 21,
Because numbers[1] + numbers[3] = 2 + 19 = 21,
return [1, 3].

Source

Stack Overflow: Find pair of numbers in array that add to given sum

[Assistant]
(formerly Perl 6)

### Procedural

**Translation of**: zkl

```
sub two_sum ( @numbers, $sum ) {
    die '@numbers is not sorted' unless [<=] @numbers;

    my ( $i, $j ) = 0, @numbers.end;
    while $i < $j {
        given $sum <=> @numbers[$i,$j].sum {
            when Order::More { $i += 1 }
            when Order::Less { $j -= 1 }
            when Order::Same { return $i, $j }
        }
    }
    return;
}

say two_sum ( 0, 2, 11, 19, 90 ), 21;
say two_sum ( 0, 2, 11, 19, 90 ), 25;

```

Output:

```
(1 3)
Nil
```

### Functional

The two versions differ only in how one 'reads' the notional flow of processing: left-to-right versus right-to-left.
Both return all pairs that sum to the target value, not just the first (e.g. for input of `0 2 10 11 19 90` would get indices 1/4 and 2/3).

```
sub two-sum-lr (@a, $sum) {
  # (((^@a X ^@a) Z=> (@a X+ @a)).grep($sum == *.value)>>.keys.map:{ .split(' ').sort.join(' ')}).unique
    (
     (
      (^@a X ^@a) Z=> (@a X+ @a)
     ).grep($sum == *.value)>>.keys
     .map:{ .split(' ').sort.join(' ')}
    ).unique
}

sub two-sum-rl (@a, $sum) {
  # unique map {.split(' ').sort.join(' ')}, keys %(grep {.value == $sum}, ((^@a X ^@a) Z=> (@a X+ @a)))
    unique
    map {.split(' ').sort.join(' ')},
    keys %(
     grep {.value == $sum}, (
      (^@a X ^@a) Z=> (@a X+ @a)
     )
    )
}

my @a = <0 2 11 19 90>;
for 21, 25 {
    say two-sum-rl(@a, $_);
    say two-sum-lr(@a, $_);
}

```

Output:

```
(1 3)
(1 3)
()
()
```


[User]
Two's complement is an important concept in representing negative numbers. To turn a positive integer negative, flip the bits and add one.

Task

Show how to calculate the two's complement of an integer. (It doesn't necessarily need to be a 32 bit integer.)

[Assistant]
By default Rakus integers are arbitrary sized, theoretically of infinite length. You can't really take the twos complement of an infinitely long number; so, we need to specifically use fixed size integers.

There is a module available from the Raku ecosystem that provides fixed size integer support, named (appropriately enough.) FixedInt.

FixedInt supports fixed bit size integers, not only 8 bit, 16 bit, 32 bit or 64 bit, but *ANY* integer size. 22 bit, 35 bit, 191 bit, whatever.

Here we'll demonstrate twos complement on a 57 bit integer.

```
use FixedInt;

# Instantiate a new 57(!) bit fixed size integer
my \fixedint = FixedInt.new: :57bits;

fixedint = (2³⁷ / 72 - 5¹⁷); # Set it to a large value

say fixedint;     # Echo the value to the console in decimal format
say fixedint.bin; # Echo the value to the console in binary format

fixedint.=C2;     # Take the twos complement

say fixedint;     # Echo the value to the console in decimal format
say fixedint.bin; # Echo the value to the console in binary format

```

Output:

```
144114427045277101
0b111111111111111110100111011001111000010101110110110101101
761030578771
0b000000000000000001011000100110000111101010001001001010011
```


[User]
This draft task needs a purpose, a description and some way to tell whether examples satisfy or do not satisfy it.

Task

Show a function/procedure that processes a block of text by printing it.

The function takes one parameter (ideally) that describes the text.

Demonstrate by calling the function twice, each time passing in a different type.

This can be done with pattern matching, multi-methods, dynamic type detection, structure(s) with a tag, etc.

The objective is write a [e.g. library] function that processes text from multiple sources (such as a string/char \*, socket, file, etc).

If not practical, show how the caller would coerce a type that can be passed to the library function.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.08.1

Raku is a dynamic language that has gradual, duck typing. It provides introspection methods through its comprehensive MOP (Meta Object Protocol) making it easy to do type detection, subroutine signatures and multi-dispatch. Raku types have two general flavors: content types and container types. Different container types have varying restrictions on what sort of content they can contain and in return provide specialized methods to operate on those contents. Content types give the compiler hints on how to best handle the information, what storage requirements it may have, what operators will work with it, etc.

This is really a very broad and kind of hand-wavey overview of Raku types. For much more in-depth coverage see: https://docs.raku.org/type.html

```
sub type ($t) { say $t.raku, "\tis type: ", $t.WHAT }

# some content types
.&type for 1, 2.0, 3e0, 4i, π, Inf, NaN, 'String';

# some primitive container types
.&type for $, [ ], @, { }, %, (5 .. 7), (8 ... 10), /0/, {;}, sub {}, ( );

# undefined things
.&type for Any, Nil;

# user defined types
class my-type { };

my my-type $object;

$object.&type;

```

Output:

```
1	is type: (Int)
2.0	is type: (Rat)
3e0	is type: (Num)
<0+4i>	is type: (Complex)
3.14159265358979e0	is type: (Num)
Inf	is type: (Num)
NaN	is type: (Num)
"String"	is type: (Str)
Any	is type: (Any)
$[]	is type: (Array)
$[]	is type: (Array)
{}	is type: (Hash)
{}	is type: (Hash)
5..7	is type: (Range)
(8, 9, 10).Seq	is type: (Seq)
/0/	is type: (Regex)
-> ;; $_? is raw { #`(Block|61385680) ... }	is type: (Block)
sub () { #`(Sub|62948936) ... }	is type: (Sub)
$()	is type: (List)
Any	is type: (Any)
Nil	is type: Nil
my-type	is type: (my-type)
```


[User]
With the following initial conditions:

```
      u1 = 1
      u2 = 2

```

We define the    nth    Ulam number    un    as the smallest number that is greater than    un-1      and

is the unique sum of two different Ulam numbers    ui (<n)    and    uj (<n).

Task

Write a function to generate the    nth    Ulam number.

References

* OEIS Ulam numbers

[Assistant]
```
my @ulams = 1, 2, &next-ulam … *;

sub next-ulam {
    state $i = 1;
    state @sums = 0,1,1;
    my $last = @ulams[$i];
    (^$i).map: { @sums[@ulams[$_] + $last]++ };
    ++$i;
    quietly ($last ^.. *).first: { @sums[$_] == 1 };
}

for 1 .. 4 {
    say "The {10**$_}th Ulam number is: ", @ulams[10**$_ - 1]
}

```

Output:

```
The 10th Ulam number is: 18
The 100th Ulam number is: 690
The 1000th Ulam number is: 12294
The 10000th Ulam number is: 132788
```


[User]
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at **1**),   constructed on a square grid, starting at the "center".

An Ulam spiral is also known as a   *prime spiral*.

The first grid (green) is shown with sequential integers,   starting at   **1**.

In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk),   and all non-primes as shown as a blank   (or some other whitespace).

Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).

Normally, the spiral starts in the "center",   and the   2nd   number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.

There are other geometric shapes that are used as well, including clock-wise spirals.

Also, some spirals (for the   2nd   number)   is viewed upwards from the   1st   number instead of to the right, but that is just a matter of orientation.

Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).

[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals   (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].

Then, in the next phase in the transformation of the Ulam prime spiral,   the non-primes are translated to blanks.

In the orange grid below,   the primes are left intact,   and all non-primes are changed to blanks.

Then, in the final transformation of the Ulam spiral (the yellow grid),   translate the primes to a glyph such as a    **•**    or some other suitable glyph.

|  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| **65** | **64** | **63** | **62** | **61** | **60** | **59** | **58** | **57** |
| **66** | **37** | **36** | **35** | **34** | **33** | **32** | **31** | **56** |
| **67** | **38** | **17** | **16** | **15** | **14** | **13** | **30** | **55** |
| **68** | **39** | **18** | **5** | **4** | **3** | **12** | **29** | **54** |
| **69** | **40** | **19** | **6** | **1** | **2** | **11** | **28** | **53** |
| **70** | **41** | **20** | **7** | **8** | **9** | **10** | **27** | **52** |
| **71** | **42** | **21** | **22** | **23** | **24** | **25** | **26** | **51** |
| **72** | **43** | **44** | **45** | **46** | **47** | **48** | **49** | **50** |
| **73** | **74** | **75** | **76** | **77** | **78** | **79** | **80** | **81** |

|  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|  |  |  |  | **61** |  | **59** |  |  |
|  | **37** |  |  |  |  |  | **31** |  |
| **67** |  | **17** |  |  |  | **13** |  |  |
|  |  |  | **5** |  | **3** |  | **29** |  |
|  |  | **19** |  |  | **2** | **11** |  | **53** |
|  | **41** |  | **7** |  |  |  |  |  |
| **71** |  |  |  | **23** |  |  |  |  |
|  | **43** |  |  |  | **47** |  |  |  |
| **73** |  |  |  |  |  | **79** |  |  |

|  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|  |  |  |  | **•** |  | **•** |  |  |
|  | **•** |  |  |  |  |  | **•** |  |
| **•** |  | **•** |  |  |  | **•** |  |  |
|  |  |  | **•** |  | **•** |  | **•** |  |
|  |  | **•** |  |  | **•** | **•** |  | **•** |
|  | **•** |  | **•** |  |  |  |  |  |
| **•** |  |  |  | **•** |  |  |  |  |
|  | **•** |  |  |  | **•** |  |  |  |
| **•** |  |  |  |  |  | **•** |  |  |

The Ulam spiral becomes more visually obvious as the grid increases in size.

Task

For any sized   **N × N**   grid,   construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number   (the default would be **1**),   with some suitably   *dotty*   (glyph) representation to indicate primes,   and the absence of dots to indicate non-primes.

You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.

Related tasks

* Spiral matrix
* Zig-zag matrix
* Identity matrix
* Sequence of primes by Trial Division

See also

* Wikipedia entry:   Ulam spiral
* MathWorld™ entry:   Prime Spiral

[Assistant]
(formerly Perl 6)

```
sub MAIN($max = 160, $start = 1) {
    (my %world){0}{0} = 0;
    my ($n, $dir, $side, $loc) = $start, 1, 0, 0+0i;

    while ++$side < $max {
	step for ^$side; turn-left;
	step for ^$side; turn-left;
    }

    braille-graphics %world;

    sub step {
	$loc += $dir;
	%world{$loc.im}{$loc.re} = $n if (++$n).is-prime;
    }

    sub turn-left  { $dir ×= -i }
    sub turn-right { $dir ×=  i }
}

sub braille-graphics (%a) {
    my ($y-lo, $y-hi, $x-lo, $x-hi);
    for %a.keys.map(+*) -> \y {
        for %a{y}.keys.map(+*) -> \x {
            $y-lo min= y; $y-hi max= y;
            $x-lo min= x; $x-hi max= x;
        }
    }

    for $y-lo, $y-lo + 4 ...^ $y-hi -> \y {
	for $x-lo, $x-lo + 2 ...^ $x-hi -> \x {
	    my $cell = 0x2800;
            $cell += 2⁰ if %a{y + 0}{x + 0};
            $cell += 2¹ if %a{y + 1}{x + 0};
            $cell += 2² if %a{y + 2}{x + 0};
            $cell += 2³ if %a{y + 0}{x + 1};
            $cell += 2⁴ if %a{y + 1}{x + 1};
            $cell += 2⁵ if %a{y + 2}{x + 1};
            $cell += 2⁶ if %a{y + 3}{x + 0};
            $cell += 2⁷ if %a{y + 3}{x + 1};
            print chr($cell);
	}
	print "\n";
    }
}

```

Output:

```
⠔⠀⠀⠀⢐⠀⠁⠀⠀⠀⢐⠁⠀⢀⠀⠄⠄⠀⢀⠀⠀⠅⢀⠁⢅⢄⠀⢀⠔⠁⠀⠀⠀⢀⢀⠀⠀⠀⠁⢀⢀⠀⠀⢔⠁⢔⠄⠀⢄⠐⠀⠀⢀⠁⠐⠄⠀⢑⠄⠁⠄⠀⠁⠄⠀⠀⠀⢐⠀⠄⠐⠀⢁⢀⠀⠀⠄⠀⢕⠐
⠄⠁⠁⠄⠀⠄⢀⠀⠐⠀⠀⠁⢁⢀⠐⠀⠀⠀⢁⠐⠄⠀⠀⠔⠀⢐⠁⠄⠀⠑⠀⢀⠁⠀⠐⠐⠁⠀⠄⠀⢀⠀⠀⠀⠐⠀⠐⠀⠅⠀⠀⢄⢀⠐⠁⠐⠄⠁⢀⠀⠀⠐⠁⠀⠀⠄⢄⠀⠕⠁⠀⠐⢄⠀⠀⢀⠐⠄⠁
⠀⠀⢀⠁⢀⠀⠑⢀⠀⠄⠀⠀⠅⢑⠀⠁⠐⠀⠀⠐⠀⠄⠁⢄⠀⢑⠀⠄⢑⠀⠁⠀⢀⠑⢐⠀⠁⢀⠄⠐⢀⠄⠁⠀⠀⠀⠀⢀⠄⠀⠀⠑⠀⢀⠔⢁⠀⠀⠀⠀⠐⠁⠀⠑⢀⠀⠐⠀⢄⠔⢐⠄⠅⠐⠀⠅⢁⠀⠁⠁
⠅⢀⠄⠑⠀⠀⠅⠄⠀⢐⠐⠀⠀⠄⠀⢁⠄⠀⢔⢀⠁⠀⠔⠁⠑⢐⠀⠐⠀⠁⢑⠀⠀⢁⠀⠀⠄⠀⠀⠑⢀⠀⠄⠔⠁⠀⠄⠀⠐⢀⠀⠀⠔⠁⠀⠐⠀⠀⠐⠁⠐⠀⠀⢀⠄⠁⢁⠀⠀⠐⠀⠁⢐⠀⠐⠀⠄⠑⠐⠄
⠀⠀⠀⢐⠑⠑⢀⠁⠑⢀⠐⠀⠄⠀⠀⢀⢐⠕⠄⠀⠀⠀⠐⠀⠀⢀⠄⠀⠀⠀⠄⠐⠐⠀⠀⠁⢄⠐⠅⢀⠐⠄⠁⠐⠀⠅⢀⠐⢁⢀⠀⠁⠐⠕⠀⠀⠀⠀⢐⠀⠅⠐⠔⢁⠀⠐⠅⠐⠄⢀⠀⢄⠀⢀⠄⠀⠀⢀⠁⠐
⢀⠀⠀⢀⠁⠀⠀⠀⢁⠁⠐⠀⠁⢐⢀⠀⠁⠀⠔⠁⢄⠁⠁⠄⠀⢀⠄⠀⢐⠀⠔⠁⢀⠕⠁⢀⠁⠀⢀⠔⢐⠀⠀⠁⢀⠀⠀⢀⠔⠀⠄⠄⠁⠀⠄⢐⠄⠁⢁⠀⠄⠀⠀⠄⠀⢄⠀⢀⢀⠁⠄⢀⠄⠀⢀⠁⢁
⠁⠄⠀⠀⠄⠀⠄⠀⠄⠑⢄⠔⠁⠀⠁⠀⠐⠀⠀⠀⠀⠀⢀⠀⠀⠄⠁⢁⠐⠀⠀⢀⠀⠄⠐⠀⢐⠀⠁⠀⠀⠁⠁⠄⠁⢄⠔⠀⠐⠀⠀⠔⢄⠀⠀⢐⠀⢅⠀⠁⢀⠀⠀⠀⠀⠀⠄⠀⠐⠀⠀⠀⠄⠀⠀⠀⠐⠀⠄⠄
⠀⠑⠐⠔⠀⢀⢀⠀⢁⠔⠁⢁⠄⠁⠀⠀⠀⠅⠀⢀⠀⠁⢀⠀⢄⠀⠀⠀⠐⠀⢀⠐⠁⢀⠀⠀⠀⢀⠁⠀⠐⠀⠄⢀⠔⢁⠀⠀⢅⠐⠑⠅⠀⠐⠀⢀⠁⢄⠀⠀⢁⠐⠄⠀⠐⢕⢀⠁⢀⠁⠑⠅⠀⢁⠐⠀⠁⠀⢁⢐
⢀⠁⠄⠀⠀⢄⠁⠄⠀⠀⠐⠅⠁⠁⢀⢀⢅⠄⠐⢁⠀⠄⠀⠄⠅⠑⢀⠔⢀⠀⠀⢁⠀⠕⠐⠀⠀⠐⢄⠐⢀⠄⠀⠁⢀⠁⢀⠀⠄⢀⠀⠀⠀⢀⠑⢐⠀⠀⠁⠄⠐⠁⠄⠄⠀⠀⠐⢄⢀⠀⠄⠄⠀⠀⠀⠄⢄⢀⠄
⠐⠄⠐⠁⠀⠔⠑⠀⠀⠐⠀⠀⠑⠀⠐⠄⠀⠀⠐⠀⠁⢀⠄⠀⠀⢐⠀⠔⠀⠀⢄⠄⠁⢐⠀⠀⢄⠔⠀⢀⢐⠁⠅⢀⠀⠄⠐⠀⢐⠀⠁⢕⠄⠀⠀⢔⠁⠀⢐⠀⢀⠄⠑⠄⠀⠀⠄⠀⠀⠄⠐⠁⠄⠀⠐⠔⠄
⢀⠐⢀⢐⠀⠀⠄⠑⠑⠐⠐⠀⠔⠑⠀⠐⠀⢀⠀⠀⢀⠄⠀⠁⢄⠀⠁⠀⢀⠁⢀⠀⠀⠀⠐⠄⠁⢐⠔⠅⢐⠅⠀⠀⠅⠀⠀⠀⠁⠀⠔⠄⠀⠔⢀⠀⠄⢁⠐⢁⢀⢁⢀⢀⢁⠄⠁⢀⠀⠀⢁⢑⠀⢀⢐⠁⠀⠀⠀⠁
⠀⠄⠅⠀⠁⠅⠁⢁⠄⠀⠀⢀⠀⢄⠀⠁⠁⢁⠀⠄⢅⢁⠄⠄⠐⢀⢀⠄⠁⠀⠀⠀⢄⠔⠁⢀⠐⠁⠄⠐⠀⠀⠁⢐⠀⠀⢀⢀⠀⠀⠀⠐⠀⠄⠐⠀⠀⠁⠄⠀⠁⠀⠀⠁⢄⠀⠁⢅⠀⠄⠁⠀⠁⠅⢀⠀⠀⠀⠐⠁
⠁⠀⠀⠀⠀⠀⠀⢄⠀⠐⢀⠀⠐⠄⠄⠁⠀⠔⠔⠄⠀⠁⠀⠐⠄⢀⠀⠄⠔⠀⠁⠀⠀⢐⢔⠁⠅⠀⠀⢐⠀⠀⠄⠄⠀⠑⠔⠀⠅⢀⠁⠔⢀⠀⢔⠀⠁⠐⠐⠐⢐⠔⠀⠐⠀⠐⠀⠀⠐⢐⠄⠐⠐⠀⠑⢐⠐⠑⠐⠐
⢀⠁⠁⠀⠀⢑⢀⠀⠑⢀⠀⢀⠀⠀⠁⢔⠀⠀⠀⠀⢀⢀⠁⠁⢄⠀⢁⠀⠀⠐⠁⢀⠐⢁⠐⠐⢁⠐⠀⢄⠐⠅⠀⢐⠄⢁⢀⠐⠄⠐⠐⠀⠀⠔⠀⠑⢔⢀⠑⠀⠀⠐⠑⠀⠀⠐⢀⢀⠑⠀⠐⢀⠀⠁⠐⠁⠀⢁
⠀⠔⠀⢀⠀⠀⢀⠑⠄⠁⠄⠄⢀⠐⠁⠁⠅⠁⢁⢀⠁⠀⢐⠀⠁⠅⢀⢁⠀⢀⠑⢑⠄⠀⠀⠄⠀⠁⢄⠀⢐⠄⠁⠑⢀⠅⢑⠀⠀⠀⠄⠄⢄⠄⠕⢀⠀⠔⢄⢀⠀⠀⠀⠁⢄⠄⠀⠁⠀⠐⠄⠀⠁⢀⠄⠔⠁⠀⠁⠄
⠀⠀⠐⠀⠄⠀⠀⢀⠄⠄⢄⠔⠐⢄⠀⠀⠄⠀⠀⠀⠀⠀⢄⠔⠐⠀⠔⠐⠀⠀⠔⠀⠀⢕⢔⠀⠁⢐⠁⢑⠐⠁⠀⠀⠀⢄⠀⠀⢅⠐⠑⠐⠀⠀⢐⠔⠀⠄⠀⠑⢔⠀⠀⠔⠀⠁⢀⠄⠀⠀⠀⠀⠀⠐⠀⠀⠐⠀⠐
⠄⠐⠀⠄⠀⢀⠐⠀⢀⢐⠀⢀⠄⠀⢐⠀⠀⠀⠀⠐⠐⢄⠀⠀⠔⠀⢀⠀⠀⢐⢔⠀⢀⢄⠀⠄⢀⢀⠐⠁⢐⠅⠅⢀⠑⠄⠐⠐⠀⢀⠀⠁⠁⠑⠀⢁⠅⠀⠁⠄⠀⠁⠀⠀⠁⠁⠁⠐⠑⠁⠁⠀⢀⠐⢀⢀⠀⠁⠀⢀
⢁⢀⠄⠁⠐⠀⢁⠀⠀⠀⠀⠁⠀⢑⠀⢁⠐⠀⠀⠀⢁⠁⢐⠀⢀⠀⠀⠀⢕⢄⢁⢑⠄⠀⠔⢀⠐⠁⢀⠄⠐⠄⠄⢑⢄⠅⢄⠀⠁⢁⢀⠐⠁⢀⠀⠄⠀⠐⠀⠀⠀⢀⠀⠁⢄⠀⠄⠀⢀⠅⢁⠀⠀⢀⠀⠅⠄⠀⠑
⠁⠄⠄⠁⠄⠀⠀⠀⠀⠁⠀⠄⠁⠀⠀⠄⠀⠀⠁⠄⠀⠁⠄⠀⠀⠄⠄⠄⠀⠀⠄⠀⠄⠁⠄⠀⠅⠄⠁⢕⢐⠀⢀⠔⠀⠔⠄⠑⠐⠀⠑⢔⠐⠁⠐⠐⠀⢄⠐⠐⠄⠀⠀⠀⠔⠑⠄⠄⠀⠀⠀⠀⢀⠄⠀⠀⠀⠁⢐⠔
⠐⠀⠑⢐⠁⠀⢐⠑⢁⢀⠐⢀⢐⠑⠁⠀⠀⢀⠀⠁⠑⠀⠑⢐⢀⠑⢐⠀⠁⢑⠀⠑⠐⠐⠐⠑⢐⠑⢑⠄⣔⢅⢁⢁⠐⢀⢁⢅⠁⠐⢐⠀⠀⠄⢀⢐⢅⢁⠀⠀⠀⠀⠐⠁⢁⠔⢀⢑⠁⢁⠐⢀⠀⠀⢄⢀⢁⢅⢀
⢀⠀⠀⠁⠀⠀⠀⢐⢀⠁⠀⠀⠁⠀⠅⠀⠔⢁⢀⠀⠀⠀⢁⢁⠁⢐⠀⢀⠅⠅⢀⠀⠄⢁⠄⢄⠀⢕⠅⠑⢄⠀⠄⢄⢀⠄⢀⠄⠄⠀⢄⠀⠄⢄⠀⠀⢀⠄⢀⢀⠄⠀⠄⠄⠀⢀⠀⢄⠄⠀⢄⢀⠄⢀⢀⠄⠀⠄⠀⢀
⠐⢄⠀⠄⠀⠄⠐⠀⠀⠁⢀⠀⠅⠀⠄⠄⠀⠀⠀⢀⠔⠕⠄⠄⠑⠀⠀⠁⠀⠐⠔⢄⠀⠀⢄⠐⠔⢀⠁⢐⢀⠐⠄⠐⠁⠀⠄⠐⠐⠄⠁⠀⠐⠀⠄⠀⠑⠄⠐⠀⠀⠐⠀⠔⠀⠁⠔⠀⠁⠀⠀⠑⠄⠔⠀⠀⠀⠑⠐
⠀⠀⢀⠄⠐⠀⠀⠀⢀⠄⠀⢑⢀⠁⠐⢀⠑⠀⠔⠐⢁⢐⠀⠐⢀⠀⠑⢐⠀⠀⢀⠐⢐⢔⠐⠄⢀⠁⠁⢐⠑⢄⢄⠑⠀⠁⠐⠐⢁⠐⠑⢁⠑⢀⢀⢀⠐⠁⢐⢐⠀⠐⠐⠀⢀⠑⢁⠁⠀⠀⠀⠑⠀⠁⢐⢀⠑⠀⢀⢀
⠁⢀⠀⠀⢁⠀⠀⠅⠀⠀⠅⠀⠀⠐⢀⢀⢀⠄⠀⠅⠀⢁⠔⠀⠁⢁⠁⠁⠑⢄⠀⠁⠁⢀⢀⠄⠑⢔⠀⠐⠔⠁⠀⠄⠀⠑⢀⠀⠕⠄⠀⠀⠄⢀⠀⠁⢄⠁⢄⠄⠐⠄⢄⠔⠀⠀⠐⠁⢀⠐⠀⠀⠅⠀⠀⠔⠀⢀⠁
⠀⢄⠐⠁⠀⠐⠕⠀⠄⠐⠀⠐⠀⢀⠐⠐⠀⠀⠅⠀⠄⠁⢀⠄⠀⠄⠔⠑⢀⠀⠅⠀⠅⠄⠀⠄⠁⢀⠄⠀⢀⠀⢁⢀⠕⠀⠀⠑⠀⠐⠀⢄⠐⠁⢄⠄⠁⠐⠄⠐⢀⠀⠁⠄⠔⠀⢄⠀⠁⠄⠔⠁⢐⠄⠐⠀⠀⠑⢀⠔
⢀⠐⢀⠀⠀⠐⠄⠁⠐⠄⠐⠀⢀⠑⠁⠄⠀⠁⠐⠀⢀⠀⠁⢀⠀⠐⠐⠔⠁⢀⠀⠑⠀⠀⠐⠀⢔⠑⠀⢐⠀⢁⢀⠐⠀⢀⠐⢀⠄⠁⢄⠁⠀⠀⠁⠀⠀⠀⢐⢀⢁⢑⠀⢀⠑⠐⠁⠀⢀⢀⠀⠁⢀⢀⠀⠀⠐⢀⠀⠐
⢀⢁⠀⠀⢑⢅⢁⢄⢀⢀⠅⠀⠀⠄⢀⢁⢐⢁⢀⢅⢄⠀⠀⢀⢀⠐⠅⠁⠀⠀⢁⠐⠀⢀⠀⠀⠐⢀⠀⢀⠄⠅⠐⢐⠀⠀⠔⠁⠑⠐⠄⠀⠄⠀⠅⠁⠄⠐⠀⠀⠁⠁⠀⠄⠅⠀⠀⠄⠄⠅⠀⠄⠀⠄⠀⠁⠀⠀⠔
⠁⠀⠀⠁⠀⠀⠀⢀⠄⠀⠀⠀⠀⠄⠄⠀⢀⠀⠐⢀⠀⠀⢄⠔⠄⠀⠄⠀⠀⠔⠕⢀⠔⠀⠀⠄⠄⠀⠁⠐⠀⠀⠕⢀⠕⠁⠀⠁⢑⠀⠀⢀⢀⠐⠄⠀⠑⠀⠀⠁⢄⠔⠑⢐⠀⠑⢄⠐⠀⠀⠐⠀⠀⠀⠀⠀⠄⠁⢀⠄
⠀⠁⠐⠀⠁⠀⠄⠀⠑⠀⠀⢀⠀⠐⠀⠄⠀⠑⠀⠀⢐⠀⠁⢅⠀⠀⠀⠐⠀⢀⠄⠀⢁⢄⠀⠁⠔⠑⠄⠀⠑⢄⠔⠁⢀⠀⠀⢄⠄⠀⠀⠐⠁⠁⢀⠐⠄⠀⠁⠐⠁⢀⢑⠁⠐⠐⢀⠑⠔⠀⠁⠀⢁⢀⠄⠁⢐
⠀⠅⠁⢀⠐⠀⠁⠐⠀⠁⠐⢄⠀⢄⢀⠀⠄⢀⠁⢁⠄⠀⠐⠀⢑⠄⠀⠑⠐⠀⠁⠀⠁⠐⠐⠀⠁⠄⠄⢀⠄⠁⠐⢀⠄⠐⠀⠄⠀⠄⠀⠀⢀⠄⢀⢐⠀⠑⠀⠀⠄⢄⢄⠀⢅⠀⠀⠄⠀⠅⠀⠄⠐⢀⠀⠔⠅⠀⠄⢁
⠄⠀⠄⠄⠀⠄⠀⢀⠀⠐⠀⠀⠁⠀⠔⠄⠀⠀⠁⠀⠄⢄⠀⠐⠀⠀⠄⢑⠀⠁⠅⠀⠁⠀⢀⠄⠑⢀⠄⢀⢀⠔⢀⠀⠑⠄⠀⠅⠀⠀⠅⢕⠀⠐⢐⠀⠄⠕⠀⠀⢀⠀⠀⢀⠀⠁⠀⠀⠐⢀⠐⠁⢀⠔⠁⢐⠀⠀⠐
⠀⠐⢁⢀⠐⠀⢀⠁⠀⠀⠁⠑⠄⠀⢁⠐⠁⠅⢀⠐⢀⠄⠀⠀⠐⠀⠅⢀⠐⢀⢀⠁⠅⢀⠀⠄⠔⠑⠁⠀⠁⠀⠐⠁⢀⠀⠀⢀⠀⠐⠄⠔⠐⠁⢄⠀⠅⢄⠑⠀⢀⠐⠀⠀⢁⢀⠀⢀⠁⢀⠁⠅⠁⠀⠁⠀⠀⠄⠀⠁
⠀⠀⢀⠀⠄⢁⠀⠀⠄⠀⢁⢁⠀⠀⠀⠐⠀⠄⠀⠐⠀⢀⢀⠁⠁⠄⠄⢀⠀⠀⠑⢀⠀⠑⠐⠁⠀⠀⠁⢐⠄⠀⢀⠐⠄⠐⢀⠁⠑⢀⠀⠀⠐⠀⢑⠄⠀⠁⠀⠅⠐⠄⠀⠀⠄⠀⠄⠁⠀⠄⢁⢀⠁⠁⠄⠀⠀⠀⠀⢄
⠑⠀⠀⠀⢀⠀⠁⠄⠐⠀⠀⠄⢄⠀⠐⠐⠀⠑⢁⠀⠔⠀⠀⠀⠀⠀⠕⢄⠀⠐⠀⢀⠔⠅⢀⠀⠐⠀⠅⢐⠀⠕⠐⢀⠀⠔⠀⠅⠀⠀⠀⠄⢀⠁⢀⠀⠀⠔⠀⠐⠁⢀⠀⠁⢀⠁⠀⠐⠐⠄⠐⠐⠄⠀⠀⠀⠀⠀⠔⠐
⠐⠀⢐⠀⠀⠀⢀⠀⠐⠐⠀⠀⠐⠀⠄⢀⠁⢄⠀⠑⢀⠀⠐⢀⢄⠀⠀⢀⠀⢅⢔⠁⠄⠐⠀⠁⠀⠑⠀⠀⠐⠁⠄⠀⢁⢀⠀⠁⠐⠁⠀⠀⠀⠀⠀⠀⠀⠀⠐⢀⠄⠀⢀⢔⠑⢅⠀⠐⢄⠁⢀⠄⢁⢀⠐⠀⠀⢀⢀⢑
⠀⠄⠅⢀⠁⠀⠀⠅⠁⠀⢄⠀⠁⠐⠁⢀⠀⠀⠀⠀⠀⠑⠀⠄⢀⠀⠀⢀⠐⠀⠀⢀⠁⠐⢀⠄⠁⢔⠄⠀⠄⠄⠑⠄⠁⠀⠀⠁⠐⠐⠄⠁⢄⠀⢀⠄⠁⠀⠔⠁⢀⠐⠄⠀⠀⠀⢁⢐⠀⠀⠄⠀⠀⢀⠀⠅
⠔⠀⠄⠀⢀⠄⠁⢀⠁⠄⠀⠀⠑⠀⠐⠁⠀⠐⠑⢀⠄⠄⠀⠀⢄⠀⠔⠔⢀⠀⠁⠀⠔⠀⢀⠄⠀⠀⠁⢐⠀⠑⠀⠀⠀⢅⠀⠀⢀⠀⠁⠄⠀⠁⢀⠀⠔⠐⠀⠀⢅⠀⠐⢀⠀⠀⠄⢀⠐⠔⠀⠁⠄⠀⠁⠀⠔⠐
⠀⠐⢀⠐⠀⠁⢀⠀⠀⠐⠐⢀⢄⠐⢄⠐⠀⠅⠀⠁⠁⠄⠐⢁⠄⠀⠀⢄⠀⠅⠔⠀⢁⠀⠐⠄⢀⠀⠁⠀⠐⠀⢀⠑⢀⠄⠀⠅⠀⠀⠅⠀⠀⢀⢔⠐⠄⠀⠁⠀⠐⠀⠀⢀⠑⠀⠄⠐⢁⢀⠀⢄⢄⠁⢀⠀⢐⠐⠁⠁
⠁⠄⠄⠀⠀⠁⠀⢐⠀⠐⠀⠄⢑⠀⠀⠑⠄⠁⢁⢀⠀⢑⠔⠁⠀⠄⠄⠀⢀⠀⠑⠔⠁⢁⠀⠄⢁⠔⠀⢀⠔⠀⢐⠀⠀⠀⠄⠄⠀⠐⠁⢁⠔⠁⠐⠐⠁⢀⢀⠀⠁⠔⠀⠀⠀⠅⠁⠀⠄⠀⠔⠁⢑⠀⠀⠀⠀⠀⠐
⠁⠀⠅⠐⠀⠁⠀⠀⠐⠁⠀⠀⠕⠀⠀⠅⠀⠐⠀⠀⠕⠁⠀⠄⠅⠀⠀⠐⠀⠐⠅⠀⠀⠄⠀⠀⠀⠀⠀⠐⠀⠀⠀⠀⠁⠀⠀⠀⠄⠀⠐⠁⠀⠄⠁⠀⠁⠄⠀⠐⠄⠀⠅⠀⠀⠔⠁⠀⠀⠕⠀⠀⠀⠀⠀⠁⠀⠁

```


[User]
An **ultra-useful prime** is a member of the sequence where each **a(n)** is the smallest positive integer **k** such that **2(2n) - k** is prime.

***k** must always be an odd number since 2 to any power is always even.*

Task

* Find and show here, on this page, the first **10** elements of the sequence.

Stretch

* Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)

See also

* OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime

[Assistant]
The first 10 take less than a quarter second. 11 through 13, a little under 30 seconds. Drops off a cliff after that.

```
sub useful ($n) {
    (|$n).map: {
        my $p = 1 +< ( 1 +< $_ );
        ^$p .first: ($p - *).is-prime
    }
}

put useful 1..10;

put useful 11..13;

```

Output:

```
1 3 5 15 5 59 159 189 569 105
1557 2549 2439
```


[User]
Given a weighted one-bit generator of random numbers where the probability of a one occurring,

P

1
{\displaystyle {\displaystyle P\_{1}}}

, is not the same as

P

0
{\displaystyle {\displaystyle P\_{0}}}

, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is

P

1
{\displaystyle {\displaystyle P\_{1}}}

×

P

0
{\displaystyle {\displaystyle P\_{0}}}

, assuming independence. This is the same as the probability of a zero followed by a one:

P

0
{\displaystyle {\displaystyle P\_{0}}}

×

P

1
{\displaystyle {\displaystyle P\_{1}}}

.

Task details

* Use your language's random number generator to create a function/method/subroutine/... **randN** that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
* Create a function **unbiased** that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).

The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.

This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

**Works with**: Rakudo version 2020.08.1

```
sub randN ( $n where 3..6 ) {
    return ( $n.rand / ($n - 1) ).Int;
}

sub unbiased ( $n where 3..6 ) {
    my $n1;
    repeat { $n1 = randN($n) } until $n1 != randN($n);
    return $n1;
}

my $iterations = 1000;
for 3 .. 6 -> $n {
    my ( @raw, @fixed );
    for ^$iterations {
        @raw[      randN($n) ]++;
        @fixed[ unbiased($n) ]++;
    }
    printf "N=%d   randN: %s, %4.1f%%   unbiased: %s, %4.1f%%\n",
        $n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;
}

```

Output:

```
N=3   randN: [676, 324], 32.4%   unbiased: [517, 483], 48.3%
N=4   randN: [734, 266], 26.6%   unbiased: [489, 511], 51.1%
N=5   randN: [792, 208], 20.8%   unbiased: [494, 506], 50.6%
N=6   randN: [834, 166], 16.6%   unbiased: [514, 486], 48.6%
```


[User] For languages which have an explicit notion of an undefined value, identify and exercise those language's mechanisms for identifying and manipulating a variable's value's status as being undefined.

[Assistant]
(formerly Perl 6)
Raku has "interesting" values of undef, but unlike Perl 5, doesn't actually have a value named undef. Instead, several very different meanings of undefinedness are distinguished. First, Nil represents the absence of a value. The absence of a value cannot be stored. Instead, an attempt to assign Nil to a storage location causes that location to revert to its uninitialized state, however that is defined.

```
my $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any()

```

This Any is an example of another kind of undefined type, which is a typed undef. All reference types have an undefined value representing the type. You can think of it as a sort of "type gluon" that carries a type charge without being a "real" particle. Hence there are undefined values whose names represent types, such as Int, Num, Str, and all the other object types in Raku. As generic objects, such undefined values carry the same metaobject pointer that a real object of the type would have, without being instantiated as a real object. As such, these types are in the type hierarchy. For example, Int derives from Cool, Cool derives from Any, and Any derives from Mu, the most general undefined object (akin to Object in other languages). Since they are real objects of the type, even if undefined, they can be used in reasoning about the type. You don't have to instantiate a Method object in order to ask if Method is derived from Routine, for instance.

```
say Method ~~ Routine;  # Bool::True

```

Variables default to Any, unless declared to be of another type:

```
my     $x; say $x.WHAT; # Any()
my Int $y; say $y.WHAT; # Int()
my Str $z; say $z.WHAT; # Str()

```

The user-interface for definedness are type smilies and the with-statement.

```
my Int:D $i = 1; # if $i has to be defined you must provide a default value
multi sub foo(Int:D $i where * != 0){ (0..100).roll / $i } # we will never divide by 0
multi sub foo(Int:U $i){ die 'WELP! $i is undefined' } # because undefinedness is deadly

with $i { say 'defined' } # as "if" is looking for Bool::True, "with" is looking for *.defined
with 0 { say '0 may not divide but it is defined' }

```

There are further some operators for your convenience.

```
my $is-defined = 1;
my $ain't-defined = Any;
my $doesn't-matter;
my Any:D $will-be-defined = $ain't-defined // $is-defined // $doesn't-matter;

my @a-mixed-list = Any, 1, Any, 'a';
$will-be-defined = [//] @a-mixed-list; # [//] will return the first defined value

my @a = Any,Any,1,1;
my @b = 2,Any,Any,2;
my @may-contain-any = @a >>//<< @b; # contains: [2, Any, 1, 1]

sub f1(){Failure.new('WELP!')};
sub f2(){ $_ ~~ Failure }; # orelse will kindly set the topic for us
my $s = (f1() orelse f2()); # Please note the parentheses, which are needed because orelse is
                            # much looser then infix:<=> .
dd $s; # this be Bool::False

```

Finally, another major group of undefined values represents failures. Raku is designed with the notion that throwing exceptions is bad for parallel processing, so exceptions are thrown lazily; that is, they tend to be returned in-band instead as data, and are only thrown for real if not properly handled as exception data. (In which case, the exception is required to report the original difficulty accurately.) In order not to disrupt control flow and the synchronicity of event ordering, such failures are returned in-band as a normal values. And in order not to subvert the type system when it comes to return types, failure may be mixed into any reference type which produces an undefined, typed value which is also indicates the nature of the failure.

Native storage types work under different rules, since most native types cannot represent failure, or even undefinedness. Any attempt to assign a value to a storage location that cannot represent a failure will cause an exception to be thrown.


[User]
An **Undulating number** in some base is a number which has the digit form ABABAB... where A and B are digits in that base.

For the purposes of this task, we shall only consider a number to be undulating if it has at least 3 digits in a given base and A != B.

Examples

The numbers: 101 and 9898 are undulating numbers in base 10.

The numbers: 50 and 2350 are undulating numbers in base 7 because their base 7 representations are: 101 and 6565 respectively.

Task

For base 10, find and show on this page:

1. All three digit undulating numbers.

2. All four digit undulating numbers.

3. All three digit undulating numbers which are primes.

4. The 600th undulating number.

5. How many undulating numbers are less than 2^53 and the largest such number.

Bonus

Do the same for base 7 expressing the results in base 10 apart from 4. and 5. which should be expressed in base 7 also.

Note that undulating numbers with a given number of digits in base 7 may, of course, have less digits when expressed in base 10 and are unlikely to be still undulating. However, 121 (or 232 in base 7) is an exception to this.

References

* Wikipedia article : Undulating number
* OEIS sequence A046075: Non-trivial undulants

[Assistant]
**Translation of**: Wren

```
# 20230602 Raku programming solution

sub undulating ($base, \n) {
   my \limit = 2**(my \mpow = 53) - 1;
   my (\bsquare,@u3,@u4) = $base*$base;
   for 1..^$base X 0..^$base -> (\a,\b) {
      next if b == a;
      @u3.push(a * bsquare + b * $base + a);
      @u4.push((my \v = a * $base + b) * bsquare + v)
   }
   say "\nAll 3 digit undulating numbers in base $base:";
   .fmt('%3d').say for @u3.rotor: 9;
   say "\nAll 4 digit undulating numbers in base $base:";
   .fmt('%4d').say for @u4.rotor: 9;
   say "\nAll 3 digit undulating numbers which are primes in base $base:";
   my @primes = @u3.grep: *.is-prime;
    .fmt('%3d').say for @primes.rotor: 10, :partial;
   my \unc = (my @un = @u3.append: @u4).elems;
   my ($j, $done) = 0, False;
   loop {
      for 0..^unc {
         my  \u = @un[$j * unc + $_] * bsquare + @un[$j * unc + $_] % bsquare;
	 u > limit ?? ( $done = True and last ) !! ( @un.push: u );
      }
      $done ?? ( last ) !! $j++
   }
   say "\nThe {n} undulating number in $base $base is: @un[n-1]";
   say "or expressed in base $base : {@un[n-1].base($base)}" unless $base == 10;
   say "\nTotal number of undulating numbers in base $base < 2**{mpow} = {+@un}";
   say "of which the largest is: ", @un[*-1];
   say "or expressed in base $base : {@un[*-1].base($base)}" unless $base == 10;
}

undulating $_, 600 for 10, 7;

```

You may Try it online!


[User]
Within a string, an escape sequence gives special meaning to otherwise ordinary characters.

For example, in the C programming language, the string literal `"a\nb"`, containing the escape sequence `\n`, would be interpreted by the compiler as the bytes `61 0a 62`, not `61 5c 6e 62`.

In JavaScript Object Notation, the string value `"a\u263Ac"`, containing the escape sequence `\u263A`, would be parsed into `"a☺c"`.

Task

Write a function (or routine, subroutine, procedure, etc.) that, when given a UTF-8 encoded string, returns a new string, also encoded in UTF-8, with all escape sequences replaced with equivalent Unicode code points.

For this task we'll follow JSON string semantics, defined in Section 7 of RFC 8259. In summary:

* Allowed two-character escapes are `\\`, `\"`, `\/`, `\b`, `\f`, `\n`, `\r`, `\t`.
* `"`, `\` and control characters (U+0000 through U+001F) must be escaped.
* Any "character" in the Basic Multilingual Plane may be escaped with a `\uXXXX` sequence, where `XXXX` are hexadecimal digits encoding the character's code point
* Characters outside the Basic Multilingual Plane may be escaped with a `\uXXXX\uXXXX` sequence, where `XXXX` are hexadecimal digits encoding the code point using UTF-16.

Although not required by RFC 8259, we'll treat strings containing invalid `\u` escape sequences (those that can't be decoded to a Unicode code point) as an error condition.

Test your program with the following inputs and display the string before and after unescaping. It's OK to display bytes rather than "characters" if it's more convenient for your language, or both, if you prefer.

Test cases

| Input string | Expected result | Comment |
| --- | --- | --- |
| `abc` | `abc` | No escape sequences |
| `a☺c` | `a☺c` | No escape sequences, extended unicode |
| `a\"c` | `a"c` | Two-character escape |
| `\u0061\u0062\u0063` | `abc` | Just escape sequences |
| `a\\c` | `a\c` | Two-character escape for reverse solidus |
| `a\u263Ac` | `a☺c` | `\u` escape, basic multilingual plane |
| `a\\u263Ac` | `a\u263Ac` | Escaped `\` before `u` |
| `a\uD834\uDD1Ec` | `a𝄞c` | `\u` escape, surrogate pair |
| `a\ud834\udd1ec` | `a𝄞c` | Lower case hex digits |
| `a\u263` | *error* | Incomplete escape sequence |
| `a\u263Xc` | *error* | Invalid hexadecimal digit |
| `a\uDD1Ec` | *error* | Lone low surrogate |
| `a\uD834c` | *error* | Lone high surrogate |
| `a\uD834\u263Ac` | *error* | High surrogate followed by non-surrogate |

Related tasks

* Literals/String
* Special characters
* UTF-8 encode and decode

[Assistant]
Implement a JSON string unescape Grammar.

```
# 20240816 Raku programming solution

grammar JSON-Unescape {
   token TOP             { ^ <value> $ }
   token value           { [ <str> | \\ <str=.str_escape> ]* }
   token str             { <-["\\\t\x[0A]]>+ }
   token str_escape      { <["\\/bfnrt]> | 'u' <utf16_codepoint>+ % '\u' }
   token utf16_codepoint { <.xdigit>**4 }
}

class JSON-Unescape-Actions {
   method        TOP($/) { make $<value>.made }
   method        str($/) { make ~$/ }
   method      value($/) { make $<str>».made.join }
   method str_escape($/) {
      make $<utf16_codepoint>.Bool
         ?? utf16.new( $<utf16_codepoint>.map({:16(~$_)}) ).decode()
         !! %(< \\ / b n t f r " > Z=> < \\ / \b \n \t \f \r " >).{~$/}
   }
}

for < abc  a☺c  a\"c \u0061\u0062\u0063 a\\\c   a\u263Ac  a\\\u263Ac
      a\uD834\uDD1Ec a\ud834\udd1ec     a"c     a\\u263   a\\u263Xc
      a\\uDD1Ec      a\\uD834c          a\\uD834\\u263Ac > -> $input {
   printf "%20s => ", $input;
   my $o = JSON-Unescape.parse($input, actions => JSON-Unescape-Actions.new).made;
   fail "Invalid JSON string" unless $o.defined;
   say $o;
   CATCH { default { say "Error: $_" } }
}

```

You may Attempt This Online!

Output:

```
                 abc => abc
                 a☺c => a☺c
                a\"c => a"c
  \u0061\u0062\u0063 => abc
                a\\c => a\c
            a\u263Ac => a☺c
           a\\u263Ac => a\u263Ac
      a\uD834\uDD1Ec => a𝄞c
      a\ud834\udd1ec => a𝄞c
                 a"c => Error: Invalid JSON string
              a\u263 => Error: Invalid JSON string
            a\u263Xc => Error: Invalid JSON string
            a\uDD1Ec => Error: Malformed UTF-16; unexpected low surrogate
            a\uD834c => Error: Malformed UTF-16; incomplete surrogate pair
      a\uD834\u263Ac => Error: Malformed UTF-16; incomplete surrogate pair
```


[User]
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend.

It is a very capable and remarquable tool, but also quite complex compared to older single- and double-byte character encodings.

How well prepared is your programming language for Unicode?

Task

Discuss and demonstrate its unicode awareness and capabilities.

Some suggested topics:

:   * How easy is it to present Unicode strings in source code?
    * Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
    * How well can the language communicate with the rest of the world?
    * Is it good at input/output with Unicode?
    * Is it convenient to manipulate Unicode strings in the language?
    * How broad/deep does the language support Unicode?
    * What encodings (e.g. UTF-8, UTF-16, etc) can be used?
    * Does it support normalization?

Note

This task is a bit unusual in that it encourages general discussion rather than clever coding.

See also

* Unicode variable names
* Terminal control/Display an extended character

[Assistant]
(formerly Perl 6)

Raku programs and strings are all in Unicode and operate at a grapheme abstraction level, which is agnostic to underlying encodings. (These are generally handled at program boundaries.) Opened files default to UTF-8 encoding. All Unicode character properties are in play, so any appropriate characters may be used as parts of identifiers, whitespace, or user-defined operators. For instance:

```
sub prefix:<∛> (\𝐕) { 𝐕 ** ⅓ }
say ∛27;  # prints 3

```

Non-Unicode strings are represented as Buf types rather than Str types, and Unicode operations may not be applied to Buf types without some kind of explicit conversion. Only ASCIIish operations are allowed on buffers.

Raku tracks the Unicode consortium standards releases and is generally up to the latest standard within a few months or so of its release. (currently at 15.0 as of February 2023)

* Supports the normalized forms NFC, NFD, NFKC, and NFKD, and character equivalence as specified in Unicode technical report #15.
* Built-in routines provide access to character classifications (Letter, Numeric. White-space, etc) and sub-classifications: (Letter-lowercase, Letter-uppercase, Numeric-digit, etc.)
* Allows users to use any Unicode character that has a Numeric property **as** that numeric value.
* Provides Unicode aware upper-case, lower-case and fold-case routines.
* Implements the Unicode technical standard #10 collation algorithm, (though not all optional mappings are supported yet).
* Provides built-in routines to access character names, do name-to-character character-to-ordinal and ordinal-to-character conversions.
* Works seamlessly with upper plane and private use plane character codepoints.
* Provides tools to deal with strings that contain invalid Unicode characters.

In general, it tries to make dealing with Unicode "just work".

Raku intends to support Unicode even better than Perl 5, which already does a great job in recent versions of accessing large swaths of Unicode spec. functionality. Raku improves on Perl 5 primarily by offering explicitly typed strings that always know which operations are sensical and which are not.

A very important distinctive characteristic of Raku to keep in mind is that it applies normalization (Unicode NFC form (Normalization Form Canonical)) automatically by default to all strings as showcased and explained on the String comparison page.


[User]
Task

1. Describe, and give a pointer to documentation on your languages use of characters *beyond* those of the ASCII character set in the naming of variables.
2. Show how to:

:   * Set a variable with a name including the 'Δ', (delta *character*), to 1
    * Increment it
    * Print its value.

Related task

* Case-sensitivity of identifiers

[Assistant]
(formerly Perl 6)
Raku is written in Unicode so, with narrow restrictions, nearly any Unicode letter can be used in identifiers.

See the current Raku documentation on the topic here: https://docs.raku.org/language/syntax#Identifiers

```
my $Δ = 1;
$Δ++;
say $Δ;

```

Function and subroutine names can also use Unicode characters: (as can methods, classes, packages, whatever...)

```
my @ᐁ = (0, 45, 60, 90);

sub π { pi };

sub postfix:<°>($degrees) { $degrees * π / 180 };

for @ᐁ -> $ಠ_ಠ { say sin $ಠ_ಠ° };

sub c͓͈̃͂̋̈̆̽h̥̪͕ͣ͛̊aͨͣ̍͞ơ̱͔̖͖̑̽ș̻̥ͬ̃̈ͩ { 'HE COMES' }

```

**See Also:**
Egyptian division


[User]
Task

Given a list of strings,   find characters appearing only in one string and once only.

The result should be given in alphabetical order.

Use the following list for this task:

```
        ["133252abcdeeffd",  "a6789798st",  "yxcdfgxcyz"]

```

Other tasks related to string operations:

Metrics

* Array length
* String length
* Copy a string
* Empty string  (assignment)

Counting

* Word frequency
* Letter frequency
* Jewels and stones
* I before E except after C
* Bioinformatics/base count
* Count occurrences of a substring
* Count how many vowels and consonants occur in a string

Remove/replace

* XXXX redacted
* Conjugate a Latin verb
* Remove vowels from a string
* String interpolation (included)
* Strip block comments
* Strip comments from a string
* Strip a set of characters from a string
* Strip whitespace from a string -- top and tail
* Strip control codes and extended characters from a string

Anagrams/Derangements/shuffling

* Word wheel
* ABC problem
* Sattolo cycle
* Knuth shuffle
* Ordered words
* Superpermutation minimisation
* Textonyms (using a phone text pad)
* Anagrams
* Anagrams/Deranged anagrams
* Permutations/Derangements

Find/Search/Determine

* ABC words
* Odd words
* Word ladder
* Semordnilap
* Word search
* Wordiff  (game)
* String matching
* Tea cup rim text
* Alternade words
* Changeable words
* State name puzzle
* String comparison
* Unique characters
* Unique characters in each string
* Extract file extension
* Levenshtein distance
* Palindrome detection
* Common list elements
* Longest common suffix
* Longest common prefix
* Compare a list of strings
* Longest common substring
* Find common directory path
* Words from neighbour ones
* Change e letters to i in words
* Non-continuous subsequences
* Longest common subsequence
* Longest palindromic substrings
* Longest increasing subsequence
* Words containing "the" substring
* Sum of the digits of n is substring of n
* Determine if a string is numeric
* Determine if a string is collapsible
* Determine if a string is squeezable
* Determine if a string has all unique characters
* Determine if a string has all the same characters
* Longest substrings without repeating characters
* Find words which contains all the vowels
* Find words which contain the most consonants
* Find words which contains more than 3 vowels
* Find words whose first and last three letters are equal
* Find words with alternating vowels and consonants

Formatting

* Substring
* Rep-string
* Word wrap
* String case
* Align columns
* Literals/String
* Repeat a string
* Brace expansion
* Brace expansion using ranges
* Reverse a string
* Phrase reversals
* Comma quibbling
* Special characters
* String concatenation
* Substring/Top and tail
* Commatizing numbers
* Reverse words in a string
* Suffixation of decimal numbers
* Long literals, with continuations
* Numerical and alphabetical suffixes
* Abbreviations, easy
* Abbreviations, simple
* Abbreviations, automatic

Song lyrics/poems/Mad Libs/phrases

* Mad Libs
* Magic 8-ball
* 99 bottles of beer
* The Name Game (a song)
* The Old lady swallowed a fly
* The Twelve Days of Christmas

Tokenize

* Text between
* Tokenize a string
* Word break problem
* Tokenize a string with escaping
* Split a character string based on change of character

Sequences

* Show ASCII table
* De Bruijn sequences
* Summarize and say sequence
* Generate lower case ASCII alphabet

[Assistant]
One has to wonder where the digits 0 through 9 come in the alphabet... 🤔 For that matter, What alphabet should they be in order of? Most of these entries seem to presuppose ASCII order but that isn't specified anywhere. What to do with characters outside of ASCII (or Latin-1)? Unicode ordinal order? Or maybe DUCET Unicode collation order? It's all very vague.

```
my @list = <133252abcdeeffd a6789798st yxcdfgxcyz>;

for @list, (@list, 'AАΑSäaoö٥🤔👨👩👧👧') {
    say "$_\nSemi-bogus \"Unicode natural sort\" order: ",
    .map( *.comb ).Bag.grep( *.value == 1 )».key.sort( { .unival, .NFKD[0], .fc } ).join,
    "\n        (DUCET) Unicode collation order: ",
    .map( *.comb ).Bag.grep( *.value == 1 )».key.collate.join, "\n";
}

```

Output:

```
133252abcdeeffd a6789798st yxcdfgxcyz
Semi-bogus "Unicode natural sort" order: 156bgstz
        (DUCET) Unicode collation order: 156bgstz

133252abcdeeffd a6789798st yxcdfgxcyz AАΑSäaoö٥🤔👨👩👧👧
Semi-bogus "Unicode natural sort" order: 15٥6ASäbgoöstzΑА👨👩👧👧🤔
        (DUCET) Unicode collation order: 👨👩👧👧🤔ä15٥6AbögosStzΑА
```


[User]
Task

Given a list of strings, find the characters appearing exactly once in each string.

The result should be in alphabetical order.

Use the following list for this task:

```
        ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"]

```

For this list, the result would be:
1 2 3 a b c

Other tasks related to string operations:

Metrics

* Array length
* String length
* Copy a string
* Empty string  (assignment)

Counting

* Word frequency
* Letter frequency
* Jewels and stones
* I before E except after C
* Bioinformatics/base count
* Count occurrences of a substring
* Count how many vowels and consonants occur in a string

Remove/replace

* XXXX redacted
* Conjugate a Latin verb
* Remove vowels from a string
* String interpolation (included)
* Strip block comments
* Strip comments from a string
* Strip a set of characters from a string
* Strip whitespace from a string -- top and tail
* Strip control codes and extended characters from a string

Anagrams/Derangements/shuffling

* Word wheel
* ABC problem
* Sattolo cycle
* Knuth shuffle
* Ordered words
* Superpermutation minimisation
* Textonyms (using a phone text pad)
* Anagrams
* Anagrams/Deranged anagrams
* Permutations/Derangements

Find/Search/Determine

* ABC words
* Odd words
* Word ladder
* Semordnilap
* Word search
* Wordiff  (game)
* String matching
* Tea cup rim text
* Alternade words
* Changeable words
* State name puzzle
* String comparison
* Unique characters
* Unique characters in each string
* Extract file extension
* Levenshtein distance
* Palindrome detection
* Common list elements
* Longest common suffix
* Longest common prefix
* Compare a list of strings
* Longest common substring
* Find common directory path
* Words from neighbour ones
* Change e letters to i in words
* Non-continuous subsequences
* Longest common subsequence
* Longest palindromic substrings
* Longest increasing subsequence
* Words containing "the" substring
* Sum of the digits of n is substring of n
* Determine if a string is numeric
* Determine if a string is collapsible
* Determine if a string is squeezable
* Determine if a string has all unique characters
* Determine if a string has all the same characters
* Longest substrings without repeating characters
* Find words which contains all the vowels
* Find words which contain the most consonants
* Find words which contains more than 3 vowels
* Find words whose first and last three letters are equal
* Find words with alternating vowels and consonants

Formatting

* Substring
* Rep-string
* Word wrap
* String case
* Align columns
* Literals/String
* Repeat a string
* Brace expansion
* Brace expansion using ranges
* Reverse a string
* Phrase reversals
* Comma quibbling
* Special characters
* String concatenation
* Substring/Top and tail
* Commatizing numbers
* Reverse words in a string
* Suffixation of decimal numbers
* Long literals, with continuations
* Numerical and alphabetical suffixes
* Abbreviations, easy
* Abbreviations, simple
* Abbreviations, automatic

Song lyrics/poems/Mad Libs/phrases

* Mad Libs
* Magic 8-ball
* 99 bottles of beer
* The Name Game (a song)
* The Old lady swallowed a fly
* The Twelve Days of Christmas

Tokenize

* Text between
* Tokenize a string
* Word break problem
* Tokenize a string with escaping
* Split a character string based on change of character

Sequences

* Show ASCII table
* De Bruijn sequences
* Summarize and say sequence
* Generate lower case ASCII alphabet

[Assistant]
```
my $strings = <1a3c52debeffd 2b6178c97a938stf 3ycxdb1fgxa2yz>;

put sort keys [∩] $strings.map: *.comb.Bag.grep: *.value == 1

```

Output:

```
1 2 3 a b c
```


[User]
Demonstrate any support for Unit testing built into the language implementation.

See https://en.wikipedia.org/wiki/Unit\_testing and Test a function for more information.

Clearly state whether this support is internal, or external to the interpreter or compiler used.

[Assistant]
(formerly Perl 6)
Raku does not really have a mechanism built into the compiler to do unit testing, (It **does** have design-by-contract capabilities built in, but that is more for run-time, not really for unit testing.) Raku, and Perl in general **does** have unit testing built into the community. The Test-Anything-Protocol was invented and developed specifically to do unit testing on the original version of Perl, is still heavily used for modern versions, and has become a major standard for unit testing in many different languages other than Perl.

Testing is such a basic value in Raku, that a suite of unit tests **is** the language specification. As decreed by Larry Wall, the original author of Perl and the lead designer of Raku, anything that can pass "roast", the official Raku test suite, or at least majority portions of it, can call itself Raku.

Unit testing tools are not built in to the base compiler. Basic tools are distributed with the compiler as loadable modules. Many more complex toolkits and test harnesses are available through the Raku ecosystem. In general, it is uncommon to include testing code in with run-time code; not unheard-of and not forbidden, but uncommon. Instead Raku modules by convention and community pressure tend to have a test suite that is automatically run when the module is installed. Again, there is no rule that a module that is released for public consumption **must** have a test suite, but the community tends to favour modules that have them and discourage/avoid those without.


[User]
One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.

(Alan Turing introduced the idea of such a machine in 1936–1937.)

Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.

Task

Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.

Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.

The three permissible actions on the tape are "left", "right" and "stay".

To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.

**Simple incrementer**

* **States:** q0, qf
* **Initial state:** q0
* **Terminating states:** qf
* **Permissible symbols:** B, 1
* **Blank symbol:** B
* **Rules:**
  + (q0, 1, 1, right, q0)
  + (q0, B, 1, stay, qf)

The input for this machine should be a tape of `1 1 1`

**Three-state busy beaver**

* **States:** a, b, c, halt
* **Initial state:** a
* **Terminating states:** halt
* **Permissible symbols:** 0, 1
* **Blank symbol:** 0
* **Rules:**
  + (a, 0, 1, right, b)
  + (a, 1, 1, left, c)
  + (b, 0, 1, left, a)
  + (b, 1, 1, right, b)
  + (c, 0, 1, left, b)
  + (c, 1, 1, stay, halt)

The input for this machine should be an empty tape.

**Bonus:**

**5-state, 2-symbol probable Busy Beaver machine from Wikipedia**

* **States:** A, B, C, D, E, H
* **Initial state:** A
* **Terminating states:** H
* **Permissible symbols:** 0, 1
* **Blank symbol:** 0
* **Rules:**
  + (A, 0, 1, right, B)
  + (A, 1, 1, left, C)
  + (B, 0, 1, right, C)
  + (B, 1, 1, right, B)
  + (C, 0, 1, right, D)
  + (C, 1, 0, left, E)
  + (D, 0, 1, left, A)
  + (D, 1, 1, left, D)
  + (E, 0, 1, stay, H)
  + (E, 1, 0, left, A)

The input for this machine should be an empty tape.

This machine runs for more than 47 millions steps.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

**Works with**: Rakudo version 2018.03

```
sub run_utm(:$state! is copy, :$blank!, :@rules!, :@tape = [$blank], :$halt, :$pos is copy = 0) {
    $pos += @tape if $pos < 0;
    die "Bad initial position" unless $pos ~~ ^@tape;

STEP: loop {
        print "$state\t";
        for ^@tape {
            my $v = @tape[$_];
            print $_ == $pos ?? "[$v]" !! " $v ";
        }
        print "\n";

        last if $state eq $halt;

        for @rules -> @rule {
            my ($s0, $v0, $v1, $dir, $s1) = @rule;
            next unless $s0 eq $state and @tape[$pos] eq $v0;

            @tape[$pos] = $v1;

            given $dir {
                when 'left' {
                    if $pos == 0 { unshift @tape, $blank }
                    else { $pos-- }
                }
                when 'right' {
                    push @tape, $blank if ++$pos >= @tape;
                }
            }

            $state = $s1;
            next STEP;

        }
        die 'No matching rules';
    }

}

say "incr machine";
run_utm	:halt<qf>,
    :state<q0>,
    :tape[1,1,1],
    :blank<B>,
    :rules[
        [< q0 1 1 right q0 >],
        [< q0 B 1 stay  qf >]
    ];

say "\nbusy beaver";
run_utm :halt<halt>,
    :state<a>,
    :blank<0>,
    :rules[
        [< a 0 1 right b >],
        [< a 1 1 left  c >],
        [< b 0 1 left  a >],
        [< b 1 1 right b >],
        [< c 0 1 left  b >],
        [< c 1 1 stay  halt >]
    ];

say "\nsorting test";
run_utm :halt<STOP>,
    :state<A>,
    :blank<0>,
    :tape[< 2 2 2 1 2 2 1 2 1 2 1 2 1 2 >],
    :rules[
        [< A 1 1 right A >],
        [< A 2 3 right B >],
        [< A 0 0 left  E >],
        [< B 1 1 right B >],
        [< B 2 2 right B >],
        [< B 0 0 left  C >],
        [< C 1 2 left  D >],
        [< C 2 2 left  C >],
        [< C 3 2 left  E >],
        [< D 1 1 left  D >],
        [< D 2 2 left  D >],
        [< D 3 1 right A >],
        [< E 1 1 left  E >],
        [< E 0 0 right STOP >]
    ];

```

Output:

```
incr machine
q0	[1] 1  1
q0	 1 [1] 1
q0	 1  1 [1]
q0	 1  1  1 [B]
qf	 1  1  1 [1]

busy beaver
a	[0]
b	 1 [0]
a	[1] 1
c	[0] 1  1
b	[0] 1  1  1
a	[0] 1  1  1  1
b	 1 [1] 1  1  1
b	 1  1 [1] 1  1
b	 1  1  1 [1] 1
b	 1  1  1  1 [1]
b	 1  1  1  1  1 [0]
a	 1  1  1  1 [1] 1
c	 1  1  1 [1] 1  1
halt	 1  1  1 [1] 1  1

sorting test
A	[2] 2  2  1  2  2  1  2  1  2  1  2  1  2
B	 3 [2] 2  1  2  2  1  2  1  2  1  2  1  2
B	 3  2 [2] 1  2  2  1  2  1  2  1  2  1  2
B	 3  2  2 [1] 2  2  1  2  1  2  1  2  1  2
B	 3  2  2  1 [2] 2  1  2  1  2  1  2  1  2
B	 3  2  2  1  2 [2] 1  2  1  2  1  2  1  2
B	 3  2  2  1  2  2 [1] 2  1  2  1  2  1  2
B	 3  2  2  1  2  2  1 [2] 1  2  1  2  1  2
B	 3  2  2  1  2  2  1  2 [1] 2  1  2  1  2
B	 3  2  2  1  2  2  1  2  1 [2] 1  2  1  2
B	 3  2  2  1  2  2  1  2  1  2 [1] 2  1  2
B	 3  2  2  1  2  2  1  2  1  2  1 [2] 1  2
B	 3  2  2  1  2  2  1  2  1  2  1  2 [1] 2
B	 3  2  2  1  2  2  1  2  1  2  1  2  1 [2]
B	 3  2  2  1  2  2  1  2  1  2  1  2  1  2 [0]
C	 3  2  2  1  2  2  1  2  1  2  1  2  1 [2] 0
C	 3  2  2  1  2  2  1  2  1  2  1  2 [1] 2  0
D	 3  2  2  1  2  2  1  2  1  2  1 [2] 2  2  0
D	 3  2  2  1  2  2  1  2  1  2 [1] 2  2  2  0
D	 3  2  2  1  2  2  1  2  1 [2] 1  2  2  2  0
D	 3  2  2  1  2  2  1  2 [1] 2  1  2  2  2  0
D	 3  2  2  1  2  2  1 [2] 1  2  1  2  2  2  0
D	 3  2  2  1  2  2 [1] 2  1  2  1  2  2  2  0
D	 3  2  2  1  2 [2] 1  2  1  2  1  2  2  2  0
D	 3  2  2  1 [2] 2  1  2  1  2  1  2  2  2  0
D	 3  2  2 [1] 2  2  1  2  1  2  1  2  2  2  0
D	 3  2 [2] 1  2  2  1  2  1  2  1  2  2  2  0
D	 3 [2] 2  1  2  2  1  2  1  2  1  2  2  2  0
D	[3] 2  2  1  2  2  1  2  1  2  1  2  2  2  0
A	 1 [2] 2  1  2  2  1  2  1  2  1  2  2  2  0
B	 1  3 [2] 1  2  2  1  2  1  2  1  2  2  2  0
B	 1  3  2 [1] 2  2  1  2  1  2  1  2  2  2  0
B	 1  3  2  1 [2] 2  1  2  1  2  1  2  2  2  0
B	 1  3  2  1  2 [2] 1  2  1  2  1  2  2  2  0
B	 1  3  2  1  2  2 [1] 2  1  2  1  2  2  2  0
B	 1  3  2  1  2  2  1 [2] 1  2  1  2  2  2  0
B	 1  3  2  1  2  2  1  2 [1] 2  1  2  2  2  0
B	 1  3  2  1  2  2  1  2  1 [2] 1  2  2  2  0
B	 1  3  2  1  2  2  1  2  1  2 [1] 2  2  2  0
B	 1  3  2  1  2  2  1  2  1  2  1 [2] 2  2  0
B	 1  3  2  1  2  2  1  2  1  2  1  2 [2] 2  0
B	 1  3  2  1  2  2  1  2  1  2  1  2  2 [2] 0
B	 1  3  2  1  2  2  1  2  1  2  1  2  2  2 [0]
C	 1  3  2  1  2  2  1  2  1  2  1  2  2 [2] 0
C	 1  3  2  1  2  2  1  2  1  2  1  2 [2] 2  0
C	 1  3  2  1  2  2  1  2  1  2  1 [2] 2  2  0
C	 1  3  2  1  2  2  1  2  1  2 [1] 2  2  2  0
D	 1  3  2  1  2  2  1  2  1 [2] 2  2  2  2  0
D	 1  3  2  1  2  2  1  2 [1] 2  2  2  2  2  0
D	 1  3  2  1  2  2  1 [2] 1  2  2  2  2  2  0
D	 1  3  2  1  2  2 [1] 2  1  2  2  2  2  2  0
D	 1  3  2  1  2 [2] 1  2  1  2  2  2  2  2  0
D	 1  3  2  1 [2] 2  1  2  1  2  2  2  2  2  0
D	 1  3  2 [1] 2  2  1  2  1  2  2  2  2  2  0
D	 1  3 [2] 1  2  2  1  2  1  2  2  2  2  2  0
D	 1 [3] 2  1  2  2  1  2  1  2  2  2  2  2  0
A	 1  1 [2] 1  2  2  1  2  1  2  2  2  2  2  0
B	 1  1  3 [1] 2  2  1  2  1  2  2  2  2  2  0
B	 1  1  3  1 [2] 2  1  2  1  2  2  2  2  2  0
B	 1  1  3  1  2 [2] 1  2  1  2  2  2  2  2  0
B	 1  1  3  1  2  2 [1] 2  1  2  2  2  2  2  0
B	 1  1  3  1  2  2  1 [2] 1  2  2  2  2  2  0
B	 1  1  3  1  2  2  1  2 [1] 2  2  2  2  2  0
B	 1  1  3  1  2  2  1  2  1 [2] 2  2  2  2  0
B	 1  1  3  1  2  2  1  2  1  2 [2] 2  2  2  0
B	 1  1  3  1  2  2  1  2  1  2  2 [2] 2  2  0
B	 1  1  3  1  2  2  1  2  1  2  2  2 [2] 2  0
B	 1  1  3  1  2  2  1  2  1  2  2  2  2 [2] 0
B	 1  1  3  1  2  2  1  2  1  2  2  2  2  2 [0]
C	 1  1  3  1  2  2  1  2  1  2  2  2  2 [2] 0
C	 1  1  3  1  2  2  1  2  1  2  2  2 [2] 2  0
C	 1  1  3  1  2  2  1  2  1  2  2 [2] 2  2  0
C	 1  1  3  1  2  2  1  2  1  2 [2] 2  2  2  0
C	 1  1  3  1  2  2  1  2  1 [2] 2  2  2  2  0
C	 1  1  3  1  2  2  1  2 [1] 2  2  2  2  2  0
D	 1  1  3  1  2  2  1 [2] 2  2  2  2  2  2  0
D	 1  1  3  1  2  2 [1] 2  2  2  2  2  2  2  0
D	 1  1  3  1  2 [2] 1  2  2  2  2  2  2  2  0
D	 1  1  3  1 [2] 2  1  2  2  2  2  2  2  2  0
D	 1  1  3 [1] 2  2  1  2  2  2  2  2  2  2  0
D	 1  1 [3] 1  2  2  1  2  2  2  2  2  2  2  0
A	 1  1  1 [1] 2  2  1  2  2  2  2  2  2  2  0
A	 1  1  1  1 [2] 2  1  2  2  2  2  2  2  2  0
B	 1  1  1  1  3 [2] 1  2  2  2  2  2  2  2  0
B	 1  1  1  1  3  2 [1] 2  2  2  2  2  2  2  0
B	 1  1  1  1  3  2  1 [2] 2  2  2  2  2  2  0
B	 1  1  1  1  3  2  1  2 [2] 2  2  2  2  2  0
B	 1  1  1  1  3  2  1  2  2 [2] 2  2  2  2  0
B	 1  1  1  1  3  2  1  2  2  2 [2] 2  2  2  0
B	 1  1  1  1  3  2  1  2  2  2  2 [2] 2  2  0
B	 1  1  1  1  3  2  1  2  2  2  2  2 [2] 2  0
B	 1  1  1  1  3  2  1  2  2  2  2  2  2 [2] 0
B	 1  1  1  1  3  2  1  2  2  2  2  2  2  2 [0]
C	 1  1  1  1  3  2  1  2  2  2  2  2  2 [2] 0
C	 1  1  1  1  3  2  1  2  2  2  2  2 [2] 2  0
C	 1  1  1  1  3  2  1  2  2  2  2 [2] 2  2  0
C	 1  1  1  1  3  2  1  2  2  2 [2] 2  2  2  0
C	 1  1  1  1  3  2  1  2  2 [2] 2  2  2  2  0
C	 1  1  1  1  3  2  1  2 [2] 2  2  2  2  2  0
C	 1  1  1  1  3  2  1 [2] 2  2  2  2  2  2  0
C	 1  1  1  1  3  2 [1] 2  2  2  2  2  2  2  0
D	 1  1  1  1  3 [2] 2  2  2  2  2  2  2  2  0
D	 1  1  1  1 [3] 2  2  2  2  2  2  2  2  2  0
A	 1  1  1  1  1 [2] 2  2  2  2  2  2  2  2  0
B	 1  1  1  1  1  3 [2] 2  2  2  2  2  2  2  0
B	 1  1  1  1  1  3  2 [2] 2  2  2  2  2  2  0
B	 1  1  1  1  1  3  2  2 [2] 2  2  2  2  2  0
B	 1  1  1  1  1  3  2  2  2 [2] 2  2  2  2  0
B	 1  1  1  1  1  3  2  2  2  2 [2] 2  2  2  0
B	 1  1  1  1  1  3  2  2  2  2  2 [2] 2  2  0
B	 1  1  1  1  1  3  2  2  2  2  2  2 [2] 2  0
B	 1  1  1  1  1  3  2  2  2  2  2  2  2 [2] 0
B	 1  1  1  1  1  3  2  2  2  2  2  2  2  2 [0]
C	 1  1  1  1  1  3  2  2  2  2  2  2  2 [2] 0
C	 1  1  1  1  1  3  2  2  2  2  2  2 [2] 2  0
C	 1  1  1  1  1  3  2  2  2  2  2 [2] 2  2  0
C	 1  1  1  1  1  3  2  2  2  2 [2] 2  2  2  0
C	 1  1  1  1  1  3  2  2  2 [2] 2  2  2  2  0
C	 1  1  1  1  1  3  2  2 [2] 2  2  2  2  2  0
C	 1  1  1  1  1  3  2 [2] 2  2  2  2  2  2  0
C	 1  1  1  1  1  3 [2] 2  2  2  2  2  2  2  0
C	 1  1  1  1  1 [3] 2  2  2  2  2  2  2  2  0
E	 1  1  1  1 [1] 2  2  2  2  2  2  2  2  2  0
E	 1  1  1 [1] 1  2  2  2  2  2  2  2  2  2  0
E	 1  1 [1] 1  1  2  2  2  2  2  2  2  2  2  0
E	 1 [1] 1  1  1  2  2  2  2  2  2  2  2  2  0
E	[1] 1  1  1  1  2  2  2  2  2  2  2  2  2  0
E	[0] 1  1  1  1  1  2  2  2  2  2  2  2  2  2  0
STOP	 0 [1] 1  1  1  1  2  2  2  2  2  2  2  2  2  0
```


[User]
Task

Write a program that will list everything in the current folder,   similar to:

:   :   :   * the Unix utility   “ls”   [1]       or
            * the Windows terminal command   “DIR”

The output must be sorted, but printing extended details and producing multi-column output is not required.

Example output

For the list of paths:

```
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b

```

When the program is executed in   `/foo`,   it should print:

```
bar

```

and when the program is executed in   `/foo/bar`,   it should print:

```
1
2
a
b

```

[Assistant]
(formerly Perl 6)

There is a dir builtin command which returns a list of IO::Path objects. We stringify them all with a hyperoperator before sorting the strings.

```
.say for sort ~«dir

```


[User]
Definitions

As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten.

───── Definition from OEIS ─────:

Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.

───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────:

(*arithmetic*)   that cannot be turned into a prime number by changing just one of its digits to any other
digit.   (sic)

**Unprimeable** numbers are also spelled:   **unprimable**.

All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.

Examples

**190**   isn't unprimeable,   because by changing the zero digit into a three yields   **193**,   which is a prime.

The number   **200**   is unprimeable,   since none of the numbers   **201, 202, 203, ··· 209**   are
prime, and all the other numbers obtained by changing a single digit to
produce   **100, 300, 400, ··· 900**,   or   **210, 220, 230, ··· 290**   which are all even.

It is valid to change   **189**   into   **089**   by changing the   **1**   (one)   into
a   **0**   (zero),   which then the leading zero can be removed,   and then treated as if
the   "new"   number is   **89**.

Task
:   :   * show the first   **35**   unprimeable numbers   (horizontally, on one line, preferably with a title)
        * show the   **600th**   unprimeable number
        * (optional) show the lowest unprimeable number ending in a specific decimal digit   (**0, 1, 2, 3, 4, 5, 6, 7, 8, 9**)
        * (optional) use commas in the numbers where appropriate

Show all output here, on this page.

Also see
:   * the     OEIS     entry:   A118118 (unprimeable)
    * with some useful counts to compare unprimeable number
    * the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable
    * from the Adam Spencer book   (page 200):   *Adam Spencer's World of Numbers*       (Xoum Publishing)

[Assistant]
(formerly Perl 6)

**Library:** ntheory

```
use ntheory:from<Perl5> <is_prime>;
use Lingua::EN::Numbers;

sub is-unprimeable (\n) {
     return False if n.&is_prime;
     my \chrs = n.chars;
     for ^chrs -> \place {
         my \pow = 10**(chrs - place - 1);
         my \this = n.substr(place, 1) × pow;
         ^10 .map: -> \dgt {
             next if this == dgt;
             return False if is_prime(n - this + dgt × pow)
         }
     }
     True
}

my @ups = lazy ^∞ .grep: { .&is-unprimeable };

say "First 35 unprimeables:\n" ~ @ups[^35];

say "\n{ordinal-digit(600, :u)} unprimeable: " ~ comma( @ups[599] ) ~ "\n";

^10 .map: -> \n {
    print "First unprimeable that ends with {n}: " ~
    sprintf "%9s\n", comma (n, *+10 … *).race.first: { .&is-unprimeable }
}

```

Output:

```
First 35 unprimeables:
200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890

600ᵗʰ unprimeable: 5,242

First unprimeable that ends with 0:       200
First unprimeable that ends with 1:   595,631
First unprimeable that ends with 2:       322
First unprimeable that ends with 3: 1,203,623
First unprimeable that ends with 4:       204
First unprimeable that ends with 5:       325
First unprimeable that ends with 6:       206
First unprimeable that ends with 7:   872,897
First unprimeable that ends with 8:       208
First unprimeable that ends with 9:   212,159
```


[User]
Definitions
:   * *Untouchable numbers*   are also known as   *nonaliquot numbers*.

:   * An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)

:   * The   *sum of all the proper divisors*   is also known as   the   *aliquot sum*.

:   * An   untouchable   are those numbers that are not in the image of the aliquot sum function.   (From Wikipedia)

:   * Untouchable numbers:   impossible values for the sum of all aliquot parts function.   (From OEIS:   The On-line Encyclopedia of Integer Sequences®)

:   * An untouchable number is a positive integer that is not the sum of the proper divisors of any number.   (From MathWorld™)

Observations and conjectures

All untouchable numbers   >  **5**  are composite numbers.

No untouchable number is perfect.

No untouchable number is sociable.

No untouchable number is a Mersenne prime.

No untouchable number is   one more   than a prime number,   since if   **p**   is prime,   then
the sum of the proper divisors of   **p2**   is  **p + 1**.

No untouchable number is   three more   than an odd prime number,   since if   **p**   is an odd prime,   then the
sum of the proper divisors of   **2p**   is  **p + 3**.

The number  **5**  is believed to be the only odd untouchable number,   but this has not been proven:   it would follow from a
slightly stronger version of the   Goldbach's conjecture,   since the sum of the
proper divisors of   **pq**   (with   **p**, **q**   being
distinct primes)   is   **1 + p + q**.

There are infinitely many untouchable numbers,   a fact that was proven
by   Paul Erdős.

According to Chen & Zhao,   their natural density is at least   **d > 0.06**.

Task
:   * show  (in a grid format)  all untouchable numbers  ≤  2,000.
    * show (for the above)   the   *count*   of untouchable numbers.
    * show the   *count*   of untouchable numbers from unity up to   (inclusive):

    :   :   :   * 10
                * 100
                * 1,000
                * 10,000
                * 100,000
                * ... or as high as is you think is practical.

    * all output is to be shown here, on this page.

See also
:   * Wolfram MathWorld:   untouchable number.
    * OEIS:   A005114 untouchable numbers.
    * OEIS:   a list of all untouchable numbers below 100,000   (inclusive).
    * Wikipedia: untouchable number.
    * Wikipedia: Goldbach's conjecture.

[Assistant]
Borrow the proper divisors routine from here.

**Translation of**: Wren

```
# 20210220 Raku programming solution

sub propdiv (\x) {
   my @l = 1 if x > 1;
   (2 .. x.sqrt.floor).map: -> \d {
      unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
   }
   @l
}

sub sieve (\n) {
   my %s;
   for (0..(n+1)) -> \k {
      given ( [+] propdiv k ) { %s{$_} = True if $_ ≤ (n+1) }
   }
   %s;
}

my \limit = 1e5;
my %c = ( grep { !.is-prime }, 1..limit ).Set; # store composites
my %s = sieve(14 * limit);
my @untouchable = 2, 5;

loop ( my \n = $ = 6 ; n ≤ limit ; n += 2 ) {
   @untouchable.append(n) if (!%s{n} && %c{n-1} && %c{n-3})
}

my ($c, $last) = 0, False;
for @untouchable.rotor(10) {
   say [~] @_».&{$c++ ; $_ > 2000 ?? ( $last = True and last ) !! .fmt: "%6d "}
   $c-- and last if $last
}

say "\nList of untouchable numbers ≤ 2,000 : $c \n";

my ($p, $count) = 10,0;
BREAK: for @untouchable -> \n {
   $count++;
   if (n > $p) {
      printf "%6d untouchable numbers were found  ≤ %7d\n", $count-1, $p;
      last BREAK if limit == ($p *= 10)
   }
}
printf "%6d untouchable numbers were found  ≤ %7d\n", +@untouchable, limit

```

Output:

```
     2      5     52     88     96    120    124    146    162    188
   206    210    216    238    246    248    262    268    276    288
   290    292    304    306    322    324    326    336    342    372
   406    408    426    430    448    472    474    498    516    518
   520    530    540    552    556    562    576    584    612    624
   626    628    658    668    670    708    714    718    726    732
   738    748    750    756    766    768    782    784    792    802
   804    818    836    848    852    872    892    894    896    898
   902    926    934    936    964    966    976    982    996   1002
  1028   1044   1046   1060   1068   1074   1078   1080   1102   1116
  1128   1134   1146   1148   1150   1160   1162   1168   1180   1186
  1192   1200   1212   1222   1236   1246   1248   1254   1256   1258
  1266   1272   1288   1296   1312   1314   1316   1318   1326   1332
  1342   1346   1348   1360   1380   1388   1398   1404   1406   1418
  1420   1422   1438   1476   1506   1508   1510   1522   1528   1538
  1542   1566   1578   1588   1596   1632   1642   1650   1680   1682
  1692   1716   1718   1728   1732   1746   1758   1766   1774   1776
  1806   1816   1820   1822   1830   1838   1840   1842   1844   1852
  1860   1866   1884   1888   1894   1896   1920   1922   1944   1956
  1958   1960   1962   1972   1986   1992

List of untouchable numbers ≤ 2,000 : 196

     2 untouchable numbers were found  ≤      10
     5 untouchable numbers were found  ≤     100
    89 untouchable numbers were found  ≤    1000
  1212 untouchable numbers were found  ≤   10000
 13863 untouchable numbers were found  ≤  100000

```