[User]
Generate the sequence **an** where each term in **a** is the smallest **n** digit prime number *(in base 10)* composed entirely of the digits **1** and **2**.

It is conjectured, though not proven, that a conforming prime exists for all **n**. No counter examples have been found up to several thousand digits.

Task

* Find and show here, the first **20** elements in the sequence (from **1** digit through **20** digits), or as many as reasonably supported by your language if it is fewer.

Stretch

* Find and and show the abbreviated values for the elements with **n** equal to **100** through **2000** in increments of **100**.

:   Shorten the displayed number by replacing any leading **1**s in the number with the count of **1**s, and show the remainder of the number. *(See Raku example for reference)*

See also

* OEIS:A036229 - Smallest n-digit prime containing only digits 1 or 2 or -1 if no such prime exists

[Assistant]
### Task specific

```
sub condense ($n) { my $i = $n.index(2); $i ?? "(1 x $i) {$n.substr($i)}" !! $n }

sub onetwo ($d, $s='') { take $s and return unless $d; onetwo($d-1,$s~$_) for 1,2 }

sub get-onetwo ($d) { (gather onetwo $d).hyper.grep(&is-prime)[0] }

printf "%4d: %s\n", $_, get-onetwo($_) for 1..20;
printf "%4d: %s\n", $_, condense get-onetwo($_) for (1..20) »×» 100;

```

Output:

```
   1: 2
   2: 11
   3: 211
   4: 2111
   5: 12211
   6: 111121
   7: 1111211
   8: 11221211
   9: 111112121
  10: 1111111121
  11: 11111121121
  12: 111111211111
  13: 1111111121221
  14: 11111111112221
  15: 111111112111121
  16: 1111111112122111
  17: 11111111111112121
  18: 111111111111112111
  19: 1111111111111111111
  20: 11111111111111212121
 100: (1 x 92) 21112211
 200: (1 x 192) 21112211
 300: (1 x 288) 211121112221
 400: (1 x 390) 2111122121
 500: (1 x 488) 221222111111
 600: (1 x 590) 2112222221
 700: (1 x 689) 21111111111
 800: (1 x 787) 2122222221111
 900: (1 x 891) 222221221
1000: (1 x 988) 222122111121
1100: (1 x 1087) 2112111121111
1200: (1 x 1191) 211222211
1300: (1 x 1289) 22121221121
1400: (1 x 1388) 222211222121
1500: (1 x 1489) 21112121121
1600: (1 x 1587) 2121222122111
1700: (1 x 1688) 212121211121
1800: (1 x 1791) 221211121
1900: (1 x 1889) 22212212211
2000: (1 x 1989) 22121121211
```

### Generalized

This version will do the task requirements, but will also find (without modification):

* OEIS:A036929 - Smallest n digit prime using only 0 and 1 (or '0' if none exists)
* OEIS:A036229 - Smallest n digit prime using only 1 and 2 (or '0' if none exists) <-- The task
* OEIS:A036930 - Smallest n digit prime using only 1 and 3 (or '0' if none exists)
* OEIS:A036931 - Smallest n digit prime using only 1 and 4 (or '0' if none exists)
* OEIS:A036932 - Smallest n digit prime using only 1 and 5 (or '0' if none exists)
* OEIS:A036933 - Smallest n digit prime using only 1 and 6 (or '0' if none exists)
* OEIS:A036934 - Smallest n digit prime using only 1 and 7 (or '0' if none exists)
* OEIS:A036935 - Smallest n digit prime using only 1 and 8 (or '0' if none exists)
* OEIS:A036936 - Smallest n digit prime using only 1 and 9 (or '0' if none exists)
* OEIS:A036937 - Smallest n digit prime using only 2 and 3 (or '0' if none exists)
* OEIS:A036938 - Smallest n digit prime using only 2 and 7 (or '0' if none exists)
* OEIS:A036939 - Smallest n digit prime using only 2 and 9 (or '0' if none exists)
* OEIS:A036940 - Smallest n digit prime using only 3 and 4 (or '0' if none exists)
* OEIS:A036941 - Smallest n digit prime using only 3 and 5 (or '0' if none exists)
* OEIS:A036942 - Smallest n digit prime using only 3 and 7 (or '0' if none exists)
* OEIS:A036943 - Smallest n digit prime using only 3 and 8 (or '0' if none exists)
* OEIS:A036944 - Smallest n digit prime using only 4 and 7 (or '0' if none exists)
* OEIS:A036945 - Smallest n digit prime using only 4 and 9 (or '0' if none exists)
* OEIS:A036946 - Smallest n digit prime using only 5 and 7 (or '0' if none exists)
* OEIS:A036947 - Smallest n digit prime using only 5 and 9 (or '0' if none exists)
* OEIS:A036948 - Smallest n digit prime using only 6 and 7 (or '0' if none exists)
* OEIS:A036949 - Smallest n digit prime using only 7 and 8 (or '0' if none exists)
* OEIS:A036950 - Smallest n digit prime using only 7 and 9 (or '0' if none exists)
* OEIS:A036951 - Smallest n digit prime using only 8 and 9 (or '0' if none exists)

Really, the only one that is a little tricky is the first one (0,1). That one required some specialized logic. All of the rest would work with the task specific version with different hard coded digits.

Limited the stretch to keep the run time reasonable. Finishes all in around 12 seconds on my system.

```
for 929,(0,1),229,(1,2),930,(1,3),931,(1,4),932,(1,5),933,(1,6),934,(1,7),935,(1,8),
    936,(1,9),937,(2,3),938,(2,7),939,(2,9),940,(3,4),941,(3,5),942,(3,7),943,(3,8),
    944,(4,7),945,(4,9),946,(5,7),947,(5,9),948,(6,7),949,(7,8),950,(7,9),951,(8,9)
  -> $oeis, $pair {

    say "\nOEIS:A036{$oeis} - Smallest n digit prime using only {$pair[0]} and {$pair[1]} (or '0' if none exists):";

    sub condense ($n) { $n.subst(/(.) {} :my $repeat=$0; ($repeat**{9..*})/, -> $/ {"($0 x {1+$1.chars}) "}) }

    sub build ($digit, $sofar='') { take $sofar and return unless $digit; build($digit-1,$sofar~$_) for |$pair }

    sub get-prime ($digits) {
        ($pair[0] ?? (gather build $digits).first: &is-prime
        !! (gather build $digits-1, $pair[1]).first: &is-prime
        ) // 0
    }

    printf "%4d: %s\n", $_, condense .&get-prime for flat 1..20, 100, 200;
}

```

Output:

```
OEIS:A036929 - Smallest n digit prime using only 0 and 1 (or '0' if none exists):
   1: 0
   2: 11
   3: 101
   4: 0
   5: 10111
   6: 101111
   7: 1011001
   8: 10010101
   9: 100100111
  10: 1000001011
  11: 10000001101
  12: 100000001111
  13: 1000000111001
  14: 10000000001011
  15: 100000000100101
  16: 1(0 x 10) 11101
  17: 1(0 x 12) 1101
  18: 1(0 x 11) 100111
  19: 1(0 x 13) 10011
  20: 1(0 x 12) 1100101
 100: 1(0 x 93) 101101
 200: 1(0 x 189) 1110101011

OEIS:A036229 - Smallest n digit prime using only 1 and 2 (or '0' if none exists):
   1: 2
   2: 11
   3: 211
   4: 2111
   5: 12211
   6: 111121
   7: 1111211
   8: 11221211
   9: 111112121
  10: 1111111121
  11: 11111121121
  12: 111111211111
  13: 1111111121221
  14: (1 x 10) 2221
  15: 111111112111121
  16: 1111111112122111
  17: (1 x 13) 2121
  18: (1 x 14) 2111
  19: (1 x 19)
  20: (1 x 14) 212121
 100: (1 x 92) 21112211
 200: (1 x 192) 21112211

... many lines manually omitted ...

OEIS:A036950 - Smallest n digit prime using only 7 and 9 (or '0' if none exists):
   1: 7
   2: 79
   3: 797
   4: 0
   5: 77797
   6: 777977
   7: 7777997
   8: 77779799
   9: 777777799
  10: 7777779799
  11: 77777779979
  12: 777777779777
  13: 7777777779977
  14: (7 x 11) 977
  15: (7 x 11) 9797
  16: (7 x 11) 97799
  17: (7 x 15) 97
  18: (7 x 13) 97977
  19: (7 x 16) 997
  20: (7 x 16) 9997
 100: (7 x 93) 9979979
 200: (7 x 192) 99777779

OEIS:A036951 - Smallest n digit prime using only 8 and 9 (or '0' if none exists):
   1: 0
   2: 89
   3: 0
   4: 8999
   5: 89899
   6: 888989
   7: 8888989
   8: 88888999
   9: 888898889
  10: 8888888989
  11: 88888888999
  12: 888888898999
  13: 8888888999899
  14: (8 x 13) 9
  15: (8 x 10) 98999
  16: (8 x 10) 989999
  17: (8 x 16) 9
  18: (8 x 13) 98889
  19: (8 x 16) 989
  20: (8 x 13) 9888989
 100: (8 x 91) 998998889
 200: (8 x 190) 9888898989
```


[User]
Task

Display a smooth shaded triangle with OpenGL.

Triangle created using C example compiled with GCC 4.1.2 and freeglut3.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

At this time there is not a publicly available OpenGL <-> Raku library, but it isn't too difficult to just call into the underlying C libraries. Here's a minimal example.

It's a little verbose since it is doing all of the setup and loading manually.

```
use NativeCall;

class Window is repr('CPointer') {}
class Monitor is repr('CPointer') {}

# GLFW

constant $lib = ('glfw', v3);

sub glfwInit(--> int32) is native($lib) {*}
sub glfwCreateWindow(int32, int32, Str, Monitor, Window --> Window) is native($lib) {*}
sub glfwTerminate() is native($lib) {*}
sub glfwMakeContextCurrent(Window) is native($lib) {*}
sub glfwSetWindowShouldClose(Window, int32) is native($lib) {*}
sub glfwWindowShouldClose(Window --> int32) is native($lib) {*}
sub glfwSwapBuffers(Window) is native($lib) {*}
sub glfwSwapInterval(int32) is native($lib) {*}
sub glfwPollEvents() is native($lib) {*}
sub glfwGetFramebufferSize(Window, int32 is rw, int32 is rw) is native($lib) {*}

# OpenGL

enum PrimitiveMode(
  GL_TRIANGLES =>	0x0004,
);

enum MatrixMode(
  GL_MATRIX_MODE => 0x0BA0,
  GL_MODELVIEW => 0x1700,
  GL_PROJECTION => 0x1701,
);

constant $gllib = 'GL';

sub glViewport(int32, int32, int32, int32) is native($gllib) {*}
sub glClear(int32) is native($gllib) {*}
sub glMatrixMode(int32) is native($gllib) {*}
sub glLoadIdentity() is native($gllib) {*}
sub glOrtho(num64, num64, num64, num64, num64, num64) is native($gllib) {*}
sub glRotatef(num32, num32, num32, num32) is native($gllib) {*}
sub glBegin(int32) is native($gllib) {*}
sub glColor3f(num32, num32, num32) is native($gllib) {*}
sub glVertex3f(num32, num32, num32) is native($gllib) {*}
sub glEnd() is native($gllib) {*}

constant GL_COLOR_BUFFER_BIT = 0x00004000;

die 'Failed to initialize GLFW' unless glfwInit().so;

my $w = glfwCreateWindow(640, 480, "OpenGL Triangle", Nil, Nil);
without $w { glfwTerminate(); die 'Failed to create window' }

glfwMakeContextCurrent($w);
glfwSwapInterval(1);

while not glfwWindowShouldClose($w) {
    my num32 $ratio;
    my int32 $width;
    my int32 $height;

    glfwGetFramebufferSize($w, $width, $height);
    $ratio = ($width / $height).Num;

    glViewport(0, 0, $width, $height);
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-$ratio, $ratio, -1e0, 1e0, 1e0, -1e0);
    glMatrixMode(GL_MODELVIEW);

    glLoadIdentity();
    glRotatef((now % 360 * 100e0) , 0e0, 0e0,  1e0);

    glBegin(GL_TRIANGLES);
    glColor3f(1e0, 0e0, 0e0);
    glVertex3f(5e-1, -2.88e-1, 0e0);
    glColor3f(0e0, 1e0, 0e0);
    glVertex3f(-5e-1, -2.88e-1, 0e0);
    glColor3f(0e0, 0e0, 1e0);
    glVertex3f( 0e0, 5.73e-1, 0e0);
    glEnd();

    glfwSwapBuffers($w);
    glfwPollEvents();
}

glfwTerminate();

```

