[User]
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway.

The   **look-and-say sequence**   is also known as the   **Morris Number Sequence**,   after cryptographer Robert Morris,   and the puzzle   *What is the next number in the sequence 1,   11,   21,   1211,   111221?*   is sometimes referred to as the *Cuckoo's Egg*,   from a description of Morris in Clifford Stoll's book   *The Cuckoo's Egg*.

**Sequence Definition**

* Take a decimal number
* *Look* at the number, visually grouping consecutive runs of the same digit.
* *Say* the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.

:   This becomes the next number of the sequence.

**An example:**

* Starting with the number 1,   you have *one* 1 which produces 11
* Starting with 11,   you have *two* 1's.   I.E.:   21
* Starting with 21,   you have *one* 2, then *one* 1.   I.E.:   (12)(11) which becomes 1211
* Starting with 1211,   you have *one* 1, *one* 2, then *two* 1's.   I.E.:   (11)(12)(21) which becomes 111221

Task

Write a program to generate successive members of the look-and-say sequence.

Related tasks

* Fours is the number of letters in the ...
* Number names
* Self-describing numbers
* Self-referential sequence
* Spelling of ordinal numbers

See also

* Look-and-Say Numbers (feat John Conway), A Numberphile Video.
* This task is related to, and an application of, the Run-length encoding task.
* Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

In Raku it is natural to avoid explicit loops; rather we use the sequence operator to define a lazy infinite sequence. We'll print the first 15 values here.

```
.say for ('1', *.subst(/(.)$0*/, { .chars ~ .[0] }, :g) ... *)[^15];
```

Output:

```
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
11131221133112132113212221
3113112221232112111312211312113211
1321132132111213122112311311222113111221131221
11131221131211131231121113112221121321132132211331222113112211
311311222113111231131112132112311321322112111312211312111322212311322113212221
```


[User]
Task

Loop over multiple arrays   (or lists or tuples or whatever they're called in
your language)   and display the    *i* th    element of each.

Use your language's   "for each"   loop if it has one, otherwise iterate
through the collection in order with some other loop.

For this example, loop over the arrays:

```
    (a,b,c)
    (A,B,C)
    (1,2,3)

```

to produce the output:

```
    aA1
    bB2
    cC3

```

If possible, also describe what happens when the arrays are of different lengths.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015.12

Note that all of the following work with *any* iterable object, (array, list, range, sequence; anything that does the Iterable role), not just arrays.

### Basic functionality

```
for <a b c> Z <A B C> Z 1, 2, 3 -> ($x, $y, $z) {
   say $x, $y, $z;
}
```

The `Z` operator stops emitting items as soon as the shortest input list is exhausted. However, short lists are easily extended by replicating all or part of the list, or by appending any kind of lazy list generator to supply default values as necessary.

Since `Z` will return a list of lists (in this example, the first list is `('a', 'A', 1)`, parentheses are used around in the lambda signature `($x, $y, $z)` to unpack the list for each iteration.

### Factoring out concatenation

Note that we can also factor out the concatenation by making the Z metaoperator apply the ~ concatenation operator across each triple:

```
.say for <a b c> Z~ <A B C> Z~ 1, 2, 3;
```

We could also use the zip-to-string with the reduction metaoperator:

```
.say for [Z~] <a b c>, <A B C>, (1,2,3);
```

We could also write that out "long-hand":

```
.say for zip :with(&infix:<~>), <a b c>, <A B C>, (1,2,3);
```

returns the exact same result so if you aren't comfortable with the concise operators, you have a choice.

### A list and its indices

The common case of iterating over a list and a list of its indices can be done using the same method:

```
for ^Inf Z <a b c d> -> ($i, $letter) { ... }
```

or by using the `.kv` (key and value) method on the list (and dropping the parentheses because the list returned by `.kv` is a flattened list):

```
for <a b c d>.kv -> $i, $letter { ... }
```

### Iterate until all exhausted

If you have different sized lists that you want to pull a value from each per iteration, but want to continue until **all** of the lists are exhausted, we have `roundrobin`.

```
.put for roundrobin <a b c>, 'A'..'G', ^5;
```

yields:

```
a A 0
b B 1
c C 2
D 3
E 4
F
G
```


[User]
Task

Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).

If a number is 10, stop the loop after printing it, and do not generate any further numbers.

Otherwise, generate and print a second random number before restarting the loop.

If the number 10 is never generated as the first number in a loop, loop forever.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version #21 "Seattle"

```
loop {
    say my $n = (0..19).pick;
    last if $n == 10;
    say (0..19).pick;
}
```


[User]
Task

Show the following output using one loop.

```
1, 2, 3, 4, 5
6, 7, 8, 9, 10

```

Try to achieve the result by forcing the next iteration within the loop
upon a specific condition, if your language allows it.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

**Works with**: Rakudo Star version 2010.08

```
for 1 .. 10 {
    .print;
    if $_ %% 5 {
        print "\n";
        next;
    }
    print ', ';
}

```

or without using a loop:

```
$_.join(", ").say for [1..5], [6..10];

```


[User]
Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

Reference

* Do while loop Wikipedia.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo Star version 2010.08

```
my $val = 0;
repeat {
    say ++$val;
} while $val % 6;
```

`repeat ... until condition` is equivalent to `do ... while not condition`.

```
my $val = 0;
repeat {
    say ++$val;
} until $val %% 6;
```

(Here we've used `%%`, the "divisible-by" operator.)

You can also put the condition before the block, without changing the order of evaluation.

```
my $val = 0;
repeat while $val % 6 {
    say ++$val;
}
```


[User]
Task

Write a    *for*    loop which writes a countdown from   **10**   to   **0**.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo Star version 2010.08

```
for 10 ... 0 {
    .say;
}
```


[User]
“**For**”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.

Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.

Task

Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.

Specifically print out the following pattern by using one for loop nested in another:

```
*
**
***
****
*****
```

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

Reference

* For loop Wikipedia.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version #22 "Thousand Oaks"

```
for ^5 {

	for 0..$_ {
		print "*";
	}

	print "\n";

}
```

or using only one for loop:

```
say '*' x $_ for 1..5;
```

or without using any loops at all:

```
([\~] "*" xx 5).join("\n").say;
```


[User]
Task

Demonstrate a   *for-loop*   where the step-value is greater than one.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2010.07

Depending on how you define your terms, this task is either trivial or impossible in Raku. `for` in Raku doesn't have a step value, it's an iteration operator. It iterates through any iterable object passed to it and sets the topic variable to each iterated value in turn. If you close one eye and squint, I guess you could say it has a step value of 1 (or more accurately, Next) and that isn't really changeable. Whatever iterable you pass to it though can have pretty much any value in pretty much any order you desire, so effectively the "step" value is completely unconstrained.

Examples of iterables (not exhaustive):

* Things that do a positional role:

:   * Array
    * List
    * Range
    * Sequence

* Things that do an associative role:

:   * Bag
    * BagHash
    * Hash
    * Map
    * Mix
    * MixHash
    * QuantHash
    * Set
    * SetHash

Probably the most straightforward way to do this is with a sequence. With at least two values on the left-hand side, the sequence operator (`...`) can infer an arithmetic series. (With at least three values, it can infer a geometric sequence, too.)

```
for 2, 4 ... 8 {
    print "$_, ";
}

say 'whom do we appreciate?';
```

But there is nothing constraining the sequence to a constant step. Here's one with a *random* step.

```
.say for rand, *+rand-.5 ... *.abs>2
```

Sample output:

```
0.1594860240843563
-0.11336537297314198
-0.04195945218519992
-0.024844489074366427
-0.20616093727620433
-0.17589258387167517
-0.40547336592612593
0.04561929494516015
0.4886003890463373
0.7843094215547495
0.6413619589945883
1.0694380727281951
1.472290164849169
1.8310404939418325
2.326272380988639

```

For that matter, the iterated object doesn't need to contain numbers.

```
.say for <17/32 π banana 👀 :d(7) 🦋>;
```


[User]
Loop through and print each element in a collection in order.

Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.10-40

```
say $_ for @collection;
```

Raku leaves off the each from foreach, leaving us with for instead. The variable $\_ refers to the current element, unless you assign a name to it using ->.

```
for @collection -> $currentElement { say $currentElement; }
```

Raku will do it's best to put the topic at the right spot.

```
.say for @collection;
for @collection { .say };
```

Iteration can also be done with hyperoperators. In this case it's a candidate for autothreading and as such, execution order may vary. The resulting list will be in order.

```
@collection>>.say;
@collection>>.=&infix:<+>(2); # increment each element by 2
```


[User]
Sometimes, one may need   (or want)   a loop which
its   *iterator*   (the index
variable)   is modified within the

loop body    *in addition to the normal incrementation by the   (**do**)   loop structure index*.

Goal

Demonstrate the best way to accomplish this.

Task

Write a loop which:

:   :   * starts the index (variable) at   **42**
        * (at iteration time)   increments the index by unity
        * if the index is prime:

        :   :   * displays the count of primes found (so far) and the prime   (to the terminal)
                * increments the index such that the new index is now the (old) index plus that prime

        * terminates the loop when   **42**   primes are shown

Extra credit:   because of the primes get rather large, use commas
within the displayed primes to ease comprehension.

Show all output here.

Note

Not all programming languages allow the modification of a
loop's index.   If that is the case, then use whatever method that
is appropriate or idiomatic for that language.   Please add a note
if the loop's index isn't modifiable.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)
Hmm.

> Demonstrate the best way to accomplish this.

The *best* way is probably to not use an explicit loop. Just calculate the sequence directly.

```
# the actual sequence logic
my @seq = grep *.is-prime, (42, { .is-prime ?? $_+<1 !! $_+1 } … *);

# display code
say (1+$_).fmt("%-4s"), @seq[$_].flip.comb(3).join(',').flip.fmt("%20s") for ^42;

```

Output:

```
1                     43
2                     89
3                    179
4                    359
5                    719
6                  1,439
7                  2,879
8                  5,779
9                 11,579
10                23,159
11                46,327
12                92,657
13               185,323
14               370,661
15               741,337
16             1,482,707
17             2,965,421
18             5,930,887
19            11,861,791
20            23,723,597
21            47,447,201
22            94,894,427
23           189,788,857
24           379,577,741
25           759,155,483
26         1,518,310,967
27         3,036,621,941
28         6,073,243,889
29        12,146,487,779
30        24,292,975,649
31        48,585,951,311
32        97,171,902,629
33       194,343,805,267
34       388,687,610,539
35       777,375,221,081
36     1,554,750,442,183
37     3,109,500,884,389
38     6,219,001,768,781
39    12,438,003,537,571
40    24,876,007,075,181
41    49,752,014,150,467
42    99,504,028,301,131
```