See screen cap: OpenGL-Triangle-perl6.png (Offsite PNG image.)

Additional Output: (Offsite Media file)


[User]
Using the triangle geometry from OpenGL. But instead of using a mechanism such as glColor3d, use a pixel shader for each pixel in the triangle. The pixel shader should pick a random RGB color for each pixel. Most pixels should have colors which are different from that of most other pixels.

Optional: provide an update mechanism, to repeatedly re-render the triangle. (Possibilities include a mouse event handler, a timer event handler or an infinite loop, or even window expose events.) Shader generated color for each pixel should be different in each render.

Optional: after updating the opengl rendering target but before rendering the triangle, query the opengl implementation to determine which versions of shaders are supported by the rendering target, list the tested shaders and the available shaders and then use a supported shader.

See also: opengl.org's gl shader language documentation, and lighthouse3d.com's glsl tutorial.

[Assistant]
**Translation of**: C

```
# 20250207 Raku programming solution

use NativeCall;

my ($angle, $r_mod) = 0e0;

# OpenGL and GLUT constants
enum GLenum ( GL_TRIANGLES => 0x0004);

enum GLbitfield ( GL_COLOR_BUFFER_BIT => 0x00004000, GL_DEPTH_BUFFER_BIT => 0x00000100 );
enum GLUTdisplay_mode ( GLUT_RGB => 0x0000, GLUT_DOUBLE => 0x0002, GLUT_DEPTH => 0x0010 );
enum Shader_type ( GL_FRAGMENT_SHADER => 0x8B30, GL_VERTEX_SHADER => 0x8B31 );
enum STDLIB ( RAND_MAX => 2147483647 );

# GLUT functions
constant $lib = 'glut';
sub glutInit(CArray[uint32], CArray[Str]) is native($lib) {*}
sub glutInitDisplayMode(uint32 $mode) is native($lib) {*}
sub glutInitWindowSize(int32 $width, int32 $height) is native($lib) {*}
sub glutCreateWindow(Str $str) is native($lib) {*}
sub glutDisplayFunc(&func ()) is native($lib) {*}
sub glutIdleFunc(&func ()) is native($lib) {*}
sub glutSwapBuffers() is native($lib) {*}
sub glutMainLoop() is native($lib) {*}

# OpenGL functions
constant $gllib = 'GL';
sub glClear(int32) is native($gllib) {*}
sub glLoadIdentity() is native($gllib) {*}
sub glRotatef(num32 $angle, num32 $x, num32 $y, num32 $z) is native($gllib) {*}
sub glBegin(uint32) is native($gllib) {*}
sub glEnd() is native($gllib) {*}
sub glVertex3f(num32 $x, num32 $y, num32 $z) is native($gllib) {*}
sub glUniform1f(uint32, num32) is native($gllib) {*}

# Shader functions
sub glCreateShader(uint32) returns uint32 is native($gllib) {*}
sub glShaderSource(uint32, int32, CArray[Str], CArray[int32]) is native($gllib) {*}
sub glCompileShader(uint32) is native($gllib) {*}
sub glCreateProgram() returns uint32 is native($gllib) {*}
sub glAttachShader(uint32, uint32) is native($gllib) {*}
sub glLinkProgram(uint32) is native($gllib) {*}
sub glUseProgram(uint32) is native($gllib) {*}
sub glGetUniformLocation(uint32, Str) returns uint32 is native($gllib) {*}

# GLEW functions
constant $glewlib = 'GLEW';
sub glewInit() returns int32 is native($glewlib) {*}
sub glewIsSupported(Str) returns int32 is native($glewlib) {*}

sub render() {
   glClear(GL_COLOR_BUFFER_BIT +| GL_DEPTH_BUFFER_BIT);
   glUniform1f($r_mod, rand / RAND_MAX);
   glLoadIdentity();
   glRotatef($angle, $angle * 0.1, 1e0, 0e0);
   glBegin(GL_TRIANGLES);
      glVertex3f(-1e0, -0.5e0, 0e0);
      glVertex3f(0e0, 1e0, 0e0);
      glVertex3f(1e0, 0e0, 0e0);
   glEnd();
   $angle += 0.02;
   glutSwapBuffers();
}

sub compile_shader($shader_type, $source) {
   my $shader = glCreateShader($shader_type);
   my $length = $source.chars;
   my $source_array = CArray[Str].new($source);
   my $length_array = CArray[int32].new($length);
   glShaderSource($shader, 1, $source_array, $length_array);
   glCompileShader($shader);
   return $shader;
}

sub set_shader() {
   my $f = q:to/END/;
varying float x, y, z;
uniform float r_mod;
float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }
void main() {
   gl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);
}
END
   my $v = q:to/END/;
varying float x, y, z;
void main() {
   gl_Position = ftransform();
   x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;
   x += y; y -= x; z += x - y;
}
END

   my $vs = compile_shader(GL_VERTEX_SHADER, $v);
   my $ps = compile_shader(GL_FRAGMENT_SHADER, $f);

   given my $prog = glCreateProgram() {
      ($vs, $ps).map: -> $shader { glAttachShader($prog, $shader) };
      glLinkProgram($prog);
      glUseProgram($prog);
      $r_mod = glGetUniformLocation($prog, "r_mod");
   }
}

glutInit(CArray[uint32].new, CArray[Str].new);
glutInitDisplayMode(GLUT_DOUBLE +| GLUT_RGB +| GLUT_DEPTH);
glutInitWindowSize(600, 600);
glutCreateWindow("pixel shader");
glutDisplayFunc(&render);
glutIdleFunc(&render);
glewInit();
die "GL 2.0 unsupported\n" unless glewIsSupported("GL_VERSION_2_0");
set_shader();
glutMainLoop();

```


[User]
This is a way to render the classic Utah Teapot using OpenGL library.

See also: Utah Teapot wikipage.

[Assistant]
**Translation of**: C

```
# 20210524 Raku programming solution

use NativeCall;

my $rot = 0e0;
                            # https://www.khronos.org/opengl/wiki/OpenGL_Type
enum GLenum (
   GL_SMOOTH   => 0x1D01,   GL_LIGHT0     => 0x4000,   GL_AMBIENT   => 0x1200,
   GL_DIFFUSE  => 0x1201,   GL_FRONT      => 0x0404,   GL_SHININESS => 0x1601,
   GL_LIGHTING => 0x0B50,   GL_DEPTH_TEST => 0x0B71,
);
enum GLbitfield ( GL_COLOR_BUFFER_BIT => 0x00004000,   GL_DEPTH_BUFFER_BIT => 0x00000100, );
enum GLUTdisplay_mode ( GLUT_RGB => 0x0000, GLUT_SINGLE => 0x0000, GLUT_DEPTH  => 0x0010, );

constant $lib = 'glut';
sub glutInit(CArray[uint32], CArray[Str]) is native($lib) {*};
sub glutInitDisplayMode(uint32 $mode) is native($lib) {*};
sub glutInitWindowSize(int32 $width, int32 $height) is native($lib) {*};
sub glutCreateWindow(Str $str) is native($lib) {*};
sub glutDisplayFunc(&func ()) is native($lib) {*};
sub glutWireTeapot(num64 $size) is native($lib) {*};
sub glutIdleFunc(&func ()) is native($lib) {*};
sub glutPostRedisplay() is native($lib) {*};
sub glutMainLoop() is native($lib) {*};

constant $gllib = 'GL';
sub glClearColor(num32 $red, num32 $green, num32 $blue, num32 $alpha) is native($gllib) {*};
sub glShadeModel(int32) is native($gllib) {*};
sub glEnable(int32) is native($gllib) {*};
sub glClear(int32) is native($gllib) {*};
sub glRotatef(num32 $angle, num32 $x, num32 $y, num32 $z) is native($gllib) {*};
sub glPushMatrix() is native($gllib) {*};
sub glPopMatrix() is native($gllib) {*};
sub glFlush() is native($gllib) {*};
sub glLightfv   (int32, int32, CArray[num32]) is native($gllib) {*};
sub glMaterialfv(int32, int32, CArray[num32]) is native($gllib) {*};

sub init {
   glClearColor(.5e0,.5e0,.5e0,0e0);
   glShadeModel(GL_SMOOTH);
   glLightfv(GL_LIGHT0,GL_AMBIENT,CArray[num32].new: 1e0,1e0,1e0,0e0); # white
   glLightfv(GL_LIGHT0,GL_DIFFUSE,CArray[num32].new: 1e0,1e0,1e0,0e0); # white
   glMaterialfv(GL_FRONT,GL_SHININESS,CArray[num32].new: 70e0); # skinless so no effect ?
   glEnable(GL_LIGHTING);
   glEnable(GL_LIGHT0);
   glEnable(GL_DEPTH_TEST);
}

sub display {
   glClear(GL_COLOR_BUFFER_BIT+|GL_DEPTH_BUFFER_BIT);
   glPushMatrix();
   glRotatef(30e0,1e0,1e0,0e0);
   glRotatef($rot,0e0,1e0,1e0);
   glMaterialfv(GL_FRONT,GL_DIFFUSE, CArray[num32].new: 0e0,1e0,0e0,0e0); # green
   glutWireTeapot(.5e0);
   glPopMatrix();
   glFlush();
}

sub onIdle {
   $rot += 0.1e0;       # changed from 0.01 for faster rotation rate
   glutPostRedisplay();
}

glutInit(CArray[uint32].new,CArray[Str].new);
glutInitDisplayMode(GLUT_SINGLE+|GLUT_RGB+|GLUT_DEPTH);
glutInitWindowSize(900,700);
glutCreateWindow("The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.");
init();
glutDisplayFunc(&display);
glutIdleFunc(&onIdle);
glutMainLoop();

```

Output: (Offsite Media file)


[User]
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist

**Note:** Factory default password is '12345'. Changing it is highly recommended !

conversation goes as follows

```
← *#*1##
→ *99*0##
← *#603356072##
```

at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent

```
→ *#25280520##
← *#*1##
```

[Assistant]
(formerly Perl 6)

Raku doesn't really have good support for unsigned fixed bit integers yet so emulating them with regular Ints and bitmasks.

```
sub own-password (Int $password, Int $nonce) {
    my int $n1 = 0;
    my int $n2 = $password;
    for $nonce.comb {
        given $_ {
            when 1 {
                $n1 = $n2 +& 0xFFFFFF80 +> 7;
                $n2 +<= 25;
            }
            when 2 {
                $n1 = $n2 +& 0xFFFFFFF0 +> 4;
                $n2 +<= 28;
            }
            when 3 {
                $n1 = $n2 +& 0xFFFFFFF8 +> 3;
                $n2 +<= 29;
            }
            when 4 {
                $n1 = $n2 +< 1;
                $n2 +>= 31;
            }
            when 5 {
                $n1 = $n2 +< 5;
                $n2 +>= 27;
            }
            when 6 {
                $n1 = $n2 +< 12;
                $n2 +>= 20;
            }
            when 7 {
                $n1 = $n2 +& 0x0000FF00 +| ($n2 +& 0x000000FF +< 24) +| ($n2 +& 0x00FF0000 +> 16);
                $n2 = $n2 +& 0xFF000000 +> 8;
            }
            when 8 {
                $n1 = $n2 +& 0x0000FFFF +< 16 +| $n2 +> 24;
                $n2 = $n2 +& 0x00FF0000 +> 8;
            }
            when 9  { $n1 = +^$n2 }
            default { $n1 = $n2 }
        }
        given $_ {
            when 0 {}
            when 9 {}
            default { $n1 = ($n1 +| $n2) +& 0xFFFFFFFF }
        }
        $n2 = $n1;
    }
    $n1
}

say own-password( 12345, 603356072 );
say own-password( 12345, 410501656 );
say own-password( 12345, 630292165 );

```

Output:

```
25280520
119537670
4269684735
```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |

Task

Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.

State whether arguments are passed by value or by reference.

[Assistant]
(formerly Perl 6)
See this table for a list of the precedence levels. Raku is an operator-rich language (and users may define more operators at will), so instead of listing all the operators in the table, representative operators are listed for some of the precedence levels; see later in the same file for a more complete list of predefined operators at each precedence level.


[User]
Task

Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:

:   |  |
    | --- |
    | ---   ordering  A function specifying the ordering of strings; lexicographic by default.  column  An integer specifying which string of each row to compare; the first by default.  reverse  Reverses the ordering.   --- |

This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting **in whatever way is most natural to your language**. If the language supports both methods naturally, you are encouraged to describe both.

Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).

See also:

* Named Arguments

[Assistant]
(formerly Perl 6)
Using named parameters:

```
method sorttable(:$column = 0, :$reverse, :&ordering = &infix:<cmp>) {
    my @result = self»[$column].sort: &ordering;
    return $reverse ?? @result.reverse !! @result;
}

```

Using optional positional parameters:

```
method sorttable-pos($column = 0, $reverse?, &ordering = &infix:<cmp>) {
    my @result = self»[$column].sort: &ordering;
    return $reverse ?? @result.reverse !! @result;
}

```


[User]
When neglecting the influence of other objects, two celestial bodies orbit one another along a conic trajectory. In the orbital plane, the polar equation is thus:

r = L/(1 + e cos(angle))

**L** ,  **e**  and  **angle**  are respectively called *semi-latus rectum*, *eccentricity* and *true anomaly*. The eccentricity and the true anomaly are two of the six so-called orbital elements often used to specify an orbit and the position of a point on this orbit.

The four other parameters are the *semi-major axis*, the *longitude of the ascending node*, the *inclination* and the *argument of periapsis*. An other parameter, called the *gravitational parameter*, along with dynamical considerations described further, also allows for the determination of the speed of the orbiting object.

The semi-major axis is half the distance between perihelion and aphelion. It is often noted  **a**, and it's not too hard to see how it's related to the semi-latus-rectum:

a = L/(1 - e2)

The longitude of the ascending node, the inclination and the argument of the periapsis specify the orientation of the orbiting plane with respect to a reference plane defined with three arbitrarily chosen reference distant stars.

The gravitational parameter is the coefficent GM in Newton's gravitational force. It is sometimes noted µ and will be chosen as one here for the sake of simplicity:

µ = GM = 1

As mentioned, dynamical considerations allow for the determination of the speed. They result in the so-called vis-viva equation:

v2 = GM(2/r - 1/a)

This only gives the magnitude of the speed. The direction is easily determined since it's tangent to the conic.

Those parameters allow for the determination of both the position and the speed of the orbiting object in cartesian coordinates, those two vectors constituting the so-called orbital state vectors.

Task

Show how to perform this conversion from orbital elements to orbital state vectors in your programming language.

TODO: pick an example from a reputable source, and bring the algorithm description onto this site. (Restating those pages in concise a fashion comprehensible to the coders and readers of this site will be a good exercise.)

[Assistant]
(formerly Perl 6)
We'll use the Clifford geometric algebra library but only for the vector operations.

```
sub orbital-state-vectors(
    Real :$semimajor-axis where * >= 0,
    Real :$eccentricity   where * >= 0,
    Real :$inclination,
    Real :$longitude-of-ascending-node,
    Real :$argument-of-periapsis,
    Real :$true-anomaly
) {
    use Clifford;
    my ($i, $j, $k) = @e[^3];

    sub rotate($a is rw, $b is rw, Real \α) {
        ($a, $b) = cos(α)*$a + sin(α)*$b, -sin(α)*$a + cos(α)*$b;
    }
    rotate($i, $j, $longitude-of-ascending-node);
    rotate($j, $k, $inclination);
    rotate($i, $j, $argument-of-periapsis);

    my \l = $eccentricity == 1 ?? # PARABOLIC CASE
        2*$semimajor-axis !!
        $semimajor-axis*(1 - $eccentricity**2);

    my ($c, $s) = .cos, .sin given $true-anomaly;

    my \r = l/(1 + $eccentricity*$c);
    my \rprime = $s*r**2/l;

    my $position = r*($c*$i + $s*$j);

    my $speed =
    (rprime*$c - r*$s)*$i + (rprime*$s + r*$c)*$j;
    $speed /= sqrt($speed**2);
    $speed *= sqrt(2/r - 1/$semimajor-axis);

    { :$position, :$speed }
}

say orbital-state-vectors
    semimajor-axis => 1,
    eccentricity => 0.1,
    inclination => pi/18,
    longitude-of-ascending-node => pi/6,
    argument-of-periapsis => pi/4,
    true-anomaly => 0;

```

Output:

```
{position => 0.237771283982207*e0+0.860960261697716*e1+0.110509023572076*e2, speed => -1.06193301748006*e0+0.27585002056925*e1+0.135747024865598*e2}
```


[User]
Assume we have a set of items that can be sorted into an order by the user.

The user is presented with pairs of items from the set in *no* order,
the user states which item
is less than, equal to, or greater than the other (with respect to their
relative positions if fully ordered).

Write a function that given items that the user can order, **asks the user** to
give the result of *comparing two items at a time* and uses the comparison results
to eventually return the items in order.

Try and minimise the comparisons the user is asked for.

Show on this page, the function ordering the colours of the rainbow:

```
   violet red green indigo blue yellow orange

```

The correct ordering being:

```
   red orange yellow green blue indigo violet

```

Note:

* Asking for/receiving user comparisons is a part of the task.
* Code *inputs* should not assume an ordering.
* The seven colours can form twenty-one different pairs.
* A routine that does not ask the user "too many" comparison questions should be used.

[Assistant]
Raku's sort (like most languages) can take a custom "comparator" routine.
Since the calls to the comparator are minimized, and the info that the user provides is analogous to the required return values of the comparator, we just need to embed the prompt directly in the comparator.

```
my $ask_count = 0;
sub by_asking ( $a, $b ) {
    $ask_count++;
    constant $fmt = '%2d. Is %-6s [ less than | greater than | equal to ] %-6s? ( < = > ) ';
    constant %o = '<' => Order::Less,
                  '=' => Order::Same,
                  '>' => Order::More;

    loop {
        my $input = prompt sprintf $fmt, $ask_count, $a, $b;
        return $_ with %o{ $input.trim };
        say "Invalid input '$input'";
    }
}

my @colors = <violet red green indigo blue yellow orange>;
my @sorted = @colors.sort: &by_asking;
say (:@sorted);

die if @sorted».substr(0,1).join ne 'roygbiv';
my $expected_ask_count = @colors.elems * log(@colors.elems);
warn "Too many questions? ({:$ask_count} > {:$expected_ask_count})" if $ask_count > $expected_ask_count;

```

Output:

```
 1. Is violet [ less than | greater than | equal to ] red   ? ( < = > ) >
 2. Is green  [ less than | greater than | equal to ] indigo? ( < = > ) <
 3. Is blue   [ less than | greater than | equal to ] yellow? ( < = > ) >
 4. Is red    [ less than | greater than | equal to ] green ? ( < = > ) <
 5. Is violet [ less than | greater than | equal to ] green ? ( < = > ) >
 6. Is violet [ less than | greater than | equal to ] indigo? ( < = > ) >
 7. Is yellow [ less than | greater than | equal to ] orange? ( < = > ) >
 8. Is red    [ less than | greater than | equal to ] orange? ( < = > ) <
 9. Is green  [ less than | greater than | equal to ] orange? ( < = > ) >
10. Is green  [ less than | greater than | equal to ] yellow? ( < = > ) >
11. Is green  [ less than | greater than | equal to ] blue  ? ( < = > ) <
12. Is indigo [ less than | greater than | equal to ] blue  ? ( < = > ) >
sorted => [red orange yellow green blue indigo violet]

```


[User]
Given   `M`   as a list of items and another list   `N`   of items chosen from   `M`,   create   `M'`   as a list with the *first* occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   `M`   but in the order given by their order in   `N`.

That is, items in   `N`   are taken from   `M`   without replacement, then the corresponding positions in   `M'`   are filled by successive items from   `N`.

For example
:   if   `M`   is   `'the cat sat on the mat'`
:   And   `N`   is   `'mat cat'`
:   Then the result   `M'`   is   `'the mat sat on the cat'`.

The words not in   `N`   are left in their original positions.

If there are duplications then only the first instances in   `M`   up to as many as are mentioned in   `N`   are potentially re-ordered.

For example
:   `M = 'A B C A B C A B C'`
:   `N = 'C A C A'`

Is ordered as:

:   `M' = 'C B A C B A A B C'`

Show the output, here, for at least the following inputs:

```
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C'      Order N: 'C A C A'
Data M: 'A B C A B D A B E'      Order N: 'E A D A'
Data M: 'A B'                    Order N: 'B'
Data M: 'A B'                    Order N: 'B A'
Data M: 'A B B A'                Order N: 'B A'

```

Cf

* Sort disjoint sublist

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

```
sub order-disjoint-list-items(\M, \N) {
    my \bag = N.BagHash;
    M.map: { bag{$_}-- ?? N.shift !! $_ }
}

# Testing:

for q:to/---/.comb(/ [\S+]+ % ' ' /).map({[.words]})
    the cat sat on the mat      mat cat
    the cat sat on the mat      cat mat
    A B C A B C A B C           C A C A
    A B C A B D A B E           E A D A
    A B                         B
    A B                         B A
    A B B A                     B A
    X X Y                       X
    A X                         Y A
    ---
->  $m, $n { say "\n$m ==> $n\n", order-disjoint-list-items($m, $n) }

```

Output:

```
the cat sat on the mat ==> mat cat
the mat sat on the cat

the cat sat on the mat ==> cat mat
the cat sat on the mat

A B C A B C A B C ==> C A C A
C B A C B A A B C

A B C A B D A B E ==> E A D A
E B C A B D A B A

A B ==> B
A B

A B ==> B A
B A

A B B A ==> B A
B A B A

X X Y ==> X
X X Y

A X ==> Y A
Y X
```