[User]
Task

Print out        **SPAM**        followed by a   *newline*   in an infinite loop.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo Star version 2010.08

```
loop {
    say 'SPAM';
}
```

In addition, there are various ways of writing lazy, infinite lists in Raku:

```
print "SPAM\n" xx *;      # repetition operator
print "SPAM\n", ~* ... *; # sequence operator
map {say "SPAM"}, ^Inf;   # upto operator
```


[User]
Quite often one needs loops which, in the last iteration, execute only part of the loop body.

Goal

Demonstrate the best way to do this.

Task

Write a loop which writes the comma-separated list

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10

```

using separate output statements for the number
and the comma from within the body of the loop.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

```
for 1 .. 10 {
    .print;
    last when 10;
    print ', ';
}

print "\n";
```


[User]
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over

[
1
,
…
,
20
]
{\displaystyle {\displaystyle [1,\ldots ,20]}}
.

The loops iterate rows and columns of the array printing the elements until the value

20
{\displaystyle {\displaystyle 20}}
 is met.

Specifically, this task also shows how to break out of nested loops.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-09-18

```
my @a = [ (1..20).roll(10) ] xx *;

LINE: for @a -> @line {
    for @line -> $elem {
        print " $elem";
        last LINE if $elem == 20;
    }
    print "\n";
}
print "\n";

```

Output:

```
 15 6 14 13 14 7 9 16 8 18
 7 6 18 11 19 13 12 5 18 8
 17 17 9 5 4 8 17 8 3 11
 9 20
```


[User]
Task

Start an integer value at   **1024**.

Loop while it is greater than zero.

Print the value (with a newline) and divide it by two each time through the loop.

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

Here is a straightforward translation of the task description:

```
my $n = 1024; while $n > 0 { say $n; $n div= 2 }
```

The same thing with a C-style loop and a bitwise shift operator:

```
loop (my $n = 1024; $n > 0; $n +>= 1) { say $n }
```

And here's how you'd *really* write it, using a sequence operator that intuits the division for you:

```
.say for 1024, 512, 256 ... 1
```


[User]
Some languages allow multiple **loop** ranges, such as the **PL/I** example (snippet) below.

```
                                       /* all variables are DECLARED as integers. */
          prod=  1;                    /*start with a product of unity.           */
           sum=  0;                    /*  "     "  "   sum    " zero.            */
             x= +5;
             y= -5;
             z= -2;
           one=  1;
         three=  3;
         seven=  7;
                                       /*(below)  **  is exponentiation:  4**3=64 */
           do j=   -three  to     3**3        by three   ,
                   -seven  to   +seven        by   x     ,
                      555  to      550 - y               ,
                       22  to      -28        by -three  ,
                     1927  to     1939                   ,
                        x  to        y        by   z     ,
                    11**x  to    11**x + one;
                                                        /* ABS(n) = absolute value*/
           sum= sum + abs(j);                           /*add absolute value of J.*/
           if abs(prod)<2**27 & j¬=0  then prod=prod*j; /*PROD is small enough & J*/
           end;                                         /*not 0, then multiply it.*/
                     /*SUM and PROD are used for verification of J incrementation.*/
         display (' sum= ' ||  sum);                    /*display strings to term.*/
         display ('prod= ' || prod);                    /*   "       "     "   "  */