[User]
Tasks in this category have to do with sorting collections of objects.

Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return `true` if the first list should be ordered before the second, and `false` otherwise.

The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is `true`.
If the second list or both run out of elements the result is `false`.

Note: further clarification of lexicographical ordering is expounded on the talk page here and here.

[Assistant]
(formerly Perl 6)
There is already a built-in comparison operator.

```
my @a = <1 2 4>;
my @b = <1 2 4>;
say @a," before ",@b," = ", @a before @b;

@a = <1 2 4>;
@b = <1 2>;
say @a," before ",@b," = ", @a before @b;

@a = <1 2>;
@b = <1 2 4>;
say @a," before ",@b," = ", @a before @b;

for 1..10 {
    my @a = flat (^100).roll((2..3).pick);
    my @b = flat @a.map: { Bool.pick ?? $_ !! (^100).roll((0..2).pick) }
    say @a," before ",@b," = ", @a before @b;
}

```

Output:

```
1 2 4 before 1 2 4 = False
1 2 4 before 1 2 = False
1 2 before 1 2 4 = True
63 52 before 0 52 = False
17 75 24 before 31 75 24 = True
43 32 before 43 32 = False
73 84 before 2 84 = False
73 92 before 40 24 46 = False
16 24 before 41 24 = True
9 12 22 before 9 12 32 67 = True
81 23 before 81 23 = False
55 53 1 before 55 62 83 = True
20 40 51 before 20 17 78 34 = False
```


[User]
In this task we want to find the ordered partitions into fixed-size blocks.

This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.

p
a
r
t
i
t
i
o
n
s
(

a
r
g

1
,

a
r
g

2
,
.
.
.
,

a
r
g

n
)
{\displaystyle {\displaystyle partitions({\mathit {arg}}\_{1},{\mathit {arg}}\_{2},...,{\mathit {arg}}\_{n})}}
 should generate all distributions of the elements in

{
1
,
.
.
.
,

Σ

i
=
1

n

a
r
g

i
}
{\displaystyle {\displaystyle \{1,...,\Sigma \_{i=1}^{n}{\mathit {arg}}\_{i}\}}}
 into

n
{\displaystyle {\displaystyle n}}
 blocks of respective size

a
r
g

1
,

a
r
g

2
,
.
.
.
,

a
r
g

n
{\displaystyle {\displaystyle {\mathit {arg}}\_{1},{\mathit {arg}}\_{2},...,{\mathit {arg}}\_{n}}}
.

Example 1:

p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle {\displaystyle partitions(2,0,2)}}
 would create:

```
{({1, 2}, {}, {3, 4}),
 ({1, 3}, {}, {2, 4}),
 ({1, 4}, {}, {2, 3}),
 ({2, 3}, {}, {1, 4}),
 ({2, 4}, {}, {1, 3}),
 ({3, 4}, {}, {1, 2})}

```

Example 2:

p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle {\displaystyle partitions(1,1,1)}}
 would create:

```
{({1}, {2}, {3}),
 ({1}, {3}, {2}),
 ({2}, {1}, {3}),
 ({2}, {3}, {1}),
 ({3}, {1}, {2}),
 ({3}, {2}, {1})}

```

Note that the number of elements in the list is

:   (

    a
    r
    g

    1
    +

    a
    r
    g

    2
    +
    .
    .
    .
    +

    a
    r
    g

    n

    a
    r
    g

    1

    )
    ⋅

    (

    a
    r
    g

    2
    +

    a
    r
    g

    3
    +
    .
    .
    .
    +

    a
    r
    g

    n

    a
    r
    g

    2

    )
    ⋅
    …
    ⋅

    (

    a
    r
    g

    n

    a
    r
    g

    n

    )
    {\displaystyle {\displaystyle {{\mathit {arg}}\_{1}+{\mathit {arg}}\_{2}+...+{\mathit {arg}}\_{n} \choose {\mathit {arg}}\_{1}}\cdot {{\mathit {arg}}\_{2}+{\mathit {arg}}\_{3}+...+{\mathit {arg}}\_{n} \choose {\mathit {arg}}\_{2}}\cdot \ldots \cdot {{\mathit {arg}}\_{n} \choose {\mathit {arg}}\_{n}}}}

(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).

Also,

p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle {\displaystyle partitions(1,1,1)}}
 creates the permutations of

{
1
,
2
,
3
}
{\displaystyle {\displaystyle \{1,2,3\}}}
 and thus there would be

3
!
=
6
{\displaystyle {\displaystyle 3!=6}}
 elements in the list.

Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of

p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle {\displaystyle partitions(2,0,2)}}
. If the programming language does not support polyvariadic functions pass a list as an argument.

**Notation**

Here are some explanatory remarks on the notation used in the task description:

{
1
,
…
,
n
}
{\displaystyle {\displaystyle \{1,\ldots ,n\}}}
 denotes the set of consecutive numbers from

1
{\displaystyle {\displaystyle 1}}
 to

n
{\displaystyle {\displaystyle n}}
, e.g.

{
1
,
2
,
3
}
{\displaystyle {\displaystyle \{1,2,3\}}}
 if

n
=
3
{\displaystyle {\displaystyle n=3}}
.

Σ
{\displaystyle {\displaystyle \Sigma }}
 is the mathematical notation for summation, e.g.

Σ

i
=
1

3
i
=
6
{\displaystyle {\displaystyle \Sigma \_{i=1}^{3}i=6}}
 (see also [1]).

a
r
g

1
,

a
r
g

2
,
.
.
.
,

a
r
g

n
{\displaystyle {\displaystyle {\mathit {arg}}\_{1},{\mathit {arg}}\_{2},...,{\mathit {arg}}\_{n}}}
 are the arguments — natural numbers — that the sought function receives.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.04.1

```
sub partition(@mask is copy) {
    my @op;
    my $last = [+] @mask or return [] xx 1;
    for @mask.kv -> $k, $v {
        next unless $v;
        temp @mask[$k] -= 1;
        for partition @mask -> @p {
            @p[$k].push: $last;
            @op.push: @p;
        }
    }
    return @op;
}

.say for reverse partition [2,0,2];

```

Output:

```
[[1, 2], (Any), [3, 4]]
[[1, 3], (Any), [2, 4]]
[[2, 3], (Any), [1, 4]]
[[1, 4], (Any), [2, 3]]
[[2, 4], (Any), [1, 3]]
[[3, 4], (Any), [1, 2]]
```


[User]
An   *ordered word*   is a word in which the letters appear in alphabetic order.

Examples include   **abbey**   and   **dirt**.

Task[edit]

Find *and display* all the ordered words in the dictionary   unixdict.txt   that have the longest word length.

(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)

The display needs to be shown on this page.

Related tasks

* |  |  |  |  |  |  |
  | --- | --- | --- | --- | --- | --- |
  | | Word plays | | | --- | --- | |  | | Ordered words  Palindrome detection  Semordnilap  Anagrams  Anagrams/Deranged anagrams | | |

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]
(formerly Perl 6)

Here we assume the dictionary is provided on standard input.

**Works with**: Rakudo version 2016.07

```
say lines.grep({ [le] .comb }).classify(*.chars).max(*.key).value

```

Output:

```
[abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty]

```


[User]
An Ormiston pair is two consecutive prime numbers which are anagrams, i.e. contain the same decimal digits but in a different order.

**(1913, 1931)** is the first such pair.

Task

* Find and show the first **30** Ormiston pairs.

* Find and show the **count** of Ormiston pairs up to one million.

Stretch

* Find and show the **count** of Ormiston pairs up to ten million.

See also

* Numbers Aplenty - Ormiston pairs * OEIS:A072274 - Ormiston prime pairs

[Assistant]
```
use Lingua::EN::Numbers;
use List::Divvy;

my @primes = lazy (^∞).hyper.grep( &is-prime ).map: { $_ => .comb.sort.join };
my @Ormistons = @primes.kv.map: { ($^value.key, @primes[$^key+1].key) if $^value.value eq @primes[$^key+1].value };

say "First thirty Ormiston pairs:";
say @Ormistons[^30].batch(3)».map( { "({.[0].fmt: "%5d"}, {.[1].fmt: "%5d"})" } ).join: "\n";
say '';
say +@Ormistons.&before( *[1] > $_ ) ~ " Ormiston pairs before " ~ .Int.&cardinal for 1e5, 1e6, 1e7;

```

Output:

```
First thirty Ormiston pairs:
( 1913,  1931) (18379, 18397) (19013, 19031)
(25013, 25031) (34613, 34631) (35617, 35671)
(35879, 35897) (36979, 36997) (37379, 37397)
(37813, 37831) (40013, 40031) (40213, 40231)
(40639, 40693) (45613, 45631) (48091, 48109)
(49279, 49297) (51613, 51631) (55313, 55331)
(56179, 56197) (56713, 56731) (58613, 58631)
(63079, 63097) (63179, 63197) (64091, 64109)
(65479, 65497) (66413, 66431) (74779, 74797)
(75913, 75931) (76213, 76231) (76579, 76597)

40 Ormiston pairs before one hundred thousand
382 Ormiston pairs before one million
3722 Ormiston pairs before ten million
```


[User]
Definition

An **Ormiston triple** is three consecutive prime numbers which are anagrams, i.e. contain the same decimal digits but in a different order.

Example

The three consecutive primes **(11117123, 11117213, 11117321)** are an Ormiston triple.

Task

* Find and show the smallest member of the first **25** Ormiston triples.

* Find and show the **count** of Ormiston triples up to one billion.

Stretch

* Find and show the **count** of Ormiston triples up to ten billion.

Reference

* OEIS:A075093 - Smallest member of Ormiston prime triple

Related task

* Ormiston pairs

[Assistant]
```
use Lingua::EN::Numbers;
use List::Divvy;

my @primes = lazy (^∞).hyper.grep( &is-prime ).map: { $_ => .comb.sort.join };
my @Ormistons = @primes.kv.map: { $^value.key if $^value.value eq @primes[$^key+1].value eq @primes[$^key+2].value};

say "First twenty-five Ormiston triples:";
say @Ormistons[^25].batch(5)».join(', ').join: "\n";
say '';
say +@Ormistons.&before( *[0] > $_ ) ~ " Ormiston triples before " ~ .Int.&cardinal for 1e8, 1e9;

```

Output:

```
First twenty-five Ormiston triples:
11117123, 12980783, 14964017, 32638213, 32964341
33539783, 35868013, 44058013, 46103237, 48015013
50324237, 52402783, 58005239, 60601237, 61395239
74699789, 76012879, 78163123, 80905879, 81966341
82324237, 82523017, 83279783, 86050781, 92514341

25 Ormiston triples before one hundred million
368 Ormiston triples before one billion
```


[User]
An overloaded operator can be used on more than one data type, or represents a different action depending on the context. For example, if your language lets you use "+" for adding numbers and concatenating strings, then one would say that the "+" operator is overloaded.

Task

Demonstrate overloaded operators in your language, by showing the different types of data they can or cannot operate on, and the results of each operation.

[Assistant]
While it is very easy to overload operators in Raku, it isn't really common...
at least, not in the traditional sense. Or it's extremely common... It depends on how you view it.

First off, do not confuse "symbol reuse" with operator overloading. Multiplication \* and exponentiation \*\* operators both use an asterisk, but one is not an overload of the other. A single asterisk is not the same as two. In fact the term \* (whatever) also exists, but differs from both. The parser is smart enough to know when a term or an operator is expected and will select the correct one (or warn if they are not in the correct position).

For example:

```
1, 2, 1, * ** * * * … *

```

is a perfectly cromulent sequence definition in Raku. A little odd perhaps, but completely sensible. (It's the sequence starting with givens 1,2,1, with each term after the value of the term 3 terms back, raised to the power of the term two terms back, multiplied by the value one term back, continuing for some undefined number of terms. - Whatever to the whatever times whatever until whatever.)

One of the founding principles of Raku is that: "Different things should look different". It follows that "Similar things should look similar".

To pick out one tiny example: Adding numbery things together shouldn't be easily confusable with concatenating
strings. Instead, Raku has the "concatenation" operator: ~ for joining stringy
things together.

Using a numeric-ish operator implies that you want a numeric-ish answer... so Raku
will try very hard to give you what you ask for, no matter what operands you
pass it.

Raku operators have multiple candidates to try to fulfil your request and will
try to coerce the operands to a sensible value.

Addition:

```
say  3    +  5;      # Int plus Int
say  3.0  +  0.5e1;  # Rat plus Num
say '3'   +  5;      # Str plus Int
say  3    + '5';     # Int plus Str
say '3'   + '5';     # Str plus Str
say '3.0' + '0.5e1'; # Str plus Str
say (2, 3, 4) + [5, 6]; # List plus Array

```

+ is a numeric operator so every thing is evaluated numerically if possible

Output:

```
8
8
8
8
8
8
5 # a list or array evaluated numerically returns the number of elements
```

Concatenation:

```
say  3    ~  5;      # Int concatenate Int
say  3.0  ~  0.5e1;  # Rat concatenate Num
say '3'   ~  5;      # Str concatenate Int
say  3    ~ '5';     # Int concatenate Str
say '3'   ~ '5';     # Str concatenate Str
say '3.0' ~ '0.5e1'; # Str concatenate Str
say (2, 3, 4) ~ [5, 6]; # List concatenate Array

```

~ is a Stringy operator so everything is evaluated as a string (numerics are evaluated numerically then coerced to a string).

Output:

```
35
35
35
35
35
3.00.5e1
2 3 45 6 # default stringification, then concatenate
```

There is nothing preventing you from overloading or overriding existing
operators. Raku firmly believes in not putting pointless restrictions on
what you can and can not do. Why make it hard to do the "wrong" thing when
we make it so easy to do it right?

There is no real impetus to "overload" existing operators to do *different*
things, it is **very** easy to add new operators in Raku, and nearly **any**
Unicode character or combination may used to define it. They may be infix,
prefix, postfix, (or post-circumfix!) The precedence, associativity and arity
are all easily defined. An operator at heart is just a subroutine with funny calling conventions.

Borrowed from the Nimber arithmetic task:

New operators, defined in place. Arity is two (almost all infix operators
take two arguments), precedence is set equivalent to similar existing operators,
default (right) associativity. The second, ⊗, actually uses itself to define
itself.

```
sub infix:<⊕> (Int $x, Int $y) is equiv(&infix:<+>) { $x +^ $y }

sub infix:<⊗> (Int $x, Int $y) is equiv(&infix:<×>) {
    return $x × $y if so $x|$y < 2;
    my $h = exp $x.lsb, 2;
    return $h ⊗ $y ⊕ (($x ⊕ $h) ⊗ $y) if $x > $h;
    return $y ⊗ $x if $y.lsb < $y.msb;
    return $x × $y unless my $comp = $x.lsb +& $y.lsb;
    $h = exp $comp.lsb, 2;
    (($x +> $h) ⊗ ($y +> $h)) ⊗ (3 +< ($h - 1))
}

say 123 ⊗ 456;

```

Output:

```
31562
```

Base Raku has 27 different operator precedence levels for built-ins. You could theoretically give a new operator an absolute numeric precedence but it would be difficult to predict exactly what the relative precedence would be. Instead, precedence is set by setting a relative precedence; either equivalent to an existing operator, or, by setting it tighter(higher) or looser(lower) precedence than an existing operator. When tighter or looser precedence is specified, a whole new precedence level is created squeezed in between the named level and its immediate successor (predecessor). The task Exponentiation with infix operators in (or operating on) the base demonstrates three different operators that nominally do the same thing, but may yield different results due to differing precedence levels.

That's all well and good, but suppose you have a new class, say, a Line class, and
you want to be able to do arithmetic on Lines. No need to override the built
in arithmetic operators, just add a multi candidate to do the right thing. A multi
allows *adding* a new definition of the operator without disturbing the existing ones.

Very, **very** basic Line class:

```
class Line {
    has @.start;
    has @.end;
}

# New infix + multi to add two Lines together, for some bogus definition of add
multi infix:<+> (Line $x, Line $y) {
    Line.new(
       :start(
          sqrt($x.start[0]² + $y.start[0]²),
          sqrt($x.start[1]² + $y.start[1]²)
       ),
       :end(
          sqrt($x.end[0]² + $y.end[0]²),
          sqrt($x.end[1]² + $y.end[1]²)
       )
    )
}

# In operation:
say Line.new(:start(-4,7), :end(5,0)) + Line.new(:start(1,1), :end(2,3));

```

Output:

```
Line.new(start => [4.123105625617661e0, 7.0710678118654755e0], end => [5.385164807134504e0, 3e0])
```

To be fair, all of this easy power in a bad programmers hands can lead to incomprehensible code... but bad programmers can be bad in any language.


[User]
Description

For the purposes of this task, an ***own digits power sum*** is a decimal integer which is **N** digits long and is equal to the sum of its individual digits raised to the power **N**.

Example

The three digit integer **153** is an *own digits power sum* because 1³ + 5³ + 3³ = 1 + 125 + 27 = **153**.

Task

Find and show here all *own digits power sums* for **N** = **3** to **N** = **8** inclusive.

Optionally, do the same for **N** = **9** which may take a while for interpreted languages.

Related

* Narcissistic\_decimal\_number

[Assistant]
```
(3..8).map: -> $p {
    my %pow = (^10).map: { $_ => $_ ** $p };
    my $start = 10 ** ($p - 1);
    my $end   = 10 ** $p;
    my @temp;
    for ^9 -> $i {
        ([X] ($i..9) xx $p).race.map: {
            next unless [<=] $_;
            my $sum = %pow{$_}.sum;
            next if $sum < $start;
            next if $sum > $end;
            @temp.push: $sum if $sum.comb.Bag eqv $_».Str.Bag
        }
    }
    .say for unique sort @temp;
}

```

Output:

```
153
370
371
407
1634
8208
9474
54748
92727
93084
548834
1741725
4210818
9800817
9926315
24678050
24678051
88593477
```

### Combinations with repetitions

Using code from Combinations with repetitions task, a version that runs relatively quickly, and scales well.

```
proto combs_with_rep (UInt, @ ) { * }
multi combs_with_rep (0,    @ ) { () }
multi combs_with_rep ($,    []) { () }
multi combs_with_rep (1,    @a) { map { $_, }, @a }
multi combs_with_rep ($n, [$head, *@tail]) {
    |combs_with_rep($n - 1, ($head, |@tail)).map({ $head, |@_ }),
    |combs_with_rep($n, @tail);
}

say sort gather {
    for 3..9 -> $d {
        for combs_with_rep($d, [^10]) -> @digits {
            .take if $d == .comb.elems and @digits.join == .comb.sort.join given sum @digits X** $d;
        }
    }
}

```

Output:

```
153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315 24678050 24678051 88593477 146511208 472335975 534494836 912985153
```


[User]
Conversion and addition of p-adic Numbers.

Task.

Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.

p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has *smaller* 2-adic norm than 1/4 (0.01).

If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.

**Recipe:** at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder \* 1/b (mod p).
The d's are the successive p-adic digits to find.

Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.

Related task.

p-Adic square roots

Reference.

[1] p-Adic expansions

[Assistant]
```
# 20210225 Raku programming solution

#!/usr/bin/env raku

class Padic { has ($.p is default(2), %.v is default({})) is rw ;

   method r2pa (Rat $x is copy, \p, \d) { # Reference: math.stackexchange.com/a/1187037
      self.p = p ;
      $x += p**d if $x < 0 ;  # complement

      my $lowerest = 0;
      my ($num,$den) = $x.nude;
      while ($den % p) == 0 { $den /= p and $lowerest-- }
      $x = $num / $den;

      while +self.v < d {
         my %d = ^p Z=> (( $x «-« ^p ) »/» p )».&{ .denominator % p }; # .kv
         for %d.keys { self.v.{$lowerest++} = $_ and last if %d{$_} != 0 }
         $x = ($x - self.v.{$lowerest-1}) / p ;
      }
      self
   }

   method add (Padic \x, \d) {
      my $div = 0;
      my $lowerest = (self.v.keys.sort({.Int}).first,
                         x.v.keys.sort({.Int}).first  ).min ;
      return Padic.new:
         p => self.p,
         v => gather for ^d {
            my $power = $lowerest + $_;
            given ((self.v.{$power}//0)+(x.v.{$power}//0)+$div).polymod(x.p)
               { take ($power, .[0]).Slip and $div = .[1] }
         }
   }

   method gist {
      # en.wikipedia.org/wiki/P-adic_number#Notation
      # my %H = (0..9) Z=> ('₀'..'₉'); # (0x2080 .. 0x2089);
      # '⋯ ' ~ self.v ~ ' ' ~ [~] self.p.comb».&{ %H{$_} }

      # express as a series
      my %H = ( 0…9 ,'-') Z=> ( '⁰','¹','²','³','⁴'…'⁹','⁻');
      [~] self.v.keys.sort({.Int}).map: {
         ' + ' ~ self.v.{$_} ~ '*' ~ self.p ~ [~] $_.comb».&{ %H{$_}} }
      }
}

my @T;
for my \D = (
#`[[ these are not working
   < 26/25 -109/125 5 4 >,
   < 6/7 -5/7 10 7 >,
   < 2/7 -3/7 10 7 >,
   < 2/7 -1/7 10 7 >,
   < 34/21 -39034/791 10 9 >,
#]]
#`[[[[[ Works
   < 11/4 679001/207 2 43>,
   < 11/4 679001/207 3 27 >,
   < 5/19 -101/384 2 12>,
   < -22/7 46071/379 7 13 >,
   < -7/5 99/70 7 4> ,
   < -101/109 583376/6649 61 7>,
   < 122/407 -517/1477 7 11>,

   < 2/1 1/1 2 4>,
   < 4/1 3/1 2 4>,
   < 4/1 3/1 2 5>,
   < 4/9 8/9 5 4>,
   < 11/4 679001/207 11 13 >,
   < 1/4 9263/2837 7 11 >,
   < 49/2 -4851/2 7 6 >,
   < -9/5 27/7 3 8>,
   < -22/7 46071/379 2 37 >,
   < -22/7 46071/379 3 23 >,

   < -101/109 583376/6649 2 40>,
   < -101/109 583376/6649 32749 3>,
   < -25/26 5571/137 7 13>,
#]]]]]

   < 5/8 353/30809 7 11 >,
) -> \D {
   given @T[0] = Padic.new { say D[0]~' = ', .r2pa: D[0],D[2],D[3] }
   given @T[1] = Padic.new { say D[1]~' = ', .r2pa: D[1],D[2],D[3] }
   given @T[0].add: @T[1], D[3] {
      given @T[2] = Padic.new { .r2pa: D[0]+D[1], D[2], D[3] }
      say "Addition result = ", $_.gist; #
      unless ( $_.v.Str eq @T[2].v.Str ) {
         say 'but ' ~ (D[0]+D[1]).nude.join('/') ~ ' = ' ~ @T[2].gist
      }
   }
}

```

Output:

```
5/8 =  + 5*7⁰ + 2*7¹ + 4*7² + 2*7³ + 4*7⁴ + 2*7⁵ + 4*7⁶ + 2*7⁷ + 4*7⁸ + 2*7⁹ + 4*7¹⁰
353/30809 =  + 5*7⁰ + 5*7¹ + 4*7² + 3*7³ + 4*7⁴ + 6*7⁵ + 3*7⁶ + 6*7⁷ + 6*7⁸ + 3*7⁹ + 2*7¹⁰
Addition result =  + 3*7⁰ + 1*7¹ + 2*7² + 6*7³ + 1*7⁴ + 2*7⁵ + 1*7⁶ + 2*7⁷ + 4*7⁸ + 6*7⁹ + 6*7¹⁰

```


[User]
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.

This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].

The adjusted p-values are sometimes called "q-values".

Task

Given one list of p-values, return the p-values correcting for multiple comparisons

```
   p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
        8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
        4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
        8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
        3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
        1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
        4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
        3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
        1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
        2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}

```

There are several methods to do this, see:

* Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", *Journal of the Royal Statistical Society. Series B*, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101
* Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", *Ann. Statist.*, Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075
* Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", *Scandinavian Journal of Statistics*, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733
* Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", *Biometrika*, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325
* Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", *Biometrika*, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190

Each method has its own advantages and disadvantages.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03.1

```
########################### Helper subs ###########################

sub adjusted (@p, $type) { "\n$type\n" ~ format adjust( check(@p), $type ) }

sub format ( @p, $cols = 5 ) {
    my $i = -$cols;
    my $fmt = "%1.10f";
    join "\n", @p.rotor($cols, :partial).map:
      { sprintf "[%2d]  { join ' ', $fmt xx $_ }", $i+=$cols, $_ };
}

sub check ( @p ) { die 'p-values must be in range 0.0 to 1.0' if @p.min < 0 or 1 < @p.max; @p }

multi ratchet ( 'up', @p ) { my $m; @p[$_] min= $m, $m = @p[$_] for ^@p; @p }

multi ratchet ( 'dn', @p ) { my $m; @p[$_] max= $m, $m = @p[$_] for ^@p .reverse; @p }

sub schwartzian ( @p, &transform, :$ratchet ) {
    my @pa = @p.map( {[$_, $++]} ).sort( -*.[0] ).map: { [transform(.[0]), .[1]] };
    @pa[*;0] = ratchet($ratchet, @pa»[0]);
    @pa.sort( *.[1] )»[0]
}

############# The various p-value correction routines #############

multi adjust( @p, 'Benjamini-Hochberg' ) {
    @p.&schwartzian: * * @p / (@p - $++) min 1, :ratchet('up')
}

multi adjust( @p, 'Benjamini-Yekutieli' ) {
    my \r = ^@p .map( { 1 / ++$ } ).sum;
    @p.&schwartzian: * * r * @p / (@p - $++) min 1, :ratchet('up')
}

multi adjust( @p, 'Hochberg' ) {
    my \m = @p.max;
    @p.&schwartzian: * * ++$ min m, :ratchet('up')
}

multi adjust( @p, 'Holm' ) {
    @p.&schwartzian: * * ++$ min 1, :ratchet('dn')
}

multi adjust( @p, 'Šidák' ) {
    @p.&schwartzian: 1 - (1 - *) ** ++$, :ratchet('dn')
}

multi adjust( @p, 'Bonferroni' ) {
    @p.map: * * @p min 1
}

# Hommel correction can't be easily reduced to a one pass transform
multi adjust( @p, 'Hommel' ) {
    my @s  = @p.map( {[$_, $++]} ).sort: *.[0] ; # sorted
    my \z  = +@p; # array si(z)e
    my @pa = @s»[0].map( * * z / ++$ ).min xx z; # p adjusted
    my @q;        # scratch array
    for (1 ..^ z).reverse -> $i {
        my @L  = 0 .. z - $i; # lower indices
        my @U  = z - $i ^..^ z; # upper indices
        my $q  = @s[@U]»[0].map( { $_ * $i / (2 + $++) } ).min;
        @q[@L] = @s[@L]»[0].map: { min $_ * $i, $q, @s[*-1][0] };
        @pa    = ^z .map: { max @pa[$_], @q[$_] }
    }
    @pa[@s[*;1].map( {[$_, $++]} ).sort( *.[0] )»[1]]
}

multi adjust ( @p, $unknown ) {
    note "\nSorry, do not know how to do $unknown correction.\n" ~
    "Perhaps you want one of these?:\n" ~
    <Benjamini-Hochberg Benjamini-Yekutieli Bonferroni Hochberg
    Holm Hommel Šidák>.join("\n");
    exit
}

########################### The task ###########################

my @p-values =
    4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
    8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
    4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
    8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
    3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
    1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
    4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
    3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
    1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
    2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03
;

for < Benjamini-Hochberg Benjamini-Yekutieli Bonferroni Hochberg Holm Hommel Šidák >
{
    say adjusted @p-values, $_
}

```

Output:

```
Benjamini-Hochberg
[ 0]  0.6126681081 0.8521710465 0.1987205200 0.1891595417 0.3217789286
[ 5]  0.9301450000 0.4870370000 0.9301450000 0.6049730556 0.6826752564
[10]  0.6482628947 0.7253722500 0.5280972727 0.8769925556 0.4705703448
[15]  0.9241867391 0.6049730556 0.7856107317 0.4887525806 0.1136717045
[20]  0.4991890625 0.8769925556 0.9991834000 0.3217789286 0.9301450000
[25]  0.2304957692 0.5832475000 0.0389954722 0.8521710465 0.1476842609
[30]  0.0168363750 0.0025629017 0.0351608438 0.0625018947 0.0036365888
[35]  0.0025629017 0.0294688286 0.0061660636 0.0389954722 0.0026889914
[40]  0.0004502863 0.0000125223 0.0788155476 0.0314261300 0.0048465270
[45]  0.0025629017 0.0048465270 0.0011017083 0.0725203250 0.0220595769

Benjamini-Yekutieli
[ 0]  1.0000000000 1.0000000000 0.8940844244 0.8510676197 1.0000000000
[ 5]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[10]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[15]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 0.5114323399
[20]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[25]  1.0000000000 1.0000000000 0.1754486368 1.0000000000 0.6644618149
[30]  0.0757503083 0.0115310209 0.1581958559 0.2812088585 0.0163617595
[35]  0.0115310209 0.1325863108 0.0277423864 0.1754486368 0.0120983246
[40]  0.0020259303 0.0000563403 0.3546073326 0.1413926119 0.0218055202
[45]  0.0115310209 0.0218055202 0.0049568120 0.3262838334 0.0992505663

Bonferroni
[ 0]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[ 5]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[10]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[15]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[20]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[25]  1.0000000000 1.0000000000 0.7019185000 1.0000000000 1.0000000000
[30]  0.2020365000 0.0151667450 0.5625735000 1.0000000000 0.0290927100
[35]  0.0153774100 0.4125636000 0.0678267000 0.6803480000 0.0188229400
[40]  0.0009005725 0.0000125223 1.0000000000 0.4713919500 0.0439557650
[45]  0.0108891550 0.0484652700 0.0033051250 1.0000000000 0.2867745000

Hochberg
[ 0]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9991834000
[ 5]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9991834000
[10]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9991834000
[15]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9991834000
[20]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9991834000
[25]  0.9991834000 0.9991834000 0.4632662100 0.9991834000 0.9991834000
[30]  0.1575884700 0.0138396690 0.3938014500 0.7600230400 0.0250197306
[35]  0.0138396690 0.3052970640 0.0542613600 0.4626366400 0.0165641872
[40]  0.0008825611 0.0000125223 0.9930759000 0.3394022040 0.0369228426
[45]  0.0102358057 0.0397415214 0.0031729200 0.8992520300 0.2179486200

Holm
[ 0]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[ 5]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[10]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[15]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[20]  1.0000000000 1.0000000000 1.0000000000 1.0000000000 1.0000000000
[25]  1.0000000000 1.0000000000 0.4632662100 1.0000000000 1.0000000000
[30]  0.1575884700 0.0139534054 0.3938014500 0.7600230400 0.0250197306
[35]  0.0139534054 0.3052970640 0.0542613600 0.4626366400 0.0165641872
[40]  0.0008825611 0.0000125223 0.9930759000 0.3394022040 0.0369228426
[45]  0.0102358057 0.0397415214 0.0031729200 0.8992520300 0.2179486200

Hommel
[ 0]  0.9991834000 0.9991834000 0.9991834000 0.9987623800 0.9991834000
[ 5]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9991834000
[10]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9991834000
[15]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9595180000
[20]  0.9991834000 0.9991834000 0.9991834000 0.9991834000 0.9991834000
[25]  0.9991834000 0.9991834000 0.4351894700 0.9991834000 0.9766522500
[30]  0.1414255500 0.0130434007 0.3530936533 0.6887708800 0.0238560222
[35]  0.0132245726 0.2722919760 0.0542613600 0.4218157600 0.0158112696
[40]  0.0008825611 0.0000125223 0.8743649143 0.3016908480 0.0351646120
[45]  0.0095824564 0.0387722160 0.0031729200 0.8122276400 0.1950066600

Šidák
[ 0]  0.9998642526 0.9999922727 0.9341844137 0.9234670175 0.9899922294
[ 5]  0.9999922727 0.9992955735 0.9999922727 0.9998642526 0.9998909746
[10]  0.9998642526 0.9999288207 0.9995533892 0.9999922727 0.9990991210
[15]  0.9999922727 0.9998642526 0.9999674876 0.9992955735 0.7741716825
[20]  0.9993332472 0.9999922727 0.9999922727 0.9899922294 0.9999922727
[25]  0.9589019598 0.9998137104 0.3728369461 0.9999922727 0.8605248833
[30]  0.1460714182 0.0138585952 0.3270159382 0.5366136349 0.0247164330
[35]  0.0138585952 0.2640282766 0.0528503728 0.3723753774 0.0164308228
[40]  0.0008821796 0.0000125222 0.6357389664 0.2889497995 0.0362651575
[45]  0.0101847015 0.0389807074 0.0031679962 0.5985019850 0.1963376344
```


[User]
As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.

The Fibonacci-like sequences can be defined like this:

```
   For n == 2:
       start:      1, 1
       Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
   For n == N:
       start:      First N terms of R(N-1, x)
       Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))