```

Task

Simulate/translate the above **PL/I** program snippet as best as possible in your
language,   with particular emphasis on the   **do**   loop construct.

The   **do**   index must be incremented/decremented in the same order shown.

If feasible, add commas to the two output numbers (being displayed).

Show all output here.

```
      A simple PL/I   DO  loop  (incrementing or decrementing)  has the construct of:

            DO variable = start_expression    {TO ending_expression]       {BY increment_expression} ;
                 ---or---
            DO variable = start_expression    {BY increment_expression}    {TO ending_expression]    ;

      where it is understood that all expressions will have a value.  The  variable  is normally a
      scaler variable,  but need not be  (but for this task, all variables and expressions are declared
      to be scaler integers).   If the   BY   expression is omitted,  a   BY   value of unity is used.
      All expressions are evaluated before the   DO   loop is executed,  and those values are used
      throughout the   DO   loop execution   (even though, for instance,  the value of   Z   may be
      changed within the   DO   loop.    This isn't the case here for this task.

      A multiple-range   DO   loop can be constructed by using a comma (,) to separate additional ranges
      (the use of multiple   TO   and/or   BY   keywords).     This is the construct used in this task.

      There are other forms of   DO   loops in PL/I involving the  WHILE  clause,  but those won't be
      needed here.    DO  loops without a   TO   clause might need a   WHILE   clause  or some other
      means of exiting the loop  (such as  LEAVE,  RETURN,  SIGNAL,  GOTO,  or  STOP),  or some other
      (possible error) condition that causes transfer of control outside the  DO  loop.

      Also, in PL/I, the check if the   DO   loop index value is outside the range is made at the
      "head"  (start)  of the   DO  loop,  so it's possible that the   DO   loop isn't executed,  but
      that isn't the case for any of the ranges used in this task.

      In the example above, the clause:                    x    to y       by z
      will cause the variable   J   to have to following values  (in this order):  5  3  1  -1  -3  -5

      In the example above, the clause:                 -seven  to +seven  by x
      will cause the variable   J   to have to following values  (in this order):  -7  -2   3

```

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

This task is really conflating two separate things, (at least in Raku). Sequences and loops are two different concepts and may be considered / implemented separately from each other.

Yes, you can generate a sequence with a loop, and a loop can use a sequence for an iteration value, but the two are somewhat orthogonal and don't necessarily overlap.

Sequences are first class objects in Raku. You can (and typically do) generate a sequence using the (appropriately enough) sequence operator and can assign it to a variable and/or pass it as a parameter; the entire sequence, not just it's individual values. It *may* be used in a looping construct, but it is not necessary to do so.

Various looping constructs often do use sequences as their iterator but not exclusively, possibly not even in the majority.

Displaying the j sequence as well since it isn't very large.

```
sub comma { ($^i < 0 ?? '-' !! '') ~ $i.abs.flip.comb(3).join(',').flip }

my \x     =  5;
my \y     = -5;
my \z     = -2;
my \one   =  1;
my \three =  3;
my \seven =  7;

my $j = flat
  ( -three, *+three … 3³         ),
  ( -seven, *+x     …^ * > seven ),
  ( 555   .. 550 - y             ),
  ( 22,     *-three …^ * < -28   ),
  ( 1927  .. 1939                ),
  ( x,      *+z     …^ * < y     ),
  ( 11**x .. 11**x + one         );

put 'j sequence: ', $j;
put '       Sum: ', comma [+] $j».abs;
put '   Product: ', comma ([\*] $j.grep: so +*).first: *.abs > 2²⁷;

# Or, an alternate method for generating the 'j' sequence, employing user-defined
# operators to preserve the 'X to Y by Z' layout of the example code.
# Note that these operators will only work for monotonic sequences.

sub infix:<to> { $^a ... $^b }
sub infix:<by> { $^a[0, $^b.abs ... *] }

$j = cache flat
    -three  to          3**3  by  three ,
    -seven  to         seven  by      x ,
       555  to     (550 - y)            ,
        22  to           -28  by -three ,
      1927  to          1939  by    one ,
         x  to             y  by      z ,
     11**x  to (11**x + one)            ;

put "\nLiteral minded variant:";
put '       Sum: ', comma [+] $j».abs;
put '   Product: ', comma ([\*] $j.grep: so +*).first: *.abs > 2²⁷;

```

Output:

```
j sequence: -3 0 3 6 9 12 15 18 21 24 27 -7 -2 3 555 22 19 16 13 10 7 4 1 -2 -5 -8 -11 -14 -17 -20 -23 -26 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 5 3 1 -1 -3 -5 161051 161052
       Sum: 348,173
   Product: -793,618,560

Literal minded variant:
       Sum: 348,173
   Product: -793,618,560

```


[User]
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.

The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference.   You are then to use that *same* syntax/function but with different parameters; and show, here, what would happen.

Use these values if possible:

:   :   :   :   :   | start | stop | increment | Comment |
                    | --- | --- | --- | --- |
                    | -2 | 2 | 1 | Normal |
                    | -2 | 2 | 0 | Zero increment |
                    | -2 | 2 | -1 | Increments away from stop value |
                    | -2 | 2 | 10 | First increment is beyond stop value |
                    | 2 | -2 | 1 | Start more than stop: positive increment |
                    | 2 | 2 | 1 | Start equal stop: positive increment |
                    | 2 | 2 | -1 | Start equal stop: negative increment |
                    | 2 | 2 | 0 | Start equal stop: zero increment |
                    | 0 | 0 | 0 | Start equal stop equal zero: zero increment |

Related tasks

* Loop over multiple arrays simultaneously
* Loops/Break
* Loops/Continue
* Loops/Do-while
* Loops/Downward for
* Loops/For
* Loops/For with a specified step
* Loops/Foreach
* Loops/Increment loop index within loop body
* Loops/Infinite
* Loops/N plus one half
* Loops/Nested
* Loops/While
* Loops/with multiple ranges
* Loops/Wrong ranges

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.08

It would be odd to call ANY of these sequences "wrong" in Raku. Raku specifically has built in capability of working with infinite sequences. Just because a sequence is infinite, doesn't mean you can't define it, work with it or use values from it. Sure, if you try to reify the whole thing you may be waiting a while, but there is nothing preventing you from using a portion of it.

Raku sequence definitions *specifically* allow "ending points" that may never occur in the sequence. Since that is the case, you don't even really **need** to specify a stop value. You can just say stop at "whatever". Whatever is spelled "**\***" in Raku.

There is additional syntax you can add to stop at the nearest value, last value previous or first value successor to the "stop value" (Note I didn't say less than or greater than the stop value since the sequence can be ascending, descending or non-monotonic).

Also note: The iterator function for the sequence is literally a function. It is any expression that produces a value. These sequences all use simple arithmatic increments but that is not a limitation of the sequence operator.

```
# Given sequence definitions
#   start  stop  inc.   Comment
for   -2,    2,    1, # Normal
      -2,    2,    0, # Zero increment
      -2,    2,   -1, # Increments away from stop value
      -2,    2,   10, # First increment is beyond stop value
       2,   -2,    1, # Start more than stop: positive increment
       2,    2,    1, # Start equal stop: positive increment
       2,    2,   -1, # Start equal stop: negative increment
       2,    2,    0, # Start equal stop: zero increment
       0,    0,    0, # Start equal stop equal zero: zero increment

# Additional "problematic" sequences
       1,  Inf,    3, # Endpoint literally at infinity
       0,    π,  τ/8, # Floating point numbers
     1.4,    *, -7.1  # Whatever

  -> $start, $stop, $inc {
    my $seq = flat ($start, *+$inc … $stop);
    printf "Start: %3s, Stop: %3s, Increment: %3s | ", $start, $stop.Str, $inc;
    # only show up to the first 15 elements of possibly infinite sequences
    put $seq[^15].grep: +*.defined
}

# For that matter the start and end values don't need to be numeric either. Both
# or either can be a function, list, or other object. Really anything that a
# "successor" function can be defined for and produces a value.
say "\nDemonstration of some other specialized sequence operator functionality:";
# Start with a list, iterate by multiplying the previous 3 terms together
# and end with a term defined by a function.
put 1, -.5, 2.sqrt, * × * × * … *.abs < 1e-2;

# Start with an array, iterate by rotating, end when 0 is in the last place.
say [0,1,2,3,4,5], *.rotate(-1).Array … !*.tail;

# Iterate strings backwards.
put 'xp' … 'xf';

```

Output:

```
Start:  -2, Stop:   2, Increment:   1 | -2 -1 0 1 2
Start:  -2, Stop:   2, Increment:   0 | -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2
Start:  -2, Stop:   2, Increment:  -1 | -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16
Start:  -2, Stop:   2, Increment:  10 | -2 8 18 28 38 48 58 68 78 88 98 108 118 128 138
Start:   2, Stop:  -2, Increment:   1 | 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Start:   2, Stop:   2, Increment:   1 | 2
Start:   2, Stop:   2, Increment:  -1 | 2
Start:   2, Stop:   2, Increment:   0 | 2
Start:   0, Stop:   0, Increment:   0 | 0
Start:   1, Stop: Inf, Increment:   3 | 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43
Start:   0, Stop: 3.141592653589793, Increment: 0.7853981633974483 | 0 0.7853981633974483 1.5707963267948966 2.356194490192345 3.141592653589793
Start: 1.4, Stop:   *, Increment: -7.1 | 1.4 -5.7 -12.8 -19.9 -27 -34.1 -41.2 -48.3 -55.4 -62.5 -69.6 -76.7 -83.8 -90.9 -98

Demonstration of some other specialized sequence operator functionality:
1 -0.5 1.4142135623730951 -0.7071067811865476 0.5000000000000001 -0.5000000000000002 0.176776695296637 -0.04419417382415928 0.0039062500000000095
([0 1 2 3 4 5] [5 0 1 2 3 4] [4 5 0 1 2 3] [3 4 5 0 1 2] [2 3 4 5 0 1] [1 2 3 4 5 0])
xp xo xn xm xl xk xj xi xh xg xf
```


[User]
Every square matrix

A
{\displaystyle {\displaystyle A}}
 can be decomposed into a product of a lower triangular matrix

L
{\displaystyle {\displaystyle L}}
 and a upper triangular matrix

U
{\displaystyle {\displaystyle U}}
,
as described in LU decomposition.

:   A
    =
    L
    U
    {\displaystyle {\displaystyle A=LU}}

It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.

There are several algorithms for calculating L and U.
To derive *Crout's algorithm* for a 3x3 example,
we have to solve the following system:

:   A
    =

    (

    a

    11

    a

    12

    a

    13

    a

    21

    a

    22

    a

    23

    a

    31

    a

    32

    a

    33
    )
    =

    (

    l

    11

    0

    0

    l

    21

    l

    22

    0

    l

    31

    l

    32

    l

    33
    )

    (

    u

    11

    u

    12

    u

    13

    0

    u

    22

    u

    23

    0

    0

    u

    33
    )
    =
    L
    U
    {\displaystyle {\displaystyle A={\begin{pmatrix}a\_{11}&a\_{12}&a\_{13}\\a\_{21}&a\_{22}&a\_{23}\\a\_{31}&a\_{32}&a\_{33}\\\end{pmatrix}}={\begin{pmatrix}l\_{11}&0&0\\l\_{21}&l\_{22}&0\\l\_{31}&l\_{32}&l\_{33}\\\end{pmatrix}}{\begin{pmatrix}u\_{11}&u\_{12}&u\_{13}\\0&u\_{22}&u\_{23}\\0&0&u\_{33}\end{pmatrix}}=LU}}

We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of

L
{\displaystyle {\displaystyle L}}
 are set to 1

:   l

    11
    =
    1
    {\displaystyle {\displaystyle l\_{11}=1}}
:   l

    22
    =
    1
    {\displaystyle {\displaystyle l\_{22}=1}}
:   l

    33
    =
    1
    {\displaystyle {\displaystyle l\_{33}=1}}

so we get a solvable system of 9 unknowns and 9 equations.

:   A
    =

    (

    a

    11

    a

    12

    a

    13

    a

    21

    a

    22

    a

    23

    a

    31

    a

    32

    a

    33
    )
    =

    (

    1

    0

    0

    l

    21

    1

    0

    l

    31

    l

    32

    1
    )

    (

    u

    11

    u

    12

    u

    13

    0

    u

    22

    u

    23

    0

    0

    u

    33
    )
    =

    (

    u

    11

    u

    12

    u

    13

    u

    11

    l

    21

    u

    12

    l

    21
    +

    u

    22

    u

    13

    l

    21
    +

    u

    23

    u

    11

    l

    31

    u

    12

    l

    31
    +

    u

    22

    l

    32

    u

    13

    l

    31
    +

    u

    23

    l

    32
    +

    u

    33
    )
    =
    L
    U
    {\displaystyle {\displaystyle A={\begin{pmatrix}a\_{11}&a\_{12}&a\_{13}\\a\_{21}&a\_{22}&a\_{23}\\a\_{31}&a\_{32}&a\_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l\_{21}&1&0\\l\_{31}&l\_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u\_{11}&u\_{12}&u\_{13}\\0&u\_{22}&u\_{23}\\0&0&u\_{33}\end{pmatrix}}={\begin{pmatrix}u\_{11}&u\_{12}&u\_{13}\\u\_{11}l\_{21}&u\_{12}l\_{21}+u\_{22}&u\_{13}l\_{21}+u\_{23}\\u\_{11}l\_{31}&u\_{12}l\_{31}+u\_{22}l\_{32}&u\_{13}l\_{31}+u\_{23}l\_{32}+u\_{33}\end{pmatrix}}=LU}}

Solving for the other

l
{\displaystyle {\displaystyle l}}
 and

u
{\displaystyle {\displaystyle u}}
, we get the following equations:

:   u

    11
    =

    a

    11
    {\displaystyle {\displaystyle u\_{11}=a\_{11}}}
:   u

    12
    =

    a

    12
    {\displaystyle {\displaystyle u\_{12}=a\_{12}}}
:   u

    13
    =

    a

    13
    {\displaystyle {\displaystyle u\_{13}=a\_{13}}}

:   u

    22
    =

    a

    22
    −

    u

    12

    l

    21
    {\displaystyle {\displaystyle u\_{22}=a\_{22}-u\_{12}l\_{21}}}
:   u

    23
    =

    a

    23
    −

    u

    13

    l

    21
    {\displaystyle {\displaystyle u\_{23}=a\_{23}-u\_{13}l\_{21}}}

:   u

    33
    =

    a

    33
    −
    (

    u

    13

    l

    31
    +

    u

    23

    l

    32
    )
    {\displaystyle {\displaystyle u\_{33}=a\_{33}-(u\_{13}l\_{31}+u\_{23}l\_{32})}}

and for

l
{\displaystyle {\displaystyle l}}
:

:   l

    21
    =

    1

    u

    11

    a

    21
    {\displaystyle {\displaystyle l\_{21}={\frac {1}{u\_{11}}}a\_{21}}}
:   l

    31
    =

    1

    u

    11

    a

    31
    {\displaystyle {\displaystyle l\_{31}={\frac {1}{u\_{11}}}a\_{31}}}

:   l

    32
    =

    1

    u

    22
    (

    a

    32
    −

    u

    12

    l

    31
    )
    {\displaystyle {\displaystyle l\_{32}={\frac {1}{u\_{22}}}(a\_{32}-u\_{12}l\_{31})}}

We see that there is a calculation pattern, which can be expressed as the following formulas, first for

U
{\displaystyle {\displaystyle U}}

:   u

    i
    j
    =

    a

    i
    j
    −

    ∑

    k
    =
    1

    i
    −
    1

    u

    k
    j

    l

    i
    k
    {\displaystyle {\displaystyle u\_{ij}=a\_{ij}-\sum \_{k=1}^{i-1}u\_{kj}l\_{ik}}}

and then for

L
{\displaystyle {\displaystyle L}}

:   l

    i
    j
    =

    1

    u

    j
    j
    (

    a

    i
    j
    −

    ∑

    k
    =
    1

    j
    −
    1

    u

    k
    j

    l

    i
    k
    )
    {\displaystyle {\displaystyle l\_{ij}={\frac {1}{u\_{jj}}}(a\_{ij}-\sum \_{k=1}^{j-1}u\_{kj}l\_{ik})}}

We see in the second formula that to get the

l

i
j
{\displaystyle {\displaystyle l\_{ij}}}
 below the diagonal, we have to divide by the diagonal element (pivot)

u

j
j
{\displaystyle {\displaystyle u\_{jj}}}
, so we get problems when

u

j
j
{\displaystyle {\displaystyle u\_{jj}}}
 is either 0 or very small, which leads to numerical instability.

The solution to this problem is *pivoting*

A
{\displaystyle {\displaystyle A}}
, which means rearranging the rows of

A
{\displaystyle {\displaystyle A}}
, prior to the

L
U
{\displaystyle {\displaystyle LU}}
 decomposition, in a way that the largest element of each column gets onto the diagonal of

A
{\displaystyle {\displaystyle A}}
. Rearranging the rows means to multiply

A
{\displaystyle {\displaystyle A}}
 by a permutation matrix

P
{\displaystyle {\displaystyle P}}
:

:   P
    A
    ⇒

    A
    ′
    {\displaystyle {\displaystyle PA\Rightarrow A'}}

Example:

:   (

    0

    1

    1

    0
    )

    (

    1

    4

    2

    3
    )
    ⇒

    (

    2

    3

    1

    4
    )
    {\displaystyle {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}}

The decomposition algorithm is then applied on the rearranged matrix so that

:   P
    A
    =
    L
    U
    {\displaystyle {\displaystyle PA=LU}}

Task description

The task is to implement a routine which will take a square nxn matrix

A
{\displaystyle {\displaystyle A}}
 and return a lower triangular matrix

L
{\displaystyle {\displaystyle L}}
, a upper triangular matrix

U
{\displaystyle {\displaystyle U}}
 and a permutation matrix

P
{\displaystyle {\displaystyle P}}
,
so that the above equation is fulfilled.

You should then test it on the following two examples and include your output.

Example 1

```
A

1   3   5
2   4   7
1   1   0

L

1.00000   0.00000   0.00000
0.50000   1.00000   0.00000
0.50000  -1.00000   1.00000

U

2.00000   4.00000   7.00000
0.00000   1.00000   1.50000
0.00000   0.00000  -2.00000

P

0   1   0
1   0   0
0   0   1

```

Example 2

```
A

11    9   24    2
 1    5    2    6
 3   17   18    1
 2    5    7    1

L

1.00000   0.00000   0.00000   0.00000
0.27273   1.00000   0.00000   0.00000
0.09091   0.28750   1.00000   0.00000
0.18182   0.23125   0.00360   1.00000

U

11.00000    9.00000   24.00000    2.00000
 0.00000   14.54545   11.45455    0.45455
 0.00000    0.00000   -3.47500    5.68750
 0.00000    0.00000    0.00000    0.51079

P

1   0   0   0
0   0   1   0
0   1   0   0
0   0   0   1

```

[Assistant]
(formerly Perl 6)

Translation of Ruby.

```
for (  [1, 3, 5], # Test Matrices
       [2, 4, 7],
       [1, 1, 0]
    ),
    (  [11,  9, 24,  2],
       [ 1,  5,  2,  6],
       [ 3, 17, 18,  1],
       [ 2,  5,  7,  1]
    )
    -> @test {
    say-it 'A Matrix', @test;
    say-it( .[0], @(.[1]) ) for 'P Matrix', 'Aʼ Matrix', 'L Matrix', 'U Matrix' Z, lu @test;
}

sub lu (@a) {
    die unless @a.&is-square;
    my $n  = @a;
    my @P  = pivotize @a;
    my @Aʼ = mmult @P, @a;
    my @L  = matrix-ident $n;
    my @U  = matrix-zero  $n;
    for ^$n X ^$n -> ($i,$j) {
        if $j ≥ $i { @U[$i;$j] =  @Aʼ[$i;$j] - [+] map { @U[$_;$j] × @L[$i;$_] }, ^$i              }
        else       { @L[$i;$j] = (@Aʼ[$i;$j] - [+] map { @U[$_;$j] × @L[$i;$_] }, ^$j) / @U[$j;$j] }
    }
    @P, @Aʼ, @L, @U;
}

sub pivotize (@m) {
    my $size = @m;
    my @id   = matrix-ident $size;
    for ^$size -> $i {
        my $max = @m[$i;$i];
        my $row = $i;
        for $i ..^ $size -> $j {
            if @m[$j;$i] > $max {
                $max = @m[$j;$i];
                $row = $j;
            }
        }
        @id[$row, $i] = @id[$i, $row] if $row != $i;
    }
    @id
}

sub is-square (@m) { so @m == all @m }

sub matrix-zero ($n, $m = $n) { map { [ flat 0 xx $n ] }, ^$m }

sub matrix-ident ($n) { map { [ flat 0 xx $_, 1, 0 xx $n - 1 - $_ ] }, ^$n }

sub mmult(@a,@b) {
    my @p;
    for ^@a X ^@b[0] -> ($r, $c) {
        @p[$r;$c] += @a[$r;$_] × @b[$_;$c] for ^@b;
    }
    @p
}

sub rat-int ($num) {
    return $num unless $num ~~ Rat;
    return $num.narrow if $num.narrow ~~ Int;
    $num.nude.join: '/';

}

sub say-it ($message, @array) {
    say "\n$message";
    $_».&rat-int.fmt("%7s").say for @array;
}

```

Output:

```
A Matrix
      1       3       5
      2       4       7
      1       1       0

P Matrix
      0       1       0
      1       0       0
      0       0       1

Aʼ Matrix
      2       4       7
      1       3       5
      1       1       0

L Matrix
      1       0       0
    1/2       1       0
    1/2      -1       1

U Matrix
      2       4       7
      0       1     3/2
      0       0      -2

A Matrix
     11       9      24       2
      1       5       2       6
      3      17      18       1
      2       5       7       1

P Matrix
      1       0       0       0
      0       0       1       0
      0       1       0       0
      0       0       0       1

Aʼ Matrix
     11       9      24       2
      3      17      18       1
      1       5       2       6
      2       5       7       1

L Matrix
      1       0       0       0
   3/11       1       0       0
   1/11   23/80       1       0
   2/11  37/160   1/278       1

U Matrix
     11       9      24       2
      0  160/11  126/11    5/11
      0       0 -139/40   91/16
      0       0       0  71/139

```


[User]
A Lucas-Carmichael number, is a squarefree composite integer **n** such that **p+1** divides **n+1** for all the prime factors **p** of **n**.

Task

Write a function that generates all the Lucas-Carmichael numbers with **n** prime factors in a given range **[A, B]**.

* Show the smallest Lucas-Carmichael with **n** prime factors, for **n = 3..12**.

* Show the count of Lucas-Carmichael numbers less than **10^n**, for **n = 1..10**.

Algorithm

Algorithm for generating Lucas-Carmichael numbers with n prime factors

Algorithm for generating Lucas-Carmichael numbers with n prime factors

See also

* OEIS A006972: Lucas-Carmichael numbers: squarefree composite numbers k such that p | k => p+1 | k+1

* OEIS A216928: Least Lucas-Carmichael number with n prime factors

* OEIS A216929: Number of Lucas-Carmichael numbers less than 10^n

[Assistant]
**Translation of**: Perl

```
# 20231224 Raku programming solution

sub primorial($n) { [*] ((2..*).grep: *.is-prime)[^$n] }
sub divceil($x, $y) { ($x %% $y ?? 0 !! 1) + $x div $y } # ceil(x/y)

sub LC_in_range ($A is copy, $B, $k) {

   my ($max_p, @LC) = Int(sqrt($B + 1) - 1);
   $A = max(primorial($k + 1) +> 1, $A);

   sub SUB($m, $L, $lo is copy, $k) {

      if $k == 1 {

         my $hi = min($B div $m, $max_p);
         $lo = max($lo, divceil($A, $m));

         my $t = $L - expmod($m, -1, $L);
         $t += $L while $t < $lo;
         return if $t > $hi;

         for $t, $t+$L ... $hi -> $p {
            if $p.is-prime {
               my $n = $m * $p;
               @LC.push($n) if ($n + 1) %% ($p + 1);
            }
         }
         return;
      }

      for $lo .. Int(($B div $m)**(1/$k)) -> $p {
         if $p.is-prime and ($m gcd ($p + 1)) == 1 {
            SUB($m * $p, ($L lcm ($p + 1)), $p + 1, $k - 1)
         }
      }
   };

   SUB(1, 1, 3, $k);

   return @LC.sort;
}

sub LC_with_n_primes ($n) {
   return if $n < 3;

   my $y = 2 * ( my $x = primorial($n + 1) +> 1);

   loop {
      my @LC = LC_in_range($x, $y, $n);
      return @LC[0] if @LC.Bool;
      $x = $y + 1;
      $y = 2 * $x;
   }
}

sub LC_count ($A, $B) {
   my $count = 0;
   for 3 .. Inf -> $k {
      last if primorial($k + 1) / 2 > $B;
      $count += LC_in_range($A, $B, $k).elems
   }
   return $count;
}

say "Least Lucas-Carmichael number with n prime factors:";

for 3 .. 12 -> $n { printf("%2d: %d\n", $n, LC_with_n_primes($n)) }

say "\nNumber of Lucas-Carmichael numbers less than 10^n:";

my $acc = 0;
for 1 .. 10 -> $n {
   my $c = LC_count(10**($n - 1), 10**$n);
   printf("%2d: %s\n", $n, $acc + $c);
   $acc += $c
}

```

Output is the same as Perl.


[User]
Lucas-Lehmer Test:

for

p
{\displaystyle {\displaystyle p}}
 an odd prime, the Mersenne number

2

p
−
1
{\displaystyle {\displaystyle 2^{p}-1}}
 is prime if and only if

2

p
−
1
{\displaystyle {\displaystyle 2^{p}-1}}
 divides

S
(
p
−
1
)
{\displaystyle {\displaystyle S(p-1)}}
 where

S
(
n
+
1
)
=
(
S
(
n
)

)

2
−
2
{\displaystyle {\displaystyle S(n+1)=(S(n))^{2}-2}}
, and

S
(
1
)
=
4
{\displaystyle {\displaystyle S(1)=4}}
.

Task

Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime   (whichever comes first).

[Assistant]
(formerly Perl 6)

```
multi is_mersenne_prime(2) { True }
multi is_mersenne_prime(Int $p) {
    my $m_p = 2 ** $p - 1;
    my $s = 4;
    $s = $s.expmod(2, $m_p) - 2 for 3 .. $p;
    !$s
}

.say for (2,3,5,7 … *).hyper(:8degree).grep( *.is-prime ).map: { next unless .&is_mersenne_prime; "M$_" };

```

On my system:

Letting it run for about a minute...

```
M2
M3
M5
M7
M13
M17
M19
M31
M61
M89
M107
M127
M521
M607
M1279
M2203
M2281
M3217
M4253
M4423
M9689
M9941
M11213
^C

real	0m55.527s
user	6m47.106s
sys	0m0.404s
```

Lightly modernized for better parallelization and run on a Ryzen 7950X with 16 cores. Followed examples set by Wren and Phix and didn't do an exhaustive search for larger Mersennes, just verified that known ones indeed were. Pure Raku. No external libraries.

```
multi is_mersenne_prime(2) { True }
multi is_mersenne_prime(Int $p) {
    my $m_p = 1 +< $p - 1;
    my $s = 4;
    $s = $s.expmod(2, $m_p) - 2 for 3 .. $p;
    !$s
}

# Exhaustive search for Mersenne primes up to 4600 - about half a second
my $start = now;
.say for (flat 2, (1..2300).map(* * 2 + 1)).hyper.map:
  { next unless .&is-prime && .&is_mersenne_prime; "M$_ {(now - $start).round(.001)} running total seconds" };

# Cheat and just verify Mersenne primes > 4600
.say for (9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503).hyper(:1batch).map:
  { next unless .&is_mersenne_prime; "M$_ {(now - $start).round(.001)} running total seconds" };

```

On my system, about 82 seconds:

```
M2 0.017 running total seconds
M3 0.018 running total seconds
M5 0.018 running total seconds
M7 0.019 running total seconds
M13 0.019 running total seconds
M17 0.019 running total seconds
M19 0.019 running total seconds
M31 0.019 running total seconds
M61 0.02 running total seconds
M89 0.021 running total seconds
M107 0.022 running total seconds
M127 0.022 running total seconds
M521 0.029 running total seconds
M607 0.039 running total seconds
M1279 0.084 running total seconds
M2203 0.096 running total seconds
M2281 0.164 running total seconds
M3217 0.173 running total seconds
M4253 0.336 running total seconds
M4423 0.457 running total seconds
M9689 0.868 running total seconds
M9941 0.878 running total seconds
M11213 0.953 running total seconds
M19937 1.828 running total seconds
M21701 2.054 running total seconds
M23209 2.324 running total seconds
M44497 9.186 running total seconds
M86243 46.836 running total seconds
M110503 81.91 running total seconds
```


[User]
Note that in the following explanation list indices are assumed to start at *one*.

Definition of lucky numbers

*Lucky numbers* are positive integers that are formed by:

1. Form a list of all the positive odd integers > 0

   1
   ,
   3
   ,
   5
   ,
   7
   ,
   9
   ,
   11
   ,
   13
   ,
   15
   ,
   17
   ,
   19
   ,
   21
   ,
   23
   ,
   25
   ,
   27
   ,
   29
   ,
   31
   ,
   33
   ,
   35
   ,
   37
   ,
   39...
   {\displaystyle {\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}}
2. Return the first number from the list (which is **1**).
3. (Loop begins here)
   * Note then return the second number from the list (which is **3**).
   * Discard every third, (as noted), number from the list to form the new list

     1
     ,
     3
     ,
     7
     ,
     9
     ,
     13
     ,
     15
     ,
     19
     ,
     21
     ,
     25
     ,
     27
     ,
     31
     ,
     33
     ,
     37
     ,
     39
     ,
     43
     ,
     45
     ,
     49
     ,
     51
     ,
     55
     ,
     57...
     {\displaystyle {\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}}
4. (Expanding the loop a few more times...)
   * Note then return the third number from the list (which is **7**).
   * Discard every 7th, (as noted), number from the list to form the new list

     1
     ,
     3
     ,
     7
     ,
     9
     ,
     13
     ,
     15
     ,
     21
     ,
     25
     ,
     27
     ,
     31
     ,
     33
     ,
     37
     ,
     43
     ,
     45
     ,
     49
     ,
     51
     ,
     55
     ,
     57
     ,
     63
     ,
     67...
     {\displaystyle {\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}}
   * Note then return the 4th number from the list (which is **9**).
   * Discard every 9th, (as noted), number from the list to form the new list

     1
     ,
     3
     ,
     7
     ,
     9
     ,
     13
     ,
     15
     ,
     21
     ,
     25
     ,
     31
     ,
     33
     ,
     37
     ,
     43
     ,
     45
     ,
     49
     ,
     51
     ,
     55
     ,
     63
     ,
     67
     ,
     69
     ,
     73...
     {\displaystyle {\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}}
   * Take the 5th, i.e. **13**. Remove every 13th.
   * Take the 6th, i.e. **15**. Remove every 15th.
   * Take the 7th, i.e. **21**. Remove every 21th.
   * Take the 8th, i.e. **25**. Remove every 25th.
5. (Rule for the loop)
   * Note the

     n
     {\displaystyle {\displaystyle n}}
     th, which is

     m
     {\displaystyle {\displaystyle m}}
     .
   * Remove every

     m
     {\displaystyle {\displaystyle m}}
     th.
   * Increment

     n
     {\displaystyle {\displaystyle n}}
     .

Definition of even lucky numbers

This follows the same rules as the definition of lucky numbers above *except for the very first step*:

1. Form a list of all the positive **even** integers > 0

   2
   ,
   4
   ,
   6
   ,
   8
   ,
   10
   ,
   12
   ,
   14
   ,
   16
   ,
   18
   ,
   20
   ,
   22
   ,
   24
   ,
   26
   ,
   28
   ,
   30
   ,
   32
   ,
   34
   ,
   36
   ,
   38
   ,
   40...
   {\displaystyle {\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}}
2. Return the first number from the list (which is **2**).
3. (Loop begins here)
   * Note then return the second number from the list (which is **4**).
   * Discard every 4th, (as noted), number from the list to form the new list

     2
     ,
     4
     ,
     6
     ,
     10
     ,
     12
     ,
     14
     ,
     18
     ,
     20
     ,
     22
     ,
     26
     ,
     28
     ,
     30
     ,
     34
     ,
     36
     ,
     38
     ,
     42
     ,
     44
     ,
     46
     ,
     50
     ,
     52...
     {\displaystyle {\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}}
4. (Expanding the loop a few more times...)
   * Note then return the third number from the list (which is **6**).
   * Discard every 6th, (as noted), number from the list to form the new list

     2
     ,
     4
     ,
     6
     ,
     10
     ,
     12
     ,
     18
     ,
     20
     ,
     22
     ,
     26
     ,
     28
     ,
     34
     ,
     36
     ,
     38
     ,
     42
     ,
     44
     ,
     50
     ,
     52
     ,
     54
     ,
     58
     ,
     60...
     {\displaystyle {\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}}
   * Take the 4th, i.e. **10**. Remove every 10th.
   * Take the 5th, i.e. **12**. Remove every 12th.
5. (Rule for the loop)
   * Note the

     n
     {\displaystyle {\displaystyle n}}
     th, which is

     m
     {\displaystyle {\displaystyle m}}
     .
   * Remove every

     m
     {\displaystyle {\displaystyle m}}
     th.
   * Increment

     n
     {\displaystyle {\displaystyle n}}
     .

Task requirements

* Write one or two subroutines (functions) to generate *lucky numbers* and *even lucky numbers*
* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
  + missing arguments
  + too many arguments
  + number (or numbers) aren't legal
  + misspelled argument (**lucky** or **evenLucky**)
* The command line handling should:
  + support mixed case handling of the (non-numeric) arguments
  + support printing a particular number
  + support printing a range of numbers by their index
  + support printing a range of numbers by their values
* The resulting list of numbers should be printed on a single line.

The program should support the arguments:

```
                             what is displayed  (on a single line)
       argument(s)              (optional verbiage is encouraged)
  ╔═══════════════════╦════════════════════════════════════════════════════╗
  ║  j                ║  Jth       lucky number                            ║
  ║  j  ,      lucky  ║  Jth       lucky number                            ║
  ║  j  ,  evenLucky  ║  Jth  even lucky number                            ║
  ║                   ║                                                    ║
  ║  j  k             ║  Jth  through  Kth (inclusive)       lucky numbers ║
  ║  j  k      lucky  ║  Jth  through  Kth (inclusive)       lucky numbers ║
  ║  j  k  evenLucky  ║  Jth  through  Kth (inclusive)  even lucky numbers ║
  ║                   ║                                                    ║
  ║  j -k             ║  all       lucky numbers in the range  j ──► |k|   ║
  ║  j -k      lucky  ║  all       lucky numbers in the range  j ──► |k|   ║
  ║  j -k  evenLucky  ║  all  even lucky numbers in the range  j ──► |k|   ║
  ╚═══════════════════╩════════════════════════════════════════════════════╝
                           where    |k|    is the absolute value of   k

```

Demonstrate the program by:

* showing the first twenty *lucky* numbers
* showing the first twenty *even lucky* numbers
* showing all *lucky* numbers between 6,000 and 6,100 (inclusive)
* showing all *even lucky* numbers in the same range as above
* showing the 10,000th *lucky* number (extra credit)
* showing the 10,000th *even lucky* number (extra credit)

See also

* This task is related to the Sieve of Eratosthenes task.
* OEIS Wiki Lucky numbers.
* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
* Entry lucky numbers on The Eric Weisstein's World of Mathematics.

[Assistant]
(formerly Perl 6)

```
sub luck(\a,\b) {
    gather {
	my @taken = take a;
	my @rotor;
	my $i = b;

	loop {
	    loop (my $j = 0; $j < @rotor; $j++) {
		--@rotor[$j] or last;
	    }
	    if $j < @rotor {
		@rotor[$j] = @taken[$j+1];
	    }
	    else {
		push @taken, take $i;
		push @rotor, $i - @taken;
	    }
	    $i += 2;
	}
    }
}

constant @lucky = luck(1,3);
constant @evenlucky = luck(2,4);

subset Luck where m:i/^ 'even'? 'lucky' $/;

multi MAIN (Int $num where * > 0) {
    say @lucky[$num-1];
}

multi MAIN (Int $num where * > 0, ',', Luck $howlucky = 'lucky') {
    say @::(lc $howlucky)[$num-1];
}

multi MAIN (Int $first where * > 0, Int $last where * > 0, Luck $howlucky = 'lucky') {
    say @::(lc $howlucky)[$first-1 .. $last - 1];
}

multi MAIN (Int $min where * > 0, Int $neg-max where * < 0, Luck $howlucky = 'lucky') {
    say grep * >= $min, (@::(lc $howlucky) ...^ * > abs $neg-max);
}

```

Output:

```
$ ./lucky
Usage:
  ./lucky <num>
  ./lucky <num> , [<howlucky>]
  ./lucky <first> <last> [<howlucky>]
  ./lucky <min> <neg-max> [<howlucky>]
$ ./lucky 20 , lucky
79
$ ./lucky 20 , evenlucky
76
$ ./lucky 1 20
1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79
$ ./lucky 1 20 evenlucky
2 4 6 10 12 18 20 22 26 34 36 42 44 50 52 54 58 68 70 76
$ ./lucky 6000 -6100
6009 6019 6031 6049 6055 6061 6079 6093
$ ./lucky 6000 -6100 evenLucky
6018 6020 6022 6026 6036 6038 6050 6058 6074 6090 6092
$ ./lucky 10000
115591
$ ./lucky 10000 , EVENLUCKY
111842
```


[User]
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.

The first ludic number is   1.

To generate succeeding ludic numbers create an array of increasing integers starting from   2.

:   `2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...`

(Loop)

* Take the first member of the resultant array as the next ludic number   2.
* Remove every   **2nd**   indexed item from the array (including the first).

:   :   `2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...`

* (Unrolling a few loops...)
* Take the first member of the resultant array as the next ludic number   3.
* Remove every   **3rd**   indexed item from the array (including the first).

:   :   `3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...`

* Take the first member of the resultant array as the next ludic number   5.
* Remove every   **5th**   indexed item from the array (including the first).

:   :   `5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...`

* Take the first member of the resultant array as the next ludic number   7.
* Remove every   **7th**   indexed item from the array (including the first).

:   :   `7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...`

* **...**
* Take the first member of the current array as the next ludic number   L.
* Remove every   **Lth**   indexed item from the array (including the first).
* **...**

Task

* Generate and show here the first 25 ludic numbers.
* How many ludic numbers are there less than or equal to 1000?
* Show the 2000..2005th ludic numbers.

Stretch goal

Show all triplets of ludic numbers < 250.

* A triplet is any three numbers

  x
  ,
  {\displaystyle {\displaystyle x,}}

  x
  +
  2
  ,
  {\displaystyle {\displaystyle x+2,}}

  x
  +
  6
  {\displaystyle {\displaystyle x+6}}
        where all three numbers are also ludic numbers.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-09-18

This implementation has no arbitrary upper limit, since it can keep adding new rotors on the fly. It just gets slower and slower instead... :-)

```
constant @ludic = gather {
        my @taken = take 1;
        my @rotor;

        for 2..* -> $i {
            loop (my $j = 0; $j < @rotor; $j++) {
                --@rotor[$j] or last;
            }
            if $j < @rotor {
                @rotor[$j] = @taken[$j+1];
            }
            else {
                push @taken, take $i;
                push @rotor, @taken[$j+1];
            }
        }
    }

say @ludic[^25];
say "Number of Ludic numbers <= 1000: ", +(@ludic ...^ * > 1000);
say "Ludic numbers 2000..2005: ", @ludic[1999..2004];

my \l250 = set @ludic ...^ * > 250;
say "Ludic triples < 250: ", gather
    for l250.keys.sort -> $a {
        my $b = $a + 2;
        my $c = $a + 6;
        take "<$a $b $c>" if $b ∈ l250 and $c ∈ l250;
    }

```

Output:

```
(1 2 3 5 7 11 13 17 23 25 29 37 41 43 47 53 61 67 71 77 83 89 91 97 107)
Number of Ludic numbers <= 1000: 142
Ludic numbers 2000..2005: (21475 21481 21487 21493 21503 21511)
Ludic triples < 250: (<1 3 7> <5 7 11> <11 13 17> <23 25 29> <41 43 47> <173 175 179> <221 223 227> <233 235 239>)
```


[User]
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.

Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:

1. Reverse the order of the digits in the number.
2. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
3. Taking the second, fourth ... and every other even digit in the reversed digits:

:   1. Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
    2. Sum the partial sums of the even digits to form s2

1. If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.

For example, if the trial number is 49927398716:

```
Reverse the digits:
  61789372994
Sum the odd digits:
  6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
    1,  8,  3,  2,  9
  Two times each even digit:
    2, 16,  6,  4, 18
  Sum the digits of each multiplication:
    2,  7,  6,  4,  9
  Sum the last:
    2 + 7 + 6 + 4 + 9 = 28 = s2

s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
```

Task

Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and

use it to validate the following numbers:

```
   49927398716
   49927398717
   1234567812345678
   1234567812345670

```

Related tasks

* SEDOL
* ISIN

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-11-29

Here we make use of comb, which splits into individual characters,
and the sequence operator ..., which can intuit an even or odd sequence from the first two values.
%% is the divisible-by operator.

```
sub luhn-test ($number --> Bool) {
    my @digits = $number.comb.reverse;
    my $sum = @digits[0,2...*].sum
            + @digits[1,3...*].map({ |($_ * 2).comb }).sum;
    return $sum %% 10;
}

# And we can test it like this:

use Test;

my @cc-numbers =
    '49927398716'       => True,
    '49927398717'       => False,
    '1234567812345678'  => False,
    '1234567812345670'  => True;

plan @cc-numbers.elems;

for @cc-numbers».kv -> ($cc, $expected-result) {
    is luhn-test(+$cc), $expected-result,
        "$cc {$expected-result ?? 'passes' !! 'does not pass'} the Luhn test.";
}
```

Output:

```
1..4
ok 1 - 49927398716 passes the Luhn test.
ok 2 - 49927398717 does not pass the Luhn test.
ok 3 - 1234567812345678 does not pass the Luhn test.
ok 4 - 1234567812345670 passes the Luhn test.
```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Lunar arithmetic. 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) |

**Lunar arithmetic** is a version of arithmetic in which the addition and multiplication on digits are defined as the max and min operations. Thus, in lunar arithmetic,

:   2
    +
    7
    =
    max
    {
    2
    ,
    7
    }
    =
    7
    {\displaystyle {\displaystyle 2+7=\max\{2,7\}=7}}
     and

    2
    ×
    7
    =
    min
    {
    2
    ,
    7
    }
    =
    2.
    {\displaystyle {\displaystyle 2\times 7=\min\{2,7\}=2.}}

The lunar arithmetic operations on nonnegative multidigit numbers are performed as in usual arithmetic as illustrated in the following examples. The world of lunar arithmetic is restricted to the set of nonnegative integers.

```
 976 +
 348
 ----
 978 (adding digits column-wise)

```

```
    976 ×
    348
   ----
   876 (multiplying the digits of 976 by 8)
  444  (multiplying the digits of 976 by 4)
 333   (multiplying the digits of 976 by 3)
 ------
 34876 (adding digits column-wise)

```

**A few important properties of lunar arithmetic**

1. The lunar addition and multiplication operations satisfy the Commutative and Associative property laws.
2. The lunar multiplication distributes over the lunar addition.
3. The digit 0 is the additive identity under lunar addition.
4. The digit 9 is the multiplicative identity under lunar multiplication.

Note that lunar arithmetic can be done in any base. This task is restricted to base 10 only.

Task

Implement lunar addition and lunar multiplication routines. Extra kudos for implementing them as operators.

Use those routines (operators) to perform the following:

* Lunar addition and lunar multiplication of the number groups: (976, 348), (23, 321), (232, 35), (123, 32192, 415, 8)
* Using lunar arithmetic, find the first twenty *distinct* even numbers.

  n
  +
  n
  ≠
  2
  ×
  n
  {\displaystyle {\displaystyle n+n\neq 2\times n}}
   and

  n
  +
  n
  =
  n
  {\displaystyle {\displaystyle n+n=n}}
  . The even numbers are numbers of the form

  2
  ×
  n
  {\displaystyle {\displaystyle 2\times n}}
  .
* Using lunar arithmetic, find the first twenty square numbers.

  n
  ×
  n
  {\displaystyle {\displaystyle n\times n}}
* Using lunar arithmetic, find the first twenty factorial numbers.

  n
  !
  =
  1
  ×
  2
  ×
  ⋯
  ×
  n
  {\displaystyle {\displaystyle n!=1\times 2\times \cdots \times n}}

Stretch

The lunar squares sequence is not monotonic. Squared values are not strictly increasing as the numbers grow larger.

* Find the first number whose lunar square is smaller than the previous.

See also
:   OEIS A087019 - Lunar squares
:   OEIS A189788 - Base-10 lunar factorials
:   Tropical algebra overloading

[Assistant]
That's not a banana. That's a crescent moon.

```
# The operators
sub infix:<🌙+> ($a, $b = 0) { # addition
    +([Zmax] ('0'x$b.chars~$a).comb,('0'x$a.chars~$b).comb).join;
}

sub infix:<🌙×> ($a, $b = 9) { # multiplication
    [🌙+] $b.flip.comb.kv.map: -> $k,$v {$a.comb.map(* min $v).join ~ '0'x$k}
}

# The task
for (976, 348), (23, 321), (232, 35), (123, 32192, 415, 8) {
    say '     Lunar add: ' ~ (.join: ' 🌙+ ') ~ ' == ' ~ (.join: ' 🌙+ ').EVAL;
    say 'Lunar multiply: ' ~ (.join: ' 🌙× ') ~ ' == ' ~ (.join: ' 🌙× ').EVAL;
    say '';
}

say "First 20 distinct lunar even numbers:\n" ~ (^Inf).map(* 🌙× 2).unique[^20];
say "\nFirst 20 lunar square numbers:\n"      ~ (my @squares = (^Inf).map:{$_ 🌙× $_})[^20];
say "\nFirst 20 lunar factorial numbers:\n"   ~ (1..*).map({[🌙×] 1..$_})[^20];

# Stretch
say "\nFirst number whose lunar square is smaller than the previous: " ~
(1..Inf).first: {@squares[$_ - 1] > @squares[$_]};

```

Output:

```
     Lunar add: 976 🌙+ 348 == 978
Lunar multiply: 976 🌙× 348 == 34876

     Lunar add: 23 🌙+ 321 == 323
Lunar multiply: 23 🌙× 321 == 2321

     Lunar add: 232 🌙+ 35 == 235
Lunar multiply: 232 🌙× 35 == 2332

     Lunar add: 123 🌙+ 32192 🌙+ 415 🌙+ 8 == 32498
Lunar multiply: 123 🌙× 32192 🌙× 415 🌙× 8 == 123233232

First 20 distinct lunar even numbers:
0 1 2 10 11 12 20 21 22 100 101 102 110 111 112 120 121 122 200 201

First 20 lunar square numbers:
0 1 2 3 4 5 6 7 8 9 100 111 112 113 114 115 116 117 118 119

First 20 lunar factorial numbers:
1 1 1 1 1 1 1 1 1 10 110 1110 11110 111110 1111110 11111110 111111110 1111111110 11111111110 111111111100

First number whose lunar square is smaller than the previous: 1020
```


[User]
:   :   1. Take an integer n, greater than zero.
        2. Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
        3. Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.

The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.

Example

If n0 = 12 we get

```
       12
       12 +  21 =  33,   a palindrome!

```

And if n0 = 55 we get

```
       55
       55 +  55 = 110
      110 + 011 = 121,   a palindrome!

```

Notice that the check for a palindrome happens   *after*   an addition.

Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.

These numbers that do not end in a palindrome are called **Lychrel numbers**.

For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.

Seed and related Lychrel numbers

Any integer produced in the sequence of a Lychrel number is also a Lychrel number.

In general, any sequence from one Lychrel number *might* converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:

```
        196
        196 +    691 =   887
        887 +    788 =  1675
       1675 +   5761 =  7436
       7436 +   6347 = 13783
      13783 +  38731 = 52514
      52514 +  41525 = 94039
       ...

        689
        689 +    986 =  1675
       1675 +   5761 =  7436
       ...

```

So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.

Because of this we can further split the Lychrel numbers into true **Seed** Lychrel number candidates, and **Related** numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.

Task

* Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
* Print the number of seed Lychrels found; the actual seed Lychrels; and just the *number* of relateds found.
* Print any seed Lychrel or related number that is itself a palindrome.

Show all output here.

References

* What's special about 196? Numberphile video.
* A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
* Status of the 196 conjecture? Mathoverflow.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

```
my %lychrels;
my @seeds;
my @palindromes;
my $count;
my $max = 500;
my $limit = '10_000';
my %seen;

for 1 .. $limit -> $int {
    my @test;
    my $index = 0;
    if $int.&is-lychrel {
        %lychrels.push: ($int => @test).invert;
        @palindromes.push: $int if $int == $int.flip;
        $count++;
    }

    sub is-lychrel (Int $l) {
        if  %seen{$l} or $index++ > $max {
            %seen{$_} = True for @test;
            return True;
        }
        @test.push: my $m = $l + $l.flip;
        return False if $m == $m.flip;
        $m.&is-lychrel;
    }
}

for %lychrels{*}»[0].unique.sort -> $ly {
    my $next = False;
    for %lychrels -> $l {
        for $l.value[1..*] -> $lt {
            $next = True and last if $ly == $lt;
            last if $ly < $lt;
        }
        last if $next;
    }
    next if $next;
    @seeds.push: $ly;
}

say "   Number of Lychrel seed numbers < $limit: ", +@seeds;
say "             Lychrel seed numbers < $limit: ", join ", ", @seeds;
say "Number of Lychrel related numbers < $limit: ", +$count - @seeds;
say "    Number of Lychrel palindromes < $limit: ", +@palindromes;
say "              Lychrel palindromes < $limit: ", join ", ", @palindromes;

```

Output:

```
   Number of Lychrel seed numbers < 10_000: 5
             Lychrel seed numbers < 10_000: 196, 879, 1997, 7059, 9999
Number of Lychrel related numbers < 10_000: 244
    Number of Lychrel palindromes < 10_000: 3
              Lychrel palindromes < 10_000: 4994, 8778, 9999
```


[User]
Given a finite alphabet, we can lexicographically order all strings in the alphabet. If two strings have different lengths, then pad the shorter string on the right with the smallest letter. For example, we have 01 > 001, but 01 = 010. As we see, this order is a total preorder, but not a total order, since it identifies different strings.

A Lyndon word is a non-empty string that is *strictly* lower in lexicographic order than all its circular rotations. In particular, if a string is equal to a circular rotation, then it is not a Lyndon word. For example, since 0101 = 0101 (rotation by 2), it is not a Lyndon word.

The first Lyndon words on the binary alphabet {0, 1} are:

:   0, 1, 01, 001, 011, 0001, 0011, 0111, 00001, 00011, 00101, 00111, 01011, 01111, ...

**Task:** Given a positive number

n
{\displaystyle {\displaystyle n}}
 and an ordered list of alphabet, list all Lyndon words of length at most

n
{\displaystyle {\displaystyle n}}
, in the lexicographic order.

Duval (1988) provides an efficient algorithm. If

w
{\displaystyle {\displaystyle w}}
 is one of the words in the sequence, then the next word after

w
{\displaystyle {\displaystyle w}}
 can be found by the following steps:

1. Repeat

   w
   {\displaystyle {\displaystyle w}}
    and truncate it to a new word

   x
   {\displaystyle {\displaystyle x}}
    of length exactly

   n
   {\displaystyle {\displaystyle n}}
   .
2. As long as the final symbol of

   x
   {\displaystyle {\displaystyle x}}
    is the last symbol in the sorted ordering of the alphabet, remove it, producing a shorter word.
3. Replace the final remaining symbol of

   x
   {\displaystyle {\displaystyle x}}
    by its successor in the sorted ordering of the alphabet.

For example, suppose we have generated the binary Lyndon words of length up to 7, and we have generated up to

w
=
00111
{\displaystyle {\displaystyle w=00111}}
, then the steps are:

1. Repeat and truncate to get

   x
   =
   00111

   00

   111
   {\displaystyle {\displaystyle x=00111\;00{\cancel {111}}}}
2. Since the last symbol is 0, it is not the final symbol.
3. Increment the last symbol to obtain

   x
   =
   00111

   01
   {\displaystyle {\displaystyle x=00111\;01}}
   .

[Assistant]
**Translation of**: Julia

```
# 20240211 Raku programming solution

sub nextword($n, $w, $alphabet) {
   my $x = ($w x ($n div $w.chars + 1)).substr(0, $n);
   while $x.Bool && $x.substr(*-1) eq $alphabet.substr(*-1) {
      $x.substr-rw(*-1) = ''
   }
   if $x.Bool {
      my $next_char_index  = ($alphabet.index($x.substr(*-1)) // 0) + 1;
      $x.substr-rw(*-1, 1) = $alphabet.substr($next_char_index, 1);
   }
   return $x;
}

.say for sub ($n, $alphabet) {
   my $w = $alphabet.substr(0, 1);
   return gather while $w.chars <= $n {
      take $w;
      last unless $w = nextword($n, $w, $alphabet);
   }
}(5, '01');

```

Output:

Same as Julia example.

You may Attempt This Online!


[User]
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.

You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.

[Assistant]
(formerly Perl 6) I just came across this SO question by chance hence the update. Notably the ancestor Perl entry simply works without any further tweak.

**Translation of**: Perl

```
# 20200421 Updated Raku programming solution ; add unicode support

sub compress(Str $uncompressed --> Seq)  {
    my $dict-size = 256;
    my %dictionary = (.chr => .chr for ^$dict-size);

    my $w = "";
    gather {
  for $uncompressed.encode('utf8').list.chrs.comb -> $c {
      my $wc = $w ~ $c;
      if %dictionary{$wc}:exists { $w = $wc }
      else {
    take %dictionary{$w};
    %dictionary{$wc} = +%dictionary;
    $w = $c;
      }
  }

  take %dictionary{$w} if $w.chars;
    }
}

sub decompress(@compressed --> Str) {
    my $dict-size = 256;
    my %dictionary = (.chr => .chr for ^$dict-size);

    my $w = shift @compressed;
    ( Blob.new: flat ( gather {
  take $w;
  for @compressed -> $k {
      my $entry;
      if %dictionary{$k}:exists { take $entry = %dictionary{$k} }
      elsif $k == $dict-size    { take $entry = $w ~ $w.substr(0,1) }
      else                      { die "Bad compressed k: $k" }

      %dictionary{$dict-size++} = $w ~ $entry.substr(0,1);
      $w = $entry;
  }
    }  )».ords ).decode('utf-8')
}

say my @compressed = compress('TOBEORNOTTOBEORTOBEORNOT');
say decompress(@compressed);

@compressed = compress('こんにちは𝒳𝒴𝒵こんにちは𝒳𝒴𝒵こんにちは𝒳𝒴𝒵');
say decompress(@compressed);

```

Output:

```
[T O B E O R N O T 256 258 260 265 259 261 263]
TOBEORNOTTOBEORTOBEORNOT
こんにちは𝒳𝒴𝒵こんにちは𝒳𝒴𝒵こんにちは𝒳𝒴𝒵

```


[User]
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address.

A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.

Task

Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.

A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result.

Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.

**{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}**

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

Apparently there is some rate limiting on place now, sleep a bit between requests.

```
use HTTP::UserAgent;

my $ua = HTTP::UserAgent.new;

$ua.timeout = 10; # seconds

my $server = 'http://api.macvendors.com/';

sub lookup ($mac) {
    my $response = $ua.get: "$server+$mac";
    sleep 1;
    return $response.is-success ?? $response.content !! 'N/A';

    CATCH {             # Normally you would report some information about what
        default { Nil } # went wrong, but the task specifies to ignore errors.
    }
}

for <
BC:5F:F4
FC-A1-3E
10:dd:b1
00:0d:4b
23:45:67
> -> $mac { say lookup $mac }

```

Output:

```
ASRock Incorporation
Samsung Electronics Co.,Ltd
Apple, Inc.
Roku, Inc.
N/A

```


[User]
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.

For example, the following assembly language program is given for x86 (32 bit) architectures:

```
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret

```

This would translate into the following opcode bytes:

```
139 68 36 4 3 68 36 8 195

```

Or in hexadecimal:

```
8B 44 24 04 03 44 24 08 C3

```

Task

If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:

* Poke the necessary opcodes into a memory location.
* Provide a means to pass two values to the machine code.
* Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
* Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)

[Assistant]
I don't know how to translate this C line

```
c = ((int (*) (int, int))buf)(a, b);

```

so cannot solve the task with an idiomatic solution. I have also tried with Go's approach by adding a helper program but it also doesn't work out. Nonetheless I just present the attempt here so perhaps someone can fix that in 10 seconds.

```
use NativeCall;

constant PROT_READ   = 0x1;   #
constant PROT_WRITE  = 0x2;   #
constant PROT_EXEC   = 0x4;   # from local /usr/include/bits/mman.h
constant MAP_PRIVATE = 0x02;  #
constant MAP_ANON    = 0x20;  #

sub mmap(Pointer $addr, size_t $length, int32 $prot, int32 $flags,
   int32 $fd, size_t $offset --> Pointer) is native { * };
sub memcpy(Pointer $dest, Pointer $src, size_t $size --> Pointer) is native {*}
sub munmap(Pointer $addr, size_t $length) is native { * };

sub test (uint8 $a, uint8 $b) {
   my $code = CArray[uint8].new(
      0x90, 0x90, 0x6A, 0xC, 0xB8, 0x7, 0x0, 0x0, 0x0, 0x48, 0xC1, 0xE0, 0x20,
      0x50, 0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0x4C, 0x89, 0xE3, 0x89,
      0xC3, 0x48, 0xC1, 0xE3, 0x4, 0x80, 0xCB, 0x2, 0x48, 0x83, 0xC4, 0x10, 0xC3
   );
   my $buf =
      mmap(Pointer, nativesizeof($code), PROT_READ +| PROT_WRITE +| PROT_EXEC,
      MAP_PRIVATE +| MAP_ANON, -1, 0);

   memcpy($buf, nativecast(Pointer,$code), nativesizeof($code));

   my $c; # = ((int (*) (int, int))buf)(a, b);

   munmap($buf, nativesizeof($code));

   return $c = "Incomplete Attempt";
}

say test 7, 12;

```

In the mean time, here is a less desirable approach by writing a wrapper for the C entry, with the 64 bit instructions from PicoLisp ..

**Translation of**: C

test.c

```
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>

int test (int a, int b)
{
  char code[] = {
     0x90, 0x90, 0x6A, 0xC, 0xB8, 0x7, 0x0, 0x0, 0x0, 0x48, 0xC1, 0xE0, 0x20,
     0x50, 0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0x4C, 0x89, 0xE3, 0x89,
     0xC3, 0x48, 0xC1, 0xE3, 0x4, 0x80, 0xCB, 0x2, 0x48, 0x83, 0xC4, 0x10, 0xC3
  };

  void *buf;
  int c;
  /* copy code to executable buffer */
  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
             MAP_PRIVATE|MAP_ANON,-1,0);
  memcpy (buf, code, sizeof(code));
  /* run code */
  c = ((int (*) (int, int))buf)(a, b);
  /* free buffer */
  munmap (buf, sizeof(code));
  return c;
}

```

mcode.raku

```
#!/usr/bin/env raku

# 20200501 Raku programming solution

use NativeCall;

constant LIBTEST = '/home/user/LibTest.so';

sub test(uint8 $a, uint8 $b) returns uint8 is native(LIBTEST) { * };

say test 7, 12;

```

Output:

```
gcc -Wall -fPIC -shared -o LibTest.so test.c

file LibTest.so
LibTest.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=90d2695df9a56b88a57144147fb9288ac07b172f, not stripped
./mcode.raku

19
```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Mad Libs. 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) |

Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.

Task;

Write a program to create a Mad Libs like story.

The program should read an arbitrary multiline story from input.

The story will be terminated with a blank line.

Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.

Stop when there are none left and print the final story.

The input should be an arbitrary story in the form:

```
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.

```

Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).

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)

**Works with**: rakudo version 2015-09-18

Some explanation: S:g[...] = ... is a global substitution that returns its result. % is an anonymous state variable in which we cache any results of a prompt using the //= operator, which assigns only if the left side is undefined. slurp reads an entire file from STDIN or as named in the argument list.

```
print S:g[ '<' (.*?) '>' ] = %.{$0} //= prompt "$0? " given slurp;

```

Sample run:

```
$ madlibs walk
name? Phydeaux
He or She? She
noun? flea
Phydeaux went for a walk in the park. She
found a flea. Phydeaux decided to take it home.
```


[User]
Task

Create Magic 8-Ball.

See details at:   Magic 8-Ball.

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)

**Works with**: Rakudo version 2018.03

```
put 'Please enter your question or a blank line to quit.';

["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely",
 "You may rely on it", "As I see it, yes", "Most likely", "Outlook good",
 "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later",
 "Better not tell you now", "Cannot predict now", "Concentrate and ask again",
 "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good",
 "Very doubtful"].roll.put while prompt('? : ').chars;

```

Output very similar to C, Kotlin and zkl examples.


[User]
A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant.

EG

A 3 x 3 magic square *always* sums to 15.

```
    ┌───┬───┬───┐
    │ 2 │ 7 │ 6 │
    ├───┼───┼───┤
    │ 9 │ 5 │ 1 │
    ├───┼───┼───┤
    │ 4 │ 3 │ 8 │
    └───┴───┴───┘
```

A 4 x 4 magic square *always* sums to 34.

Traditionally, the sequence leaves off terms for n = 0 and n = 1 as the magic squares of order 0 and 1 are trivial; and a term for n = 2 because it is impossible to form a magic square of order 2.

Task

* Starting at order 3, show the first 20 magic constants.
* Show the 1000th magic constant. (Order 1003)
* Find and show the order of the smallest N x N magic square whose constant is greater than 10¹ through 10¹⁰.

Stretch

* Find and show the order of the smallest N x N magic square whose constant is greater than 10¹¹ through 10²⁰.

See also

* Wikipedia: Magic constant
* OEIS: A006003 (Similar sequence, though it includes terms for 0, 1 & 2.)
* Magic squares of odd order
* Magic squares of singly even order
* Magic squares of doubly even order

[Assistant]
```
use Lingua::EN::Numbers:ver<2.8+>;

my @magic-constants = lazy (3..∞).hyper.map: { (1 + .²) * $_ / 2 };

put "First 20 magic constants: ", @magic-constants[^20]».,
say "1000th magic constant: ", @magic-constants[999].,
say "\nSmallest order magic square with a constant greater than:";

(1..20).map: -> $p {printf "10%-2s: %s\n", $p.&super, comma 3 + @magic-constants.first( * > exp($p, 10), :k ) }

```

Output:

```
First 20 magic constants: 15 34 65 111 175 260 369 505 671 870 1,105 1,379 1,695 2,056 2,465 2,925 3,439 4,010 4,641 5,335
1000th magic constant: 503,006,505

Smallest order magic square with a constant greater than:
10¹ : 3
10² : 6
10³ : 13
10⁴ : 28
10⁵ : 59
10⁶ : 126
10⁷ : 272
10⁸ : 585
10⁹ : 1,260
10¹⁰: 2,715
10¹¹: 5,849
10¹²: 12,600
10¹³: 27,145
10¹⁴: 58,481
10¹⁵: 125,993
10¹⁶: 271,442
10¹⁷: 584,804
10¹⁸: 1,259,922
10¹⁹: 2,714,418
10²⁰: 5,848,036
```


[User]
Magic numbers are polydivisible numbers in base 10. A polydivisible number is an **m** digit number where the first **n** digits are evenly divisible by **n** for all **n** from **1** to **m**.

E.G. The number **1868587** is a magic number (is polydivisible in base 10.)

```
      1 ÷ 1 = 1
     18 ÷ 2 = 9
    186 ÷ 3 = 62
   1868 ÷ 4 = 467
  18685 ÷ 5 = 3737
 186858 ÷ 6 = 31143
1868587 ÷ 7 = 266941
```

There is a finite number of magic numbers.

Task

* Write a routine (subroutine, function, procedure, generator, whatever it may be called in your language) to find magic numbers.
* Use that routine to find and display how many magic numbers exist.
* Use that routine to find and display the largest possible magic number.
* Count and display how many magic numbers have 1 digit, 2 digits, 3 digits, ... for all magic numbers.
* Find and display all of the magic numbers that are minimally pandigital in **1** through **9**. (Contains each digit but only once.)
* Find and display all of the magic numbers that are minimally pandigital in **0** through **9**.

*Zero (0) may or may not be included as a magic number. For this task, include zero.*

See also

* Wikipedia: Polydivisible numbers * OEIS:A144688 - "Magic" numbers * OEIS:A143671 - Count of "Magic" numbers with n digits

[Assistant]
```
my \Δ = $ = 1;
my @magic = flat 0, [1..9], {last if .not; ++Δ; [(.flat X~ 0..9).grep: * %% Δ]}…*;

put "There are {@magic.eager.elems} magic numbers in total.";
put "\nThe largest is {@magic.tail}.";
put "\nThere are:";
put "{(+.value).fmt: "%4d"} with {.key.fmt: "%2d"} digit{1 == +.key ?? '' !! 's'}"
    for sort @magic.classify: {.chars};
{
    my $pan-digital = ($_..9).join.comb.Bag;
    put "\nAll magic numbers that are pan-digital in $_ through 9 with no repeats: " ~
    @magic.grep( { .comb.Bag eqv $pan-digital } );
} for 1, 0;

```

Output:

```
There are 20457 magic numbers in total.

The largest is 3608528850368400786036725.

There are:
  10 with  1 digit
  45 with  2 digits
 150 with  3 digits
 375 with  4 digits
 750 with  5 digits
1200 with  6 digits
1713 with  7 digits
2227 with  8 digits
2492 with  9 digits
2492 with 10 digits
2225 with 11 digits
2041 with 12 digits
1575 with 13 digits
1132 with 14 digits
 770 with 15 digits
 571 with 16 digits
 335 with 17 digits
 180 with 18 digits
  90 with 19 digits
  44 with 20 digits
  18 with 21 digits
  12 with 22 digits
   6 with 23 digits
   3 with 24 digits
   1 with 25 digits

All magic numbers that are pan-digital in 1 through 9 with no repeats: 381654729

All magic numbers that are pan-digital in 0 through 9 with no repeats: 3816547290
```


[User]
A magic square is an   **N×N**  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   *and*   both diagonals are equal to the same sum   (which is called the *magic number* or *magic constant*).

A magic square of doubly even order has a size that is a multiple of four   (e.g.     **4**, **8**, **12**).

This means that the subsquares also have an even size, which plays a role in the construction.

|  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **1** | **2** | **62** | **61** | **60** | **59** | **7** | **8** |
| **9** | **10** | **54** | **53** | **52** | **51** | **15** | **16** |
| **48** | **47** | **19** | **20** | **21** | **22** | **42** | **41** |
| **40** | **39** | **27** | **28** | **29** | **30** | **34** | **33** |
| **32** | **31** | **35** | **36** | **37** | **38** | **26** | **25** |
| **24** | **23** | **43** | **44** | **45** | **46** | **18** | **17** |
| **49** | **50** | **14** | **13** | **12** | **11** | **55** | **56** |
| **57** | **58** | **6** | **5** | **4** | **3** | **63** | **64** |

Task

Create a magic square of   **8 × 8**.

Related tasks

* Magic squares of odd order
* Magic squares of singly even order

See also

* Doubly Even Magic Squares (1728.org)

[Assistant]
(formerly Perl 6)

See Magic squares/Raku for a general magic square generator.

Output:

With a parameter of 8:

```
 1  2 62 61 60 59  7  8
 9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58  6  5  4  3 63 64

The magic number is 260
```

With a parameter of 12:

```
  1   2   3 141 140 139 138 137 136  10  11  12
 13  14  15 129 128 127 126 125 124  22  23  24
 25  26  27 117 116 115 114 113 112  34  35  36
108 107 106  40  41  42  43  44  45  99  98  97
 96  95  94  52  53  54  55  56  57  87  86  85
 84  83  82  64  65  66  67  68  69  75  74  73
 72  71  70  76  77  78  79  80  81  63  62  61
 60  59  58  88  89  90  91  92  93  51  50  49
 48  47  46 100 101 102 103 104 105  39  38  37
109 110 111  33  32  31  30  29  28 118 119 120
121 122 123  21  20  19  18  17  16 130 131 132
133 134 135   9   8   7   6   5   4 142 143 144

The magic number is 870
```