```

For this task we similarly define terms of the first 2..n-step Padovan sequences as:

```
   For n == 2:
       start:      1, 1, 1
       Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
   For n == N:
       start:      First N + 1 terms of R(N-1, x)
       Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))

```

The initial values of the sequences are:

:   :   Padovan

        n
        {\displaystyle {\displaystyle n}}
        -step sequences

        | n {\displaystyle {\displaystyle n}} | Values | OEIS Entry |
        | --- | --- | --- |
        | 2 | 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... | A134816: 'Padovan's spiral numbers' |
        | 3 | 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... | A000930: 'Narayana's cows sequence' |
        | 4 | 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... | A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter' |
        | 5 | 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... | A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's' |
        | 6 | 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... | <not found> |
        | 7 | 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... | A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)' |
        | 8 | 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ... | <not found> |

Task

1. Write a function to generate the first

   t
   {\displaystyle {\displaystyle t}}
    terms, of the first `2..max_n` Padovan

   n
   {\displaystyle {\displaystyle n}}
   -step number sequences as defined above.
2. Use this to print and show here at least the first `t=15` values of the first `2..8`

   n
   {\displaystyle {\displaystyle n}}
   -step sequences.
    (The OEIS column in the table above should be omitted).

[Assistant]
```
say 'Padovan N-step sequences; first 25 terms:';

for 2..8 -> \N {
    my @n-step = 1, 1, 1, { state $n = 2; @n-step[ ($n - N .. $n++ - 1).grep: * >= 0 ].sum } … *;
    put "N = {N} |" ~ @n-step[^25]».fmt: "%5d";
}

```

Output:

```
Padovan N-step sequences; first 25 terms:
N = 2 |    1     1     1     2     2     3     4     5     7     9    12    16    21    28    37    49    65    86   114   151   200   265   351   465   616
N = 3 |    1     1     1     2     3     4     6     9    13    19    28    41    60    88   129   189   277   406   595   872  1278  1873  2745  4023  5896
N = 4 |    1     1     1     2     3     5     7    11    17    26    40    61    94   144   221   339   520   798  1224  1878  2881  4420  6781 10403 15960
N = 5 |    1     1     1     2     3     5     8    12    19    30    47    74   116   182   286   449   705  1107  1738  2729  4285  6728 10564 16587 26044
N = 6 |    1     1     1     2     3     5     8    13    20    32    51    81   129   205   326   518   824  1310  2083  3312  5266  8373 13313 21168 33657
N = 7 |    1     1     1     2     3     5     8    13    21    33    53    85   136   218   349   559   895  1433  2295  3675  5885  9424 15091 24166 38698
N = 8 |    1     1     1     2     3     5     8    13    21    34    54    87   140   225   362   582   936  1505  2420  3891  6257 10061 16178 26014 41830
```


[User]
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.

:   :   | Comment | Padovan | Fibonacci |
        | --- | --- | --- |
        |  |  |  |
        | Named after. | Richard Padovan | Leonardo of Pisa: Fibonacci |
        |  |  |  |
        | Recurrence initial values. | P(0)=P(1)=P(2)=1 | F(0)=0, F(1)=1 |
        | Recurrence relation. | P(n)=P(n-2)+P(n-3) | F(n)=F(n-1)+F(n-2) |
        |  |  |  |
        | First 10 terms. | 1,1,1,2,2,3,4,5,7,9 | 0,1,1,2,3,5,8,13,21,34 |
        |  |  |  |
        | Ratio of successive terms... | Plastic ratio, p | Golden ratio, g |
        |  | 1.324717957244746025960908854… | 1.6180339887498948482... |
        | Exact formula of ratios p and q. | ((9+69\*\*.5)/18)\*\*(1/3) + ((9-69\*\*.5)/18)\*\*(1/3) | (1+5\*\*0.5)/2 |
        | Ratio is real root of polynomial. | p: x\*\*3-x-1 | g: x\*\*2-x-1 |
        |  |  |  |
        | Spirally tiling the plane using. | Equilateral triangles | Squares |
        |  |  |  |
        | Constants for ... | s= 1.0453567932525329623 | a=5\*\*0.5 |
        | ... Computing by truncation. | P(n)=floor(p\*\*(n-1) / s + .5) | F(n)=floor(g\*\*n / a + .5) |
        |  |  |  |
        | L-System Variables. | A,B,C | A,B |
        | L-System Start/Axiom. | A | A |
        | L-System Rules. | A->B,B->C,C->AB | A->B,B->AB |

Task

* Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
* Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
* Show the first twenty terms of the sequence.
* Confirm that the recurrence and floor based functions give the same results for 64 terms,
* Write a function/method/... using the L-system to generate successive strings.
* Show the first 10 strings produced from the L-system
* Confirm that the length of the first 32 strings produced is the Padovan sequence.

Show output here, on this page.

Ref

* The Plastic Ratio - Numberphile video.

[Assistant]
```
constant p = 1.32471795724474602596;
constant s = 1.0453567932525329623;
constant %rules = A => 'B', B => 'C', C => 'AB';

my @pad-recur = 1, 1, 1, -> $c, $b, $ { $b + $c }  … *;

my @pad-floor = { floor 1/2 + p ** ($++ - 1) / s } … *;

my @pad-L-sys = 'A', { %rules{$^axiom.comb}.join } … *;
my @pad-L-len = @pad-L-sys.map: *.chars;

say @pad-recur.head(20);
say @pad-L-sys.head(10);

say "Recurrence == Floor to N=64" if (@pad-recur Z== @pad-floor).head(64).all;
say "Recurrence == L-len to N=32" if (@pad-recur Z== @pad-L-len).head(32).all;

```

Output:

```
(1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151)
(A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB)
Recurrence == Floor to N=64
Recurrence == L-len to N=32

```


[User]
Generate the sequence where each term **n** is the count of the pairs **(x,y)** with **1 < x < y <= n**, that have at least one common prime factor.

For instance, when **n** = 9, examine the pairs:

```
   (2,3) (2,4) (2,5) (2,6) (2,7) (2,8) (2,9)
   (3,4) (3,5) (3,6) (3,7) (3,8) (3,9)
   (4,5) (4,6) (4,7) (4,8) (4,9)
   (5,6) (5,7) (5,8) (5,9)
   (6,7) (6,8) (6,9)
   (7,8) (7,9)
   (8,9)

```

Find all of the pairs that have at least one common prime factor:

```
   (2,4) (2,6) (2,8) (3,6) (3,9) (4,6) (4,8) (6,8) (6,9)

```

and count them:

```
   a(9) = 9

```

Terms may be found directly using the formula:

```
   a(n) = n × (n-1) / 2 + 1 - 𝚺{i=1..n} 𝚽(i)

```

where 𝚽() is Phi; the Euler totient function.

For the term **a(p)**, if **p** is prime, then **a(p)** is equal to the previous term.

Task

* Find and display the first one hundred terms of the sequence.
* Find and display the one thousandth.

Stretch

* Find and display the ten thousandth, one hundred thousandth, one millionth.

See also

* OEIS:A185670 - Number of pairs (x,y) with 1 <= x < y <= n with at least one common factor * Task: Totient function

[Assistant]
```
use Prime::Factor;
use Lingua::EN::Numbers;

my \𝜑 = 0, |(1..*).hyper.map: -> \t { t × [×] t.&prime-factors.unique.map: { 1 - 1/$_ } }

sub pair-count (\n) {  n × (n - 1) / 2 + 1 - sum 𝜑[1..n] }

say "Number of pairs with common factors - first one hundred terms:\n"
    ~ (1..100).map(&pair-count).batch(10)».&comma».fmt("%6s").join("\n") ~ "\n";

for ^7 { say (my $i = 10 ** $_).&ordinal.tc.fmt("%22s term: ") ~ $i.&pair-count.&comma }

```

Output:

```
Number of pairs with common factors - first one hundred terms:
     0      0      0      1      1      4      4      7      9     14
    14     21     21     28     34     41     41     52     52     63
    71     82     82     97    101    114    122    137    137    158
   158    173    185    202    212    235    235    254    268    291
   291    320    320    343    363    386    386    417    423    452
   470    497    497    532    546    577    597    626    626    669
   669    700    726    757    773    818    818    853    877    922
   922    969    969  1,006  1,040  1,079  1,095  1,148  1,148  1,195
 1,221  1,262  1,262  1,321  1,341  1,384  1,414  1,461  1,461  1,526
 1,544  1,591  1,623  1,670  1,692  1,755  1,755  1,810  1,848  1,907

                 First term: 0
                 Tenth term: 14
         One hundredth term: 1,907
        One thousandth term: 195,309
        Ten thousandth term: 19,597,515
One hundred thousandth term: 1,960,299,247
         One millionth term: 196,035,947,609
```


[User]
Today   (**2020-02-02**,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   **yyyy-mm-dd**   format but,   unusually,   also for countries which use the   **dd-mm-yyyy**   format.

Task

Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the   **yyyy-mm-dd**   format.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.01

Pretty basic, but good enough. Could start earlier but 3/2/1 digit years require different handling that isn't necessary for this task. (And would be pretty pointless anyway assuming we need 2 digits for the month and two digits for the day. ISO:8601 anybody?)

```
my $start = '1000-01-01';

my @palindate = {
     state $year = $start.substr(0,4);
     ++$year;
     my $m = $year.substr(2, 2).flip;
     my $d = $year.substr(0, 2).flip;
     next if not try Date.new("$year-$m-$d");
     "$year-$m-$d"
} … *;

my $date-today = Date.today; # 2020-02-02

my $k = @palindate.first: { Date.new($_) > $date-today }, :k;

say join "\n", @palindate[$k - 1 .. $k + 14];

say "\nTotal number of four digit year palindrome dates:\n" ~
my $four = @palindate.first( { .substr(5,1) eq '-' }, :k );
say "between {@palindate[0]} and {@palindate[$four - 1]}.";

my $five = @palindate.first: { .substr(6,1) eq '-' }, :k;

say "\nTotal number of five digit year palindrome dates:\n" ~
+@palindate[$four .. $five]

```

Output:

```
2020-02-02
2021-12-02
2030-03-02
2040-04-02
2050-05-02
2060-06-02
2070-07-02
2080-08-02
2090-09-02
2101-10-12
2110-01-12
2111-11-12
2120-02-12
2121-12-12
2130-03-12
2140-04-12

Total number of four digit year palindrome dates:
331
between 1001-10-01 and 9290-09-29.

Total number of five digit year palindrome dates:
3303
```


[User]
A palindrome is a phrase which reads the same backward and forward.

Task[edit]

Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.

***For extra credit:***

* Support Unicode characters.
* Write a second function (possibly as a wrapper to the first) which detects *inexact* palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.

Hints

* It might be useful for this task to know how to reverse a string.
* This task's entries might also form the subjects of the task Test a function.

Related tasks

* |  |  |  |  |  |  |
  | --- | --- | --- | --- | --- | --- |
  | | Word plays | | | --- | --- | |  | | Ordered words  Palindrome detection  Semordnilap  Anagrams  Anagrams/Deranged anagrams | | |

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]
(formerly Perl 6)

```
subset Palindrom of Str where {
    .flip eq $_ given .comb(/\w+/).join.lc
}

my @tests = q:to/END/.lines;
    A man, a plan, a canal: Panama.
    My dog has fleas
    Madam, I'm Adam.
    1 on 1
    In girum imus nocte et consumimur igni
    END

for @tests { say $_ ~~ Palindrom, "\t", $_ }
```

Output:

```
True	A man, a plan, a canal: Panama.
False	My dog has fleas
True	Madam, I'm Adam.
False	1 on 1
True	In girum imus nocte et consumimur igni

```


[User]
For this task, a *number* is to be understood as a positive integer expressed in base ten,
and a *palindromic* number is one that is equal to the integer formed by reversing its decimal digits.

A number that is evenly divisible by the number formed by concatenating its
first and last digits in that order is known as a **gapful number**.
All one─ and two─digit numbers have this property and accordingly only
numbers greater than or equal to **100** should be considered for this Rosetta Code task.

(*Evenly divisible* here means divisible with no remainder.)

Example

**1037**   is a   **gapful**   number because it is evenly divisible by the
number   **17**   which is formed by the first and last decimal digits
of    **1037**.

Task
:   * Show   (nine sets)   the first   **20**   palindromic gapful numbers that   *end*   with:

    :   :   * the digit   **1**
            * the digit   **2**
            * the digit   **3**
            * the digit   **4**
            * the digit   **5**
            * the digit   **6**
            * the digit   **7**
            * the digit   **8**
            * the digit   **9**

    * Show   (nine sets, like above)   of palindromic gapful numbers:

    :   :   * the last   **15**   palindromic gapful numbers   (out of      **100**)
            * the last   **10**   palindromic gapful numbers   (out of   **1,000**)       {optional}

For other ways of expressing the (above) requirements, see the   *discussion*   page.

Note

All palindromic gapful numbers are divisible by eleven.

Related tasks
:   * palindrome detection.
    * gapful numbers.

Also see
:   * The OEIS entry:   A108343 gapful numbers.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

```
constant @digits = '0','1','2','3','4','5','6','7','8','9';

# Infinite lazy iterator to generate palindromic "gap" numbers
my @npal = flat [ @digits ], [ '00','11','22','33','44','55','66','77','88','99' ],
  {
    sink @^previous, @^penultimate;
    [ flat @digits.map: -> \digit { @penultimate.map: digit ~ * ~ digit  } ]
  } … *;

# Individual lazy palindromic gapful number iterators for each start/end digit
my @gappal = (1..9).map: -> \digit {
    my \divisor = digit + 10 * digit;
    @npal.map: -> \this { next unless (my \test = digit ~ this ~ digit) %% divisor; test }
}

# Display
( "(Required) First 20 gapful palindromes:",              ^20, 7
  ,"\n(Required) 86th through 100th:",                 85..99, 8
  ,"\n(Optional) 991st through 1,000th:",            990..999, 10
  ,"\n(Extra stretchy) 9,995th through 10,000th:", 9994..9999, 12
  ,"\n(Meh) 100,000th:",                                99999, 14
).hyper(:1batch).map: -> $caption, $range, $fmt {
    my $now = now;
    say $caption;
    put "$_: " ~ @gappal[$_-1][|$range].fmt("%{$fmt}s") for 1..9;
    say round( now - $now, .001 ), " seconds";
}

```

Output:

```
(Required) First 20 gapful palindromes:
1:     121    1001    1111    1221    1331    1441    1551    1661    1771    1881    1991   10901   11011   12221   13431   14641   15851   17171   18381   19591
2:     242    2002    2112    2222    2332    2442    2552    2662    2772    2882    2992   20702   21912   22022   23232   24442   25652   26862   28182   29392
3:     363    3003    3333    3663    3993   31713   33033   36663  300003  303303  306603  309903  312213  315513  318813  321123  324423  327723  330033  333333
4:     484    4004    4224    4444    4664    4884   40304   42724   44044   46464   48884  400004  401104  402204  403304  404404  405504  406604  407704  408804
5:    5005    5115    5225    5335    5445    5555    5665    5775    5885    5995   50105   51315   52525   53735   54945   55055   56265   57475   58685   59895
6:    6006    6336    6666    6996   61116   64746   66066   69696  600006  603306  606606  609906  612216  615516  618816  621126  624426  627726  630036  633336
7:    7007    7777   77077  700007  707707  710017  717717  720027  727727  730037  737737  740047  747747  750057  757757  760067  767767  770077  777777  780087
8:    8008    8448    8888   80608   86768   88088  800008  802208  804408  806608  808808  821128  823328  825528  827728  829928  840048  842248  844448  846648
9:    9009    9999   94149   99099  900009  909909  918819  927729  936639  945549  954459  963369  972279  981189  990099  999999 9459549 9508059 9557559 9606069
0.111 seconds

(Required) 86th through 100th:
1:   165561   166661   167761   168861   169961   170071   171171   172271   173371   174471   175571   176671   177771   178871   179971
2:   265562   266662   267762   268862   269962   270072   271172   272272   273372   274472   275572   276672   277772   278872   279972
3: 30366303 30399303 30422403 30455403 30488403 30511503 30544503 30577503 30600603 30633603 30666603 30699603 30722703 30755703 30788703
4:  4473744  4485844  4497944  4607064  4619164  4620264  4632364  4644464  4656564  4668664  4681864  4693964  4803084  4815184  4827284
5:   565565   566665   567765   568865   569965   570075   571175   572275   573375   574475   575575   576675   577775   578875   579975
6: 60399306 60422406 60455406 60488406 60511506 60544506 60577506 60600606 60633606 60666606 60699606 60722706 60755706 60788706 60811806
7: 72299227 72322327 72399327 72422427 72499427 72522527 72599527 72622627 72699627 72722727 72799727 72822827 72899827 72922927 72999927
8: 80611608 80622608 80633608 80644608 80655608 80666608 80677608 80688608 80699608 80800808 80811808 80822808 80833808 80844808 80855808
9: 95311359 95400459 95499459 95588559 95677659 95766759 95855859 95944959 96033069 96122169 96211269 96300369 96399369 96488469 96577569
0.046 seconds

(Optional) 991st through 1,000th:
1:   17799771   17800871   17811871   17822871   17833871   17844871   17855871   17866871   17877871   17888871
2:   27799772   27800872   27811872   27822872   27833872   27844872   27855872   27866872   27877872   27888872
3: 3084004803 3084334803 3084664803 3084994803 3085225803 3085555803 3085885803 3086116803 3086446803 3086776803
4:  482282284  482414284  482535284  482656284  482777284  482898284  482909284  483020384  483141384  483262384
5:   57800875   57811875   57822875   57833875   57844875   57855875   57866875   57877875   57888875   57899875
6: 6084004806 6084334806 6084664806 6084994806 6085225806 6085555806 6085885806 6086116806 6086446806 6086776806
7: 7452992547 7453223547 7453993547 7454224547 7454994547 7455225547 7455995547 7456226547 7456996547 7457227547
8: 8085995808 8086006808 8086116808 8086226808 8086336808 8086446808 8086556808 8086666808 8086776808 8086886808
9: 9675005769 9675995769 9676886769 9677777769 9678668769 9679559769 9680440869 9681331869 9682222869 9683113869
0.282 seconds

(Extra stretchy) 9,995th through 10,000th:
1:   1787447871   1787557871   1787667871   1787777871   1787887871   1787997871
2:   2787447872   2787557872   2787667872   2787777872   2787887872   2787997872
3: 308757757803 308760067803 308763367803 308766667803 308769967803 308772277803
4:  48326662384  48327872384  48329192384  48330303384  48331513384  48332723384
5:   5787447875   5787557875   5787667875   5787777875   5787887875   5787997875
6: 608760067806 608763367806 608766667806 608769967806 608772277806 608775577806
7: 746951159647 746958859647 746961169647 746968869647 746971179647 746978879647
8: 808690096808 808691196808 808692296808 808693396808 808694496808 808695596808
9: 968688886869 968697796869 968706607869 968715517869 968724427869 968733337869
3.114 seconds

(Meh) 100,000th:
1:   178788887871
2:   278788887872
3: 30878611687803
4:  4833326233384
5:   578789987875
6: 60878611687806
7: 74826144162847
8: 80869688696808
9: 96878077087869
32.603 seconds
```


[User]
Task

Find and show all palindromic primes   **n**,     where    **n   <   1000**

[Assistant]
```
say "{+$_} matching numbers:\n{.batch(10)».fmt('%3d').join: "\n"}"
    given (^1000).grep: { .is-prime and $_ eq .flip };

```

Output:

```
20 matching numbers:
  2   3   5   7  11 101 131 151 181 191
313 353 373 383 727 757 787 797 919 929
```


[User]
Task

Find palindromic primes   **n**   in base 16,   where   **n   <   50010**

[Assistant]
Trivial modification of Palindromic primes task.

```
say "{+$_} matching numbers:\n{.batch(10)».fmt('%3X').join: "\n"}"
    given (^500).grep: { .is-prime and .base(16) eq .base(16).flip };

```

Output:

```
13 matching numbers:
  2   3   5   7   B   D  11 101 151 161
191 1B1 1C1
```


[User]
Primes are prime no matter which base they are expressed in. Some numeric strings are prime in a large number of bases. (Not the *same* prime, but **a** prime.)

For example

The numeric string "255", while obviously not a prime in base 10, **is** a prime in bases:

```
     6   8  12  14  18  24  26  32  36  38  72  84  86  92  96 102 104 108 128 134
   138 144 158 164 188 216 224 236 242 246 252 254 264 272 294 318 332 344 348 368
   374 392 396 408 428 432 446 456 468 476 482 512 522 528 542 546 552 566 572 576
   578 594 596 602 606 614 618 626 654 702 714 722 728 756 762 774 776 788 806 816
   818 822 828 836 848 864 866 872 882 888 902 908 912 918 924 932 936 942 944 956
   966 986 998

```

among others.

There *are* numeric strings however, that are not a prime in **any** base. Confining ourselves to 'decimal' numeric strings; the single digit numeric primes are prime in every base where they are a valid number.

E.G.

The numeric string **"2"** is a prime in *every* base except base 2, where it is invalid.

The numeric string **"3"** is a prime in *every* base except base 2 and 3, where it is invalid.

**"4"** is *not* a prime in every base except bases 2, 3, and 4 where it is an invalid number (and hence not a prime there either.)

In general, even pan-base non-primes are much more prevalent than odd, though both are fairly common.

With the exception of **"10"**, numeric strings that end in 0 are composite in every base where they are valid.

Numeric strings where the greatest common divisor of all of the digits is more than 1 are composite in every base.

If a "decimal" numeric string N is composite in every base up to base N, it is composite in every base.

The digit **1** is an odd-ball case as it is neither prime nor composite. It typically is *not* included, but due to the ambiguous wording, would not be wrong if it is.

Task

* Find and display, here on this page, the first 40 pan-base non-prime "base 10" numeric strings.
* Find and display, here on this page, the first 20 **odd** pan-base non-prime "base 10" numeric strings.
* Find and display the count of pan-base non-prime "base 10" numeric strings up to at least the numeric string "1000".
* What percentage of them are odd / even?

See also

* OEIS A121719 - Strings of digits which are composite regardless of the base in which they are interpreted. Exclude bases in which numbers are not interpretable.

[Assistant]
```
use Base::Any;
use List::Divvy;

my @np = 4,6,8,9, |lazy (11..*).hyper.grep( -> $n { ($n.substr(*-1) eq '0') || (1 < [gcd] $n.comb».Int) || none (2..$n).map: { try "$n".&from-base($_).is-prime } } );

put "First 50 pan-base composites:\n" ~ @np[^50].batch(10)».fmt("%3s").join: "\n";
put "\nFirst 20 odd pan-base composites:\n" ~ @np.grep(* % 2)[^20].batch(10)».fmt("%3s").join: "\n";

my $threshold = 2500;
put "\nCount of pan-base composites up to and including $threshold: " ~ +@np.&upto($threshold);

put "Percent odd  up to and including $threshold: " ~ +@np.&upto($threshold).grep(* % 2) / +@np.&upto($threshold) × 100;
put "Percent even up to and including $threshold: " ~ +@np.&upto($threshold).grep(* %% 2) / +@np.&upto($threshold) × 100;

```

Output:

```
First 50 pan-base composites:
  4   6   8   9  20  22  24  26  28  30
 33  36  39  40  42  44  46  48  50  55
 60  62  63  64  66  68  69  70  77  80
 82  84  86  88  90  93  96  99 100 110
112 114 116 118 120 121 130 132 134 136

First 20 odd pan-base composites:
  9  33  39  55  63  69  77  93  99 121
143 165 169 187 231 253 273 275 297 299

Count of pan-base composites up to and including 2500: 953
Percent odd  up to and including 2500: 16.894019
Percent even up to and including 2500: 83.105981
```