[User]
The task is to implement the Lagrange Interpolation formula and use it to solve the example problem to find a polynomial
P of degree<4 satisfying P(1)=1 P(2)=4 P(3)=1 P(4)=5 as described at https://brilliant.org/wiki/lagrange-interpolation
or https://en.wikipedia.org/wiki/Lagrange\_polynomial

Related task Curve that touches three points

[Assistant]
**Translation of**: Wren

```
# 20231020 Raku programming solution

class Point { has Rat ($.x, $.y) }

sub add(@p1, @p2) { return @p1 <<+>> @p2 } # Add two polynomials.

sub multiply(@p1, @p2) { # Multiply two polynomials.
   my @prod;
   for ^+@p1 X ^+@p2 -> ($i, $j) { @prod[$i + $j] += @p1[$i] * @p2[$j] }
   return @prod;
}

# Multiply a polynomial by a scalar.
sub scalarMultiply(@poly, $x) { return @poly.map: * × $x }

# Divide a polynomial by a scalar.
sub scalarDivide(@poly, $x) { return scalarMultiply(@poly, 1/$x) }

# rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation#Raku
sub evalPoly(@coefs, $x) { return ([o] map { $_ + $x × * }, @coefs.reverse)(0) }

sub lagrange(@pts) {
   my ($c, @polys) = @pts.elems;
   for ^$c -> $i {
      my @poly = 1;
      for ^$c -> $j {
         next if $i == $j;
         @poly = multiply @poly, [ -@pts[$j].x, 1 ]
      }
      @polys[$i] = scalarDivide @poly, evalPoly(@poly.reverse, @pts[$i].x)
   }
   my @sum = 0;
   for ^$c -> $i { @sum = add @sum, scalarMultiply @polys[$i], @pts[$i].y }
   return @sum;
}

my @pts = map { Point.new: x=>.[0].Rat,y=>.[1].Rat }, [<1 1>,<2 4>,<3 1>,<4 5>];

say [~] lagrange(@pts).kv.rotor(2).reverse.map: -> ($expo, $coef) {
   "{ '+' if $coef ≥ 0 }$coef.nude.join('/') " ~ do given $expo {
      when 0  { " " }
      when 1  { "𝑥 " }
      default { "𝑥^$_ " }
   }
}

```

You may Attempt This Online!


[User]
Lah numbers, sometimes referred to as *Stirling numbers of the third kind*, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.

Unsigned Lah numbers count the number of ways a set of **n** elements can be partitioned into **k** non-empty linearly ordered subsets.

Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.

Lah numbers obey the identities and relations:

```
  L(n, 0), L(0, k) = 0   # for n, k > 0
  L(n, n) = 1
  L(n, 1) = n!
  L(n, k) =           ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)!      # For unsigned Lah numbers
     or
  L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)!      # For   signed Lah numbers

```

Task
:   * Write a routine (function, procedure, whatever) to find **unsigned Lah numbers**. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.

:   * Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, **L(n, k)**, up to **L(12, 12)**. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n).

:   * If your language supports large integers, find and show here, on this page, the maximum value of **L(n, k)** where **n == 100**.

See also

:   * **Wikipedia - Lah number**
    * **OEIS:A105278 - Unsigned Lah numbers**
    * **OEIS:A008297 - Signed Lah numbers**

Related Tasks

:   * **Stirling numbers of the first kind**
    * **Stirling numbers of the second kind**
    * **Bell numbers**

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

```
constant @factorial = 1, |[\*] 1..*;

sub Lah (Int \n, Int \k) {
    return @factorial[n] if k == 1;
    return 1 if k == n;
    return 0 if k > n;
    return 0 if k < 1 or n < 1;
    (@factorial[n] * @factorial[n - 1]) / (@factorial[k] * @factorial[k - 1]) / @factorial[n - k]
}

my $upto = 12;

my $mx = (1..$upto).map( { Lah($upto, $_) } ).max.chars;

put 'Unsigned Lah numbers:  L(n, k):';
put 'n\k', (0..$upto)».fmt: "%{$mx}d";

for 0..$upto -> $row {
    $row.fmt('%-3d').print;
    put (0..$row).map( { Lah($row, $_) } )».fmt: "%{$mx}d";
}

say "\nMaximum value from the L(100, *) row:";
say (^100).map( { Lah 100, $_ } ).max;

```

Output:

```
Unsigned Lah numbers:  L(n, k):
n\k         0          1          2          3          4          5          6          7          8          9         10         11         12
0           1
1           0          1
2           0          2          1
3           0          6          6          1
4           0         24         36         12          1
5           0        120        240        120         20          1
6           0        720       1800       1200        300         30          1
7           0       5040      15120      12600       4200        630         42          1
8           0      40320     141120     141120      58800      11760       1176         56          1
9           0     362880    1451520    1693440     846720     211680      28224       2016         72          1
10          0    3628800   16329600   21772800   12700800    3810240     635040      60480       3240         90          1
11          0   39916800  199584000  299376000  199584000   69854400   13970880    1663200     118800       4950        110          1
12          0  479001600 2634508800 4390848000 3293136000 1317254400  307359360   43908480    3920400     217800       7260        132          1

Maximum value from the L(100, *) row:
44519005448993144810881324947684737529186447692709328597242209638906324913313742508392928375354932241404408343800007105650554669129521241784320000000000000000000000
```


[User]
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.

Each cell can either be black or white.

The ant moves according to the color of the cell it is currently sitting in, with the following rules:

:   :   1. If the cell is black, it changes to white and the ant turns left;
        2. If the cell is white, it changes to black and the ant turns right;
        3. The ant then moves forward to the next cell, and repeat from step 1.

This rather simple ruleset leads to an initially chaotic movement pattern, and after about 10000 steps, a cycle appears where the ant moves steadily away from the starting location in a diagonal corridor about 10 cells wide.
Conceptually the ant can then walk infinitely far away.

Task

Start the ant near the center of a 100x100 field of cells, which is about big enough to contain the initial chaotic part of the movement.

Follow the movement rules for the ant, terminate when it moves out of the region, and show the cell colors it leaves behind.

The problem has received some analysis; for more details, please take a look at the Wikipedia article   (a link is below)..

See also

* Wikipedia:   Langton's ant.

Related task

* Conway's Game of Life.
* Elementary cellular automaton

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

In this version we use 4-bits-per-char graphics to shrink the output to a quarter the area of ASCII graphics.

```
constant @vecs = [1,0,1], [0,-1,1], [-1,0,1], [0,1,1];
constant @blocky = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'.comb;
constant $size = 100;
enum Square <White Black>;
my @plane = [White xx $size] xx $size;
my ($x, $y) = $size/2, $size/2;
my $dir = @vecs.keys.pick;
my $moves = 0;
loop {
    given @plane[$x][$y] {
        when :!defined { last }
        when White { $dir--; $_ = Black; }
        when Black { $dir++; $_ = White; }
    }
    ($x,$y,$moves) »+=« @vecs[$dir %= @vecs];
}
say "Out of bounds after $moves moves at ($x, $y)";
for 0,2,4 ... $size - 2 -> $y {
    say join '', gather for 0,2,4 ... $size - 2 -> $x {
        take @blocky[ 1 * @plane[$x][$y]
                    + 2 * @plane[$x][$y+1]
                    + 4 * @plane[$x+1][$y]
                    + 8 * @plane[$x+1][$y+1] ];
    }
}

```

Output:

```
Out of bounds after 11669 moves at (-1, 26)
            ▄▚▚
           ▟▟▜▟▚
           ▜▀▚▌▟▚
            ▜▘▗▌▟▚
             ▜▘▗▌▟▚
              ▜▘▗▌▟▚
               ▜▘▗▌▟▚
                ▜▘▗▌▟▚
                 ▜▘▗▌▟▚
                  ▜▘▗▌▟▚
                   ▜▘▗▌▟▚
                    ▜▘▗▌▟▚
                     ▜▘▗▌▟▚
                      ▜▘▗▌▟▚
                       ▜▘▗▌▟▚
                        ▜▘▗▌▟▚ ▄
                         ▜▘▗▌▟▘▟▘▗
                      ▞▀▚ ▜▘▗▌▄▙▝▜
                     ▐█  ▌▄▘▘▗▗▞▐▚▌
                      ▌▖▝ ▐▚▙▙ ▖▀▖
                     ▐▄▝█▀▖▄▗▗▗▀▐▛▛▙
                    ▞▚▝▟██▜▞ ▞▗▜▌ ▞▘▌
                   ▐▗▄▌▙▜▐▄▛▀▜▞▜▛▛▄▐
                    ▘▗▝▜▚▖▌▟▞▛▜▌▜▖ █▌
                   ▄▄ ▄▜▛▜▙▖▟▗▛▟▘▌  ▌
                  ▟▖ ▘▘▄▛▌▛▟█▖ ▚▜▀  ▌
                  ▘▘ █▚▛▜▟▌▘▗█▞▛▞▌  ▌
                  ▐▖ ▙▐▙▗█▌▐▀  ▟▛ ▄ ▌
                  ▟▙▚▛▀▄▗▟▖▐▗▘▛▐▀▟▌ ▌
                  ▘▀▞▛▗▘▘█▐▞▗▗▝▟▖▄▝▝
                   ▗▜▞▖▗▘▝█▜▞▖▗▙ ▝ ▙▌
                  ▟▞▖▟▄▌▟▄▙▐█▗▟▙▟▚▗▞
                  ▘▌▚▖▝▛▀ ▐▘▞█▀▟▛█▖
               ▄ ▝▛▚ ▀▜▙▜▜▀▜▚▄▘▙▖
              ▟▖▘▐▜▌▛▄▟▛▝▌ ▜▘▛▗▖▟▌
              ▘▀█▙▙▚▄▛▗▛▖ ▞▗▖▚▗▚▞
               ▜ ▖▄▙▛▚▀▗▜▛ ▞▗▝▛
               ▞▌▜▌█▀▀▘▖ ▙  ▌▀
              ▐▗▌█▛    ▀▚▞▚▞
               ▜▖

```


[User]
Task

Find and show on this page the largest difference between adjacent primes under 1,000,000.

[Assistant]
### Built-ins

```
for 2..8 -> $n {
    printf "Largest prime gap up to {10 ** $n}: %d - between %d and %d.\n", .[0], |.[1]
      given max (^10**$n).grep(&is-prime).rotor(2=>-1).map({.[1]-.[0],$_})
}

```

Output:

```
Largest prime gap up to 100: 8 - between 89 and 97.
Largest prime gap up to 1000: 20 - between 887 and 907.
Largest prime gap up to 10000: 36 - between 9551 and 9587.
Largest prime gap up to 100000: 72 - between 31397 and 31469.
Largest prime gap up to 1000000: 114 - between 492113 and 492227.
Largest prime gap up to 10000000: 154 - between 4652353 and 4652507.
Largest prime gap up to 100000000: 220 - between 47326693 and 47326913.
```

Or, significantly faster using a

### Module

```
use Math::Primesieve;
my $sieve = Math::Primesieve.new;

for 2..8 -> $n {
    printf "Largest prime gap up to {10 ** $n}: %d - between %d and %d.\n", .[0], |.[1]
      given max $sieve.primes(10 ** $n).rotor(2=>-1).map({.[1]-.[0],$_})
}

```

Same output


[User]
Task

Generate **random** 1000-digit number.

 Find the **five** adjacent digits in the 1000-digit number that form the largest 5-digit number.

Extra credit

Find the **five** adjacent digits in the 1000-digit number that form the smallest 5-digit number.

[Assistant]
Show minimum too because... why not?

Use some Tamil Unicode numbers for brevity, and for amusement purposes.

```
   ௰ - Tamil number ten
   ௲ - Tamil number one thousand

```

Do it 5 times for variety, it's random after all.

```
(^௰).roll(௲).rotor(5 => -4)».join.minmax.bounds.put xx 5

```

Sample output:

```
00371 99975
00012 99982
00008 99995
00012 99945
00127 99972
```


[User]
Task

Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.

Use the following two sets of integers as tests   and   show your program output here.

:   :   :   :   :   * {1, 34, 3, 98, 9, 76, 45, 4}
                    * {54, 546, 548, 60}

Possible algorithms

1. A solution could be found by trying all combinations and return the best.
2. Another way to solve this is to note that in the best arrangement, for any two adjacent original integers **X** and **Y**, the concatenation **X** followed by **Y** will be numerically greater than or equal to the concatenation **Y** followed by **X.**
3. Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.

See also

* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?
* Constructing the largest number possible by rearranging a list

[Assistant]
(formerly Perl 6)

```
sub maxnum(*@x) {
    [~] @x.sort: -> $a, $b { $b ~ $a leg $a ~ $b }
}

say maxnum <1 34 3 98 9 76 45 4>;
say maxnum <54 546 548 60>;

```

Output:

```
998764543431
6054854654
```


[User]
Task

Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits.

These numbers are also known as   **Lynch-Bell numbers**,   numbers   **n**   such that the
(base ten) digits are all different (and do not include zero)   and   **n**   is divisible by each of its individual digits.

Example

**135**   is evenly divisible by   **1**,   **3**,   and   **5**.

Note that the digit zero (0) can not be in the number as integer division by zero is undefined.

The digits must all be unique so a base ten number will have at most **9** digits.

Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)

Stretch goal

Do the same thing for hexadecimal.

Related tasks
:   * gapful numbers.
    * palindromic gapful numbers.

Also see
:   * The OEIS sequence:   A115569: Lynch-Bell numbers.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.08

### Base 10

The number can not have a zero in it, that implies that it can not have a 5 either since if it has a 5, it must be divisible by 5, but the only numbers divisible by 5 end in 5 or 0. It can't be zero, and if it is odd, it can't be divisible by 2, 4, 6 or 8. So that leaves 98764321 as possible digits the number can contain. The sum of those 8 digits is not divisible by three so the largest possible integer must use no more than 7 of them (since 3, 6 and 9 would be eliminated). Strictly by removing possibilities that cannot possibly work we are down to at most 7 digits.

We can deduce that the digit that won't get used is one of 1, 4, or 7 since those are the only ones where the removal will yield a sum divisible by 3. It is *extremely* unlikely be 1, since EVERY number is divisible by 1. Removing it reduces the number of digits available but doesn't gain anything as far as divisibility. It is unlikely to be 7 since 7 is prime and can't be made up of multiples of other numbers. Practically though, the code to accommodate these observations is longer running and more complex than just brute-forcing it from here.

In order to accommodate the most possible digits, the number must be divisible by 7, 8 and 9. If that is true then it is automatically divisible by 2, 3, 4, & 6 as they can all be made from the combinations of multiples of 2 and 3 which are present in 8 & 9; so we'll only bother to check multiples of 9 \* 8 \* 7 or 504.

All these optimizations get the run time to well under 1 second.

```
my $magic-number = 9 * 8 * 7;                        # 504

my $div = 9876432 div $magic-number * $magic-number; # largest 7 digit multiple of 504 < 9876432

for $div, { $_ - $magic-number } ... * -> $test {    # only generate multiples of 504
    next if $test ~~ / <[05]> /;                     # skip numbers containing 0 or 5
    next if $test ~~ / (.).*$0 /;                    # skip numbers with non unique digits

    say "Found $test";                               # Found a solution, display it
    for $test.comb {
        printf "%s / %s = %s\n", $test, $_, $test / $_;
    }
    last
}

```

Output:

```
Found 9867312
9867312 / 9 = 1096368
9867312 / 8 = 1233414
9867312 / 6 = 1644552
9867312 / 7 = 1409616
9867312 / 3 = 3289104
9867312 / 1 = 9867312
9867312 / 2 = 4933656
```

### Base 16

There are fewer analytical optimizations available for base 16. Other than 0, no digits can be ruled out so a much larger space must be searched. We'll start at the largest possible permutation (FEDCBA987654321) and work down so as soon as we find **a** solution, we know it is **the** solution. The combination of `.race` with `.first` lets us utilize concurrency and exit early when the single desired solution is found.

```
my $hex = 'FEDCBA987654321';        # largest possible hex number
my $magic-number = [lcm] 1 .. 15;   # find least common multiple
my $div = :16($hex) div $magic-number * $magic-number;

# hunt for target stepping backwards in multiples of the lcm
my $target = ($div, * - $magic-number ... 0).race.first: -> \test {
    my \num= test.base(16);
    (num.contains('0') || num.comb.Bag.values.max > 1) ?? False !! True
};
my $hexnum = $target.base(16);

say "Found $hexnum"; # Found a solution, display it

say ' ' x 12, 'In base 16', ' ' x 36, 'In base 10';
for $hexnum.comb {
    printf "%s / %s = %s  |  %d / %2d = %19d\n",
        $hexnum, $_, ($target / :16($_)).base(16),
        $target, :16($_), $target / :16($_);}

```

Output:

```
Found FEDCB59726A1348
            In base 16                                    In base 10
FEDCB59726A1348 / F = 10FDA5B4BE4F038  |  1147797065081426760 / 15 =   76519804338761784
FEDCB59726A1348 / E = 1234561D150B83C  |  1147797065081426760 / 14 =   81985504648673340
FEDCB59726A1348 / D = 139AD2E43E0C668  |  1147797065081426760 / 13 =   88292081929340520
FEDCB59726A1348 / C = 153D0F21EDE2C46  |  1147797065081426760 / 12 =   95649755423452230
FEDCB59726A1348 / B = 172B56538F25ED8  |  1147797065081426760 / 11 =  104345187734675160
FEDCB59726A1348 / 5 = 32F8F11E3AED0A8  |  1147797065081426760 /  5 =  229559413016285352
FEDCB59726A1348 / 9 = 1C5169829283B08  |  1147797065081426760 /  9 =  127533007231269640
FEDCB59726A1348 / 7 = 2468AC3A2A17078  |  1147797065081426760 /  7 =  163971009297346680
FEDCB59726A1348 / 2 = 7F6E5ACB93509A4  |  1147797065081426760 /  2 =  573898532540713380
FEDCB59726A1348 / 6 = 2A7A1E43DBC588C  |  1147797065081426760 /  6 =  191299510846904460
FEDCB59726A1348 / A = 197C788F1D76854  |  1147797065081426760 / 10 =  114779706508142676
FEDCB59726A1348 / 1 = FEDCB59726A1348  |  1147797065081426760 /  1 = 1147797065081426760
FEDCB59726A1348 / 3 = 54F43C87B78B118  |  1147797065081426760 /  3 =  382599021693808920
FEDCB59726A1348 / 4 = 3FB72D65C9A84D2  |  1147797065081426760 /  4 =  286949266270356690
FEDCB59726A1348 / 8 = 1FDB96B2E4D4269  |  1147797065081426760 /  8 =  143474633135178345
```


[User]
Task

Task description is taken from Project Euler (https://projecteuler.net/problem=4)

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Stretch Goal

Find the largest palindrome made from the product of two n-digit numbers, where n ranges from 4 to 7.

Extended Stretch Goal

Find the largest palindrome made from the product of two n-digit numbers, where n ranges beyond 7,

[Assistant]
```
use Inline::Perl5;
my $p5 = Inline::Perl5.new();
$p5.use: 'ntheory';
my &divisors = $p5.run('sub { ntheory::divisors $_[0] }');

.say for (2..12).map: {.&lpp};

multi lpp ($oom where {!($_ +& 1)}) { # even number of multiplicand digits
    my $f = +(9 x $oom);
    my $o = $oom / 2;
    my $pal = +(9 x $o ~ 0 x $oom ~ 9 x $o);
    sprintf "Largest palindromic product of two %2d-digit integers: %d × %d = %d", $oom, $pal div $f, $f, $pal
}

multi lpp ($oom where {$_ +& 1}) { # odd number of multiplicand digits
    my $p;
    (+(1 ~ (0 x ($oom - 1))) .. +(9 ~ (9 x ($oom - 1)))).reverse.map({ +($_ ~ .flip) }).map: -> $pal {
        for my @factors = divisors("$pal")».Int.grep({ .chars == $oom }).sort( -* ) {
            next unless $pal div $_ ∈ @factors;
            $p = sprintf("Largest palindromic product of two %2d-digit integers: %d × %d = %d", $oom, $pal div $_, $_, $pal);
            last;
        }
        last if $p;
    }
    $p
}

```

```
Largest palindromic product of two  2-digit integers: 91 × 99 = 9009
Largest palindromic product of two  3-digit integers: 913 × 993 = 906609
Largest palindromic product of two  4-digit integers: 9901 × 9999 = 99000099
Largest palindromic product of two  5-digit integers: 99681 × 99979 = 9966006699
Largest palindromic product of two  6-digit integers: 999001 × 999999 = 999000000999
Largest palindromic product of two  7-digit integers: 9997647 × 9998017 = 99956644665999
Largest palindromic product of two  8-digit integers: 99990001 × 99999999 = 9999000000009999
Largest palindromic product of two  9-digit integers: 999920317 × 999980347 = 999900665566009999
Largest palindromic product of two 10-digit integers: 9999900001 × 9999999999 = 99999000000000099999
Largest palindromic product of two 11-digit integers: 99999943851 × 99999996349 = 9999994020000204999999
Largest palindromic product of two 12-digit integers: 999999000001 × 999999999999 = 999999000000000000999999
```


[User]
Task

The task description is taken for Project Euler (https://projecteuler.net/problem=3)

What is the largest prime factor of the number 600851475143 ?

[Assistant]
Note: These are both extreme overkill for the task requirements.

### Not particularly fast

Pure Raku. Using Prime::Factor from the Raku ecosystem. Makes it to 2^95 - 1 in 1 second on my system.

```
use Prime::Factor;

my $start = now;

for flat 600851475143, (1..∞).map: { 2 +< $_ - 1 } {
    say "Largest prime factor of $_: ", max prime-factors $_;
    last if now - $start > 1; # quit after one second of total run time
}

```

```
Largest prime factor of 600851475143: 6857
Largest prime factor of 3: 3
Largest prime factor of 7: 7
Largest prime factor of 15: 5
Largest prime factor of 31: 31
Largest prime factor of 63: 7
Largest prime factor of 127: 127
Largest prime factor of 255: 17
Largest prime factor of 511: 73
Largest prime factor of 1023: 31
Largest prime factor of 2047: 89
Largest prime factor of 4095: 13
Largest prime factor of 8191: 8191
Largest prime factor of 16383: 127
Largest prime factor of 32767: 151
Largest prime factor of 65535: 257
Largest prime factor of 131071: 131071
Largest prime factor of 262143: 73
Largest prime factor of 524287: 524287
Largest prime factor of 1048575: 41
Largest prime factor of 2097151: 337
Largest prime factor of 4194303: 683
Largest prime factor of 8388607: 178481
Largest prime factor of 16777215: 241
Largest prime factor of 33554431: 1801
Largest prime factor of 67108863: 8191
Largest prime factor of 134217727: 262657
Largest prime factor of 268435455: 127
Largest prime factor of 536870911: 2089
Largest prime factor of 1073741823: 331
Largest prime factor of 2147483647: 2147483647
Largest prime factor of 4294967295: 65537
Largest prime factor of 8589934591: 599479
Largest prime factor of 17179869183: 131071
Largest prime factor of 34359738367: 122921
Largest prime factor of 68719476735: 109
Largest prime factor of 137438953471: 616318177
Largest prime factor of 274877906943: 524287
Largest prime factor of 549755813887: 121369
Largest prime factor of 1099511627775: 61681
Largest prime factor of 2199023255551: 164511353
Largest prime factor of 4398046511103: 5419
Largest prime factor of 8796093022207: 2099863
Largest prime factor of 17592186044415: 2113
Largest prime factor of 35184372088831: 23311
Largest prime factor of 70368744177663: 2796203
Largest prime factor of 140737488355327: 13264529
Largest prime factor of 281474976710655: 673
Largest prime factor of 562949953421311: 4432676798593
Largest prime factor of 1125899906842623: 4051
Largest prime factor of 2251799813685247: 131071
Largest prime factor of 4503599627370495: 8191
Largest prime factor of 9007199254740991: 20394401
Largest prime factor of 18014398509481983: 262657
Largest prime factor of 36028797018963967: 201961
Largest prime factor of 72057594037927935: 15790321
Largest prime factor of 144115188075855871: 1212847
Largest prime factor of 288230376151711743: 3033169
Largest prime factor of 576460752303423487: 3203431780337
Largest prime factor of 1152921504606846975: 1321
Largest prime factor of 2305843009213693951: 2305843009213693951
Largest prime factor of 4611686018427387903: 2147483647
Largest prime factor of 9223372036854775807: 649657
Largest prime factor of 18446744073709551615: 6700417
Largest prime factor of 36893488147419103231: 145295143558111
Largest prime factor of 73786976294838206463: 599479
Largest prime factor of 147573952589676412927: 761838257287
Largest prime factor of 295147905179352825855: 131071
Largest prime factor of 590295810358705651711: 10052678938039
Largest prime factor of 1180591620717411303423: 122921
Largest prime factor of 2361183241434822606847: 212885833
Largest prime factor of 4722366482869645213695: 38737
Largest prime factor of 9444732965739290427391: 9361973132609
Largest prime factor of 18889465931478580854783: 616318177
Largest prime factor of 37778931862957161709567: 10567201
Largest prime factor of 75557863725914323419135: 525313
Largest prime factor of 151115727451828646838271: 581283643249112959
Largest prime factor of 302231454903657293676543: 22366891
Largest prime factor of 604462909807314587353087: 1113491139767
Largest prime factor of 1208925819614629174706175: 4278255361
Largest prime factor of 2417851639229258349412351: 97685839
Largest prime factor of 4835703278458516698824703: 8831418697
Largest prime factor of 9671406556917033397649407: 57912614113275649087721
Largest prime factor of 19342813113834066795298815: 14449
Largest prime factor of 38685626227668133590597631: 9520972806333758431
Largest prime factor of 77371252455336267181195263: 2932031007403
Largest prime factor of 154742504910672534362390527: 9857737155463
Largest prime factor of 309485009821345068724781055: 2931542417
Largest prime factor of 618970019642690137449562111: 618970019642690137449562111
Largest prime factor of 1237940039285380274899124223: 18837001
Largest prime factor of 2475880078570760549798248447: 23140471537
Largest prime factor of 4951760157141521099596496895: 2796203
Largest prime factor of 9903520314283042199192993791: 658812288653553079
Largest prime factor of 19807040628566084398385987583: 165768537521
Largest prime factor of 39614081257132168796771975167: 30327152671
```

### Particularly fast

Using Perl 5 ntheory library via Inline::Perl5. Makes it to about 2^155 - 1 in 1 second on my system. *Varies from 2^145-1 (lowest seen) to 2^168-1 (highest seen).*

```
use Inline::Perl5;
my $p5 = Inline::Perl5.new();
$p5.use: 'ntheory';
my &lpf = $p5.run('sub { ntheory::todigitstring ntheory::vecmax ntheory::factor $_[0] }');

my $start = now;

for flat 600851475143, (1..∞).map: { 2 +< $_ - 1 } {
    say "Largest prime factor of $_: ", lpf "$_";
    last if now - $start > 1; # quit after one second of total run time
}

```

Same output only much longer.


[User]
Task

The task description is taken from Project Euler:

(https://projecteuler.net/problem=11)

Given the 20×20 grid below:

08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08

49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00

81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65

52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91

22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80

24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50

32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70

67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21

24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72

21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95

78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92

16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57

86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58

19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40

04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66

88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69

04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36

20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16

20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54

01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48

What is the greatest product of four adjacent numbers in the same direction (down, right) in the 20×20 grid?

[Assistant]
General solution. No hard coded values. Works with any size matrix, configurable number of terms.

```
my @matrix = q:to/END/.lines».words;
  08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
  49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
  81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
  52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
  22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
  24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
  32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
  67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
  24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
  21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
  78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
  16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
  86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
  19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
  04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
  88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
  04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
  20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
  20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
  01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
END

my $terms = 4;

say "Largest product of $terms adjacent elements: " ~ max flat (^@matrix).map: {
    @matrix.rotor($terms => -$terms+1).flat»[$_].batch($terms)».reduce(&[*]), # vertical
    @matrix[$_].rotor($terms => -$terms+1)».reduce(&[*]);                     # horizontal
}

```

Output:

```
Largest product of 4 adjacent elements: 51267216
```


[User]
Task
:   a(1) = 1; for n > 1, a(n) = **largest** proper divisor of n, where **n < 101** .

[Assistant]
A little odd to special case a(1) == 1 as technically, 1 doesn't have any proper divisors... but it matches **OEIS A032742** so whatever.

Note: this example is ridiculously overpowered (and so, somewhat inefficient) for a range of 1 to 100, but will easily handle large numbers without modification.

```
use Prime::Factor;

for 0, 2**67 - 1 -> $add {
    my $start = now;

    my $range = $add + 1 .. $add + 100;

    say "GPD for {$range.min} through {$range.max}:";

    say ( $range.hyper(:14batch).map: {$_ == 1 ?? 1 !! $_ %% 2 ?? $_ / 2 !! .&proper-divisors.max} )\
        .batch(10)».fmt("%{$add.chars + 1}d").join: "\n";

    say (now - $start).fmt("%0.3f seconds\n");
}

```

Output:

```
GPD for 1 through 100:
 1  1  1  2  1  3  1  4  3  5
 1  6  1  7  5  8  1  9  1 10
 7 11  1 12  5 13  9 14  1 15
 1 16 11 17  7 18  1 19 13 20
 1 21  1 22 15 23  1 24  7 25
17 26  1 27 11 28 19 29  1 30
 1 31 21 32 13 33  1 34 23 35
 1 36  1 37 25 38 11 39  1 40
27 41  1 42 17 43 29 44  1 45
13 46 31 47 19 48  1 49 33 50
0.071 seconds

GPD for 147573952589676412928 through 147573952589676413027:
  73786976294838206464   49191317529892137643   73786976294838206465                      1   73786976294838206466   21081993227096630419   73786976294838206467   49191317529892137645   73786976294838206468    8680820740569200761
  73786976294838206469    5088756985850910791   73786976294838206470   49191317529892137647   73786976294838206471   13415813871788764813   73786976294838206472   29514790517935282589   73786976294838206473   49191317529892137649
  73786976294838206474    6416258808246800563   73786976294838206475     977310944302492801   73786976294838206476   49191317529892137651   73786976294838206477   29514790517935282591   73786976294838206478      87167130885810049
  73786976294838206479   49191317529892137653   73786976294838206480   21081993227096630423   73786976294838206481    7767050136298758577   73786976294838206482   49191317529892137655   73786976294838206483    2784414199805215339
  73786976294838206484   11351842506898185613   73786976294838206485   49191317529892137657   73786976294838206486     939961481462907089   73786976294838206487   29514790517935282595   73786976294838206488   49191317529892137659
  73786976294838206489      82581954443019817   73786976294838206490        147258377885867   73786976294838206491   49191317529892137661   73786976294838206492   29514790517935282597   73786976294838206493   13415813871788764817
  73786976294838206494   49191317529892137663   73786976294838206495                      1   73786976294838206496    2202596307308603179   73786976294838206497   49191317529892137665   73786976294838206498    5088756985850910793
  73786976294838206499                      1   73786976294838206500   49191317529892137667   73786976294838206501   21081993227096630429   73786976294838206502   29514790517935282601   73786976294838206503   49191317529892137669
  73786976294838206504   13415813871788764819   73786976294838206505     103270785577100359   73786976294838206506   49191317529892137671   73786976294838206507   29514790517935282603   73786976294838206508   21081993227096630431
  73786976294838206509   49191317529892137673   73786976294838206510   11351842506898185617   73786976294838206511                      1   73786976294838206512   49191317529892137675   73786976294838206513    1305964182209525779
0.440 seconds
```


[User]
Task

Write a program or a script that returns the date of the last Fridays of each month of a given year.

The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:

```
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28

```

Related tasks

* Five weekends
* Day of the week
* Find the last Sunday of each month

[Assistant]
(formerly Perl 6)

```
sub MAIN (Int $year = Date.today.year) {
    my @fri;
    for Date.new("$year-01-01") .. Date.new("$year-12-31") {
        @fri[.month] = .Str if .day-of-week == 5;
    }
    .say for @fri[1..12];
}

```

Example:

```
$ ./lastfri 2038
2038-01-29
2038-02-26
2038-03-26
2038-04-30
2038-05-28
2038-06-25
2038-07-30
2038-08-27
2038-09-24
2038-10-29
2038-11-26
2038-12-31
```

A solution without a result array to store things in:

```
sub MAIN (Int $year = Date.today.year) {
    say ~.value.reverse.first: *.day-of-week == 5
        for classify *.month, Date.new("$year-01-01") .. Date.new("$year-12-31");
}

```

Here, `classify` sorts the dates into one bin per month (but preserves the order in each bin). We then take the list inside each bin (`.value`) and find the last (`.reverse.first`) date which is a Friday.

Another variation where the data flow can be read left to right using feed operators:

```
sub MAIN (Int $year = Date.today.year) {
    .say for Date.new("$year-01-01") .. Date.new("$year-12-31") ==> classify *.month ==>
             map *.value.reverse.first: *.day-of-week == 5
}

```


[User]
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the game.

For example, with   "animals"   as the category,

```
Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake
...

```

Task

Take the following selection of 70 English Pokemon names   (extracted from   Wikipedia's list of Pokemon)   and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name.

No Pokemon name is to be repeated.

```
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask

```

Extra brownie points for dealing with the full list of   646   names.

[Assistant]
(formerly Perl 6)
A breadth-first search that uses disk files to avoid memory exhaustion. Each candidate sequence is encoded at one character per name, so to avoid reuse of names we merely have to make sure there are no repeat characters in our encoded string. (The encoding starts at ASCII space for the first name, so newline is not among the encoded characters.)

```
my @names = <
    audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
    cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
    girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
    kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
    nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
    porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
    sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
    tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask
>;

my @last = @names.map: {.substr(*-1,1).ord }
my @succs = [] xx 128;
for @names.kv -> $i, $name {
    my $ix = $name.ord; # $name.substr(0,1).ord
    push @succs[$ix], $i;
}

my $OUT = open "llfl.new", :w orelse .die;
$OUT.print: chr($_ + 32),"\n" for 0 ..^ @names;
close $OUT;
my $new = +@names;
my $len = 1;

while $new {
    say "Length { $len++ }: $new candidates";
    shell 'mv llfl.new llfl.known';
    my $IN = open "llfl.known" orelse .die;
    my $OUT = open "llfl.new", :w orelse .die;
    $new = 0;

    loop {
	my $cand = $IN.get // last;
	for @succs[@last[$cand.ord - 32]][] -> $i {
	    my $ic = chr($i + 32);
	    next if $cand ~~ /$ic/;
	    $OUT.print: $ic,$cand,"\n";
	    $new++;
	}
    }
    $IN.close;
    $OUT.close;
}

my $IN = open "llfl.known" orelse .die;
my $eg = $IN.lines.pick;
say "Length of longest: ", $eg.chars;
say join ' ', $eg.ords.reverse.map: { @names[$_ - 32] }

```

Output:

```
Length 1: 70 candidates
Length 2: 172 candidates
Length 3: 494 candidates
Length 4: 1288 candidates
Length 5: 3235 candidates
Length 6: 7731 candidates
Length 7: 17628 candidates
Length 8: 37629 candidates
Length 9: 75122 candidates
Length 10: 139091 candidates
Length 11: 236679 candidates
Length 12: 367405 candidates
Length 13: 516210 candidates
Length 14: 650916 candidates
Length 15: 733915 candidates
Length 16: 727566 candidates
Length 17: 621835 candidates
Length 18: 446666 candidates
Length 19: 260862 candidates
Length 20: 119908 candidates
Length 21: 40296 candidates
Length 22: 10112 candidates
Length 23: 1248 candidates
Length of longest: 23
machamp petilil loudred darmanitan nosepass simisear rufflet trapinch heatmor registeel landorus starly yamask kricketune exeggcute emboar relicanth haxorus seaking girafarig gabite emolga audino
```


[User]
Task

List = [6, 81, 243, 14, 25, 49, 123, 69, 11]

Find the two smallest items, remove them from the list, find their sum, and add the sum to the end of list.

Repeat until the list contains one element.

Show the steps and last item on this page.

Show the unsorted list in output in case "Without sort"

[Assistant]
Uses no sorting; does not modify overall list order while processing.

```
say ' Original ', my @list = 6, 81, 243, 14, 25, 49, 123, 69, 11;

say push @list: get(min @list) + get(min @list) while @list > 1;

sub get ($min) {
    @list.splice: @list.first(* == $min, :k), 1;
    printf " %3d ", $min;
    $min;
}

```

Output:

```
 Original [6 81 243 14 25 49 123 69 11]
   6   11 [81 243 14 25 49 123 69 17]
  14   17 [81 243 25 49 123 69 31]
  25   31 [81 243 49 123 69 56]
  49   56 [81 243 123 69 105]
  69   81 [243 123 105 150]
 105  123 [243 150 228]
 150  228 [243 378]
 243  378 [621]

```


[User]
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.

For a reduced Latin Square the first row is always 1 to n. The second row is all Permutations/Derangements of 1 to n starting with 2. The third row is all Permutations/Derangements of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all Permutations/Derangements of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.

Demonstrate by:

* displaying the four reduced Latin Squares of order 4.
* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.

[Assistant]
(formerly Perl 6)

```
# utilities: factorial, sub-factorial, derangements
sub  postfix:<!>($n) { (constant f = 1, |[\×] 1..*)[$n] }
sub   prefix:<!>($n) { (1, 0, 1, -> $a, $b { ($++ + 2) × ($b + $a) } ... *)[$n] }
sub derangements(@l) { @l.permutations.grep(-> @p { none(@p Zeqv @l) }) }

sub LS-reduced (Int $n) {
    return [1] if $n == 1;

    my @LS;
    my @l = 1 X+ ^$n;
    my %D = derangements(@l).classify(*.[0]);

    for [X] (^(!$n/($n-1))) xx $n-1 -> $tuple {
        my @d.push: @l;
        @d.push: %D{2}[$tuple[0]];
        LOOP:
        for 3 .. $n -> $x {
            my @try = |%D{$x}[$tuple[$x-2]];
            last LOOP if any @try »==« @d[$_] for 1..@d-1;
            @d.push: @try;
        }
        next unless @d == $n and [==] [Z+] @d;
        @LS.push: @d;
    }
    @LS
}

say .join("\n") ~ "\n" for LS-reduced(4);
for 1..6 -> $n {
    printf "Order $n: Size %-4d x $n! x {$n-1}! => Total %d\n", $_, $_ * $n! * ($n-1)! given LS-reduced($n).elems
}

```

Output:

```
1 2 3 4
2 1 4 3
3 4 1 2
4 3 2 1

1 2 3 4
2 1 4 3
3 4 2 1
4 3 1 2

1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3

1 2 3 4
2 4 1 3
3 1 4 2
4 3 2 1

Order 1: Size 1    x 1! x 0! => Total 1
Order 2: Size 1    x 2! x 1! => Total 2
Order 3: Size 1    x 3! x 2! => Total 12
Order 4: Size 4    x 4! x 3! => Total 576
Order 5: Size 56   x 5! x 4! => Total 161280
Order 6: Size 9408 x 6! x 5! => Total 812851200
```


[User]
Section 3.3 of [Generalised 2-designs with Block Size 3(Andy L. Drizen)] describes a method of generating Latin Squares of order n attributed to Jacobson and Matthews. The purpose of this task is to produce a function which given a valid Latin Square transforms it to another using this method.

part 1

Use one of the 4 Latin Squares in reduced form of order 4 as X0 to generate 10000 Latin Squares using X(n-1) to generate X(n). Convert the resulting Latin Squares to their reduced form, display them and the number of times each is produced.

part 2

As above for order 5, but do not display the squares. Generate the 56 Latin Squares in reduced form of order 5, confirm that all 56 are produced by the Jacobson and Matthews technique and display the number of each produced.

part 3

Generate 750 Latin Squares of order 42 and display the 750th.

part 4

Generate 1000 Latin Squares of order 256. Don't display anything but confirm the approximate time taken and anything else you may find interesting

[Assistant]
**Translation of**: Go

```
# 20210729 Raku programming solution

#!/usr/bin/env raku

sub makeCube(\from, Int \n) {
   my @c = [[[ 0 xx n ] xx n ] xx n ];
   from.Bool ?? do race for ^n X ^n -> (\i,\j) { @c[i;j; { from[i;j]-1 } ] = 1 }
             !! do race for ^n X ^n -> (\i,\j) { @c[i;j; {   (i+j)%n   } ] = 1 }
   return @c
}

sub shuffleCube(@c) {
   my ($rx, $ry, $rz); my \n = +@c; my Bool \proper = $ = True;

   repeat { ($rx ,$ry, $rz) = (^n).roll: 3 } until @c[$rx;$ry;$rz] == 0;
   loop {
      my ($ox, $oy, $oz);
      for ^n { last if @c[ $ox = $_ ;$ry;$rz] == 1 }
      if !proper and (^3).roll==0 {
         for $ox^…^n { last if @c[ $ox = $_ ;$ry;$rz] == 1 }
      }
      for ^n { last if @c[$rx; $oy = $_ ;$rz] == 1 }
      if !proper and (^3).roll==0 {
         for $oy^…^n { last if @c[$rx; $oy = $_ ;$rz] == 1 }
      }
      for ^n { last if @c[$rx;$ry;  $oz = $_ ] == 1 }
      if !proper and (^3).roll==0 {
         for $oz^…^n { last if @c[$rx;$ry; $oz = $_ ] == 1 }
      }

      (@c[$rx;$ry;$rz],@c[$rx;$oy;$oz],@c[$ox;$ry;$oz],@c[$ox;$oy;$rz]) »+=»1;
      (@c[$rx;$ry;$oz],@c[$rx;$oy;$rz],@c[$ox;$ry;$rz],@c[$ox;$oy;$oz]) »-=»1;

      @c[$ox;$oy;$oz] < 0 ?? (($rx,$ry,$rz) = ($ox,$oy,$oz)) !! last ;
      proper = False
   }
}

sub toMatrix(@c) {
   my \n = +@c;
   my @m = [[0 xx n] xx n];
   for ^n X ^n -> (\i,\j) {
      for ^n -> \k { if @c[i;j;k] != 0 { @m[i;j] = k and last } }
   }
   return @m
}

sub toReduced(@m is copy) {
   my \n = +@m;
   for 0…(n-2) -> \j {
      if ( @m[0;j] != j ) {
         for j^…^n -> \k {
            if ( @m[0;k] == j ) {
               for 0…^n -> \i { (@m[i;j], @m[i;k]) = (@m[i;k], @m[i;j]) }
               last
            }
         }
      }
   }
   for 1…(n-2) -> \i {
      if ( @m[i;0] != i ) {
         for i^…^n -> \k {
            if ( @m[k;0] == i ) {
               for 0…^n -> \j { (@m[i;j], @m[k;j]) = (@m[k;j], @m[i;j]) }
               last
            }
         }
      }
   }
   return @m
}

sub printAs1based { say ($_ »+» 1).Str for @_.rotor: @_.elems.sqrt }

my (%freq, @c, @in);

say "Part 1: 10,000 latin Squares of order 4 in reduced form:\n";
@in = [[1, 2, 3, 4], [2, 1, 4, 3], [3, 4, 1, 2], [4, 3, 2, 1]];
@c = makeCube(@in, 4);
for ^10_000 {
   shuffleCube @c ;
   %freq{@c.&toMatrix.&toReduced».List.flat.Str}++
}
for %freq.kv -> $k, $v {
   printAs1based $k.split(' ');
   say "\nOccurs $v times.\n"
}

say "Part 2: 10,000 latin Squares of order 5 in reduced form:\n";
@in = [ [1,2,3,4,5], [2,3,4,5,1], [3,4,5,1,2], [4,5,1,2,3], [5,1,2,3,4] ];
%freq = ();
@c = makeCube(@in, 5);
for ^10_000 {
   shuffleCube @c ;
   %freq{@c.&toMatrix.&toReduced».List.flat.Str}++
}
for %freq.values.kv -> $i, $j { printf "%2d(%3d)%s", $i+1, $j, ' ' }

say "\n\nPart 3: 750 latin squares of order 42, showing the last one:\n";
@c = makeCube([], 42); # (1..42).pick(*)
( for ^750 { shuffleCube @c } ) and printAs1based @c.&toMatrix».List.flat ;

say "\nPart 4: 100 latin squares of order 256:\n";
my $snapshot = now;
@c = makeCube([], 256);
for ^100 { shuffleCube @c } # without hyper, will do only 100 cycles
say "Generated in { now - $snapshot } seconds."

```

Output:

```
Part 1: 10,000 latin Squares of order 4 in reduced form:

1 2 3 4
2 1 4 3
3 4 1 2
4 3 2 1

Occurs 2442 times.

1 2 3 4
2 4 1 3
3 1 4 2
4 3 2 1

Occurs 2705 times.

1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3

Occurs 2548 times.

1 2 3 4
2 1 4 3
3 4 2 1
4 3 1 2

Occurs 2305 times.

Part 2: 10,000 latin Squares of order 5 in reduced form:

 1(210)  2(191)  3(186)  4(158)  5(219)  6(164)  7(147)  8(160)  9(196) 10(188) 11(193) 12(168) 13(195) 14(173) 15(151) 16(184) 17(211) 18(171) 19(185) 20(155) 21(157) 22(191) 23(195) 24(177) 25(157) 26(191) 27(165) 28(178) 29(191) 30(180) 31(193) 32(176) 33(196) 34(178) 35(156) 36(168) 37(155) 38(152) 39(155) 40(223) 41(159) 42(165) 43(210) 44(175) 45(195) 46(188) 47(178) 48(154) 49(172) 50(176) 51(178) 52(164) 53(175) 54(196) 55(187) 56(189)

Part 3: 750 latin squares of order 42, showing the last one:

26 27 4 41 31 10 28 13 3 29 21 42 14 39 19 8 5 7 6 40 17 37 35 33 1 38 22 34 18 11 12 2 32 36 9 24 25 23 16 15 30 20
16 40 6 11 22 14 41 42 20 7 24 8 29 27 28 4 26 19 21 39 37 9 2 32 36 15 12 13 38 5 31 33 34 3 17 1 23 35 30 18 10 25
31 15 11 3 5 22 13 10 14 24 41 18 6 16 17 29 36 37 12 28 23 39 34 8 27 40 4 35 7 19 32 26 21 1 2 33 20 9 38 30 25 42
13 37 31 38 42 9 11 2 10 36 22 34 18 23 12 39 25 20 19 26 8 41 16 6 21 32 5 4 33 17 40 24 30 29 27 3 28 14 1 7 35 15
41 7 17 28 24 12 29 8 31 22 1 3 11 42 23 26 39 13 25 19 36 18 33 37 6 5 20 15 2 16 14 4 27 35 38 10 30 32 9 21 34 40
5 19 12 32 20 30 6 33 17 16 27 13 8 9 2 37 21 18 39 4 7 40 1 15 3 35 11 24 10 31 36 23 29 41 22 25 26 28 34 14 42 38
11 14 20 5 3 32 19 27 42 18 12 41 34 6 24 21 38 26 10 35 33 28 9 22 23 39 17 40 31 15 30 37 16 2 36 4 8 1 13 25 29 7
20 6 22 16 34 26 33 23 2 11 29 7 4 13 21 42 9 24 14 41 15 31 5 3 25 18 19 30 1 10 37 36 17 12 39 27 40 38 28 32 8 35
4 25 32 8 28 17 40 19 22 15 23 2 35 5 34 16 18 39 38 24 30 13 41 1 20 3 36 33 42 12 26 29 10 31 6 21 14 37 7 9 11 27
21 2 35 39 26 28 36 16 7 37 19 32 33 1 38 27 4 8 23 6 5 34 40 30 29 42 14 10 9 22 11 12 25 15 13 31 17 18 41 24 20 3
30 28 3 12 6 8 31 32 40 42 25 38 9 33 16 14 13 27 26 17 4 19 20 24 15 36 37 18 11 23 10 22 1 39 21 5 34 41 2 35 7 29
8 34 26 6 16 33 15 28 41 38 40 24 30 21 22 17 20 35 32 23 42 25 11 5 12 1 31 2 13 3 39 27 14 9 18 7 19 29 36 4 37 10
1 22 2 7 39 23 14 18 11 30 15 17 26 10 6 28 16 12 24 31 35 36 37 21 40 29 13 8 3 41 34 38 4 32 25 42 5 27 20 19 33 9
25 32 1 9 35 6 42 34 37 10 13 20 5 19 30 41 17 36 7 15 40 38 26 31 2 23 18 28 24 33 21 11 22 4 14 39 27 8 3 29 16 12
17 12 18 30 11 4 10 5 28 8 33 31 19 22 36 13 6 9 34 42 29 1 27 39 38 21 25 23 26 24 7 15 2 16 41 14 32 40 35 20 3 37
27 36 39 37 18 13 34 14 19 5 32 26 38 12 3 23 1 30 17 11 6 35 21 16 24 41 7 9 28 20 2 31 40 10 4 29 22 25 33 42 15 8
36 24 28 2 32 11 37 12 29 33 16 9 40 3 10 34 7 15 4 27 22 20 25 18 13 26 42 39 17 14 5 8 41 21 23 30 35 31 6 38 19 1
32 30 36 34 14 7 22 9 35 23 6 21 37 2 5 15 31 33 3 16 25 17 4 27 19 13 24 29 40 39 28 1 20 38 10 11 42 12 8 41 26 18
2 41 8 20 29 35 25 4 6 1 17 19 3 18 42 33 12 34 5 32 11 15 30 38 39 14 23 31 21 37 22 9 26 27 16 28 36 7 40 10 13 24
39 1 27 14 2 20 9 26 4 25 18 33 41 28 29 32 34 38 13 7 21 8 10 35 31 17 16 19 23 30 15 5 6 40 37 12 3 36 42 22 24 11
3 13 9 24 15 21 8 41 33 32 20 1 25 40 27 22 29 31 18 36 10 11 17 2 37 28 39 42 14 4 16 35 7 30 34 26 38 6 12 23 5 19
6 33 37 26 30 15 20 35 21 39 14 27 7 4 32 36 2 5 9 18 34 23 22 17 42 24 28 11 8 1 38 3 12 25 31 41 29 10 19 13 40 16
33 16 21 29 40 38 24 7 30 27 11 25 2 32 37 5 35 4 22 9 31 42 18 36 10 34 1 14 12 13 8 41 23 17 3 19 15 20 39 6 28 26
14 17 24 31 19 27 26 6 38 3 9 36 12 41 15 18 37 22 40 33 16 32 29 42 11 4 10 7 34 25 23 28 35 13 20 8 2 5 21 1 39 30
18 31 29 22 37 25 3 24 26 28 8 4 20 36 9 30 33 42 27 38 1 7 13 10 32 11 2 16 19 21 35 14 5 23 40 15 41 39 17 12 6 34
34 9 15 19 23 41 5 39 24 31 26 30 13 25 11 10 40 1 16 22 2 33 28 12 14 37 38 32 29 8 3 7 42 20 35 6 18 4 27 17 21 36
24 42 5 23 10 37 35 17 18 13 7 39 21 29 8 1 32 40 20 14 12 4 15 26 22 25 9 6 41 36 27 34 3 19 28 16 11 30 31 2 38 33
7 23 41 10 17 24 21 22 36 14 30 16 42 34 18 19 11 3 1 37 39 12 38 40 8 33 35 25 4 32 20 6 9 5 15 13 31 26 29 28 27 2
23 18 25 42 27 5 1 38 34 12 31 15 32 20 40 6 19 10 28 30 13 3 8 7 4 2 29 26 36 9 17 21 24 37 33 35 39 22 11 16 14 41
28 11 40 35 36 42 16 25 13 19 4 5 39 26 20 12 15 41 37 34 38 14 31 9 17 7 30 27 6 2 29 10 8 24 1 18 21 33 32 3 22 23
40 38 23 1 21 19 32 29 12 4 2 35 31 11 26 7 28 16 41 10 3 22 24 20 33 27 8 37 15 42 25 39 13 14 30 36 6 34 18 5 9 17
19 26 34 27 8 29 7 20 16 41 36 14 10 15 4 25 3 6 33 5 9 21 23 13 35 30 32 22 37 38 18 17 31 11 12 40 1 42 24 39 2 28
35 29 10 33 13 31 39 1 9 21 38 11 36 30 14 40 42 17 2 20 41 27 6 19 18 22 3 12 5 26 24 16 28 7 8 23 37 15 25 34 4 32
10 35 33 21 4 3 2 30 25 40 39 12 1 37 31 20 24 28 42 8 14 26 32 23 9 16 6 38 22 34 41 19 11 18 29 17 7 13 15 27 36 5
15 5 13 25 9 2 17 40 27 35 42 37 16 8 39 31 41 23 36 1 32 10 7 28 30 19 33 21 20 29 4 18 38 6 11 34 24 3 22 26 12 14
22 39 16 4 41 1 38 11 5 26 10 23 15 14 35 3 8 29 30 13 28 6 12 25 7 20 40 17 32 27 9 42 18 34 19 2 33 24 37 36 31 21
9 3 38 15 25 34 12 21 1 20 5 40 17 24 33 2 27 14 8 29 18 30 19 41 16 10 26 36 35 28 6 32 37 42 7 22 13 11 4 31 23 39
37 10 14 40 12 36 18 3 39 6 35 29 24 38 41 9 23 25 31 21 19 2 42 34 26 8 27 1 30 7 33 13 15 28 32 20 4 16 5 11 17 22
29 20 7 13 38 18 30 37 23 17 34 22 28 31 25 11 14 2 15 12 24 16 36 4 5 9 21 3 27 35 1 40 39 8 42 32 10 19 26 33 41 6
12 21 42 18 7 39 27 36 8 34 37 28 23 17 13 24 30 32 35 3 20 29 14 11 41 31 15 5 16 6 19 25 33 22 26 38 9 2 10 40 1 4
42 4 30 36 1 16 23 15 32 9 3 10 27 35 7 38 22 21 11 2 26 24 39 29 28 6 34 41 25 40 13 20 19 33 5 37 12 17 14 8 18 31
38 8 19 17 33 40 4 31 15 2 28 6 22 7 1 35 10 11 29 25 27 5 3 14 34 12 41 20 39 18 42 30 36 26 24 9 16 21 23 37 32 13

Part 4: 100 latin squares of order 256:

Generated in 76.816295878 seconds.

```


[User]
Task

Simulate the countdown of a rocket launch from   **5**   down to   **0**   seconds,   and then display the moving, accelerating rocket on the standard output device as a simple ASCII art animation.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

Uses ANSI graphics. Works best in a 24 bit ANSI terminal at least 80x24, though bigger is better.

This is a very simple simulation. It assumes a constant ~2G+ acceleration in a gravitational field; so net +10 meters per second². It completely neglects the effects of air friction, impulse, snap, crackle & pop and has an unrealistically clean fuel burn (no contrail). It does however (unlike most of the entries at this time) start at the base of the terminal (on the ground) and go up, rather than starting at the top and dropping a contrail. It calculates and displays an accurate displacement and velocity over time and uses those to scale its vertical screen displacement.

The motion is a little "notchy" as the vertical resolution in a terminal is rather low. Exits after the rocket leaves the visible area of the terminal. See the example animated gif

```
signal(SIGINT).tap: { cleanup() }

my ($rows,$cols) = qx/stty size/.words;
my $v = floor $rows - 9;
my $h = floor $cols / 2 - 4;
my $a = 0;
my $start = now;
my $t = -5;
my $i = 0;
my $j = 0;

my @r = Q'   |',   Q'  /_\',  Q'  | |',  Q' /| |\', Q'/_|_|_\';
my @x = Q' (/|\)', Q' {/|\}', Q'  \|/',  Q'   |';
my @y = Q'  /|\',  Q' // \\', Q' (/ \)', Q'  \ /'; #'

my $sp = ' ' x $h;

my $altitude = 0;
my $velocity = 0;

my @pal = "\e[38;2;255;0;0m", "\e[38;2;255;255;0m", "\e[38;2;255;155;0m";
constant \W = "\e[38;2;255;255;255m";

print "\e[?25l\e[48;5;232m";

loop {
    if $t >= 0 {
        $velocity = 5 * $t²;
        $altitude = $velocity * $t / 2;
        $a = ($altitude / $v).round;
    }
    cleanup() if $a > $rows + 5;

    print "\e[H\e[J", "\n" xx $v, W, $sp, @r.join("\n$sp"), "\n", $sp;
    if $t < 0 {
        print Q'\/   \/'
    } else {
        exhaust( @pal[$i], $a )
    }
    print W, "\n", '▔' x $cols, @pal[1];
    printf "\n Time: T %-4s %9s  Altitude: %6.2f meters  Velocity: %5.1f m/sec\n",
    $t < 0 ?? "- {$t.round.abs}" !! "+ {$t.round}",
    $t < 0 ?? '' !! $a == 0 ?? 'Ignition!' !! 'Lift-off!',
    $altitude.round(.01), $velocity.round(.1);

    ++$i;
    $i %= 3;
    ++$j;
    $j %= 2;
    $t = (now - $start - 5);
    sleep .05;
}

sub exhaust ($clr, $a) {
    print Q'\/', $clr, Q'/^\', W, Q'\/'; #'
    return if $a == 0;
    if $a < 4 {
        print "\n", $clr,
        $sp, ( $j ?? @x[^$a].join("\n$sp") !! @y[^$a].join("\n$sp"))
    } else {
        print "\n", $clr,
        $sp, ( $j ?? @x.join("\n$sp") !! @y.join("\n$sp"));
        print "\n" x $a - 4;
    }
}

# clean up on exit, reset ANSI codes, scroll, re-show the cursor & clear screen
sub cleanup () {  print "\e[0m", "\n" xx 50, "\e[H\e[J\e[?25h"; exit(0) }

```

Sample output:

See rocket-perl6.gif (offsite animated gif image)


[User]
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:

```
           A2 + B2 - 2ABcos(γ) = C2

```

Specific angles

For an angle of of   **90º**   this becomes the more familiar "Pythagoras equation":

```
           A2 + B2  =  C2

```

For an angle of   **60º**   this becomes the less familiar equation:

```
           A2 + B2 - AB  =  C2

```

And finally for an angle of   **120º**   this becomes the equation:

```
           A2 + B2 + AB  =  C2

```

Task

* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.
* Restrain all sides to the integers   **1..13**   inclusive.
* Show how many results there are for each of the three angles mentioned above.
* Display results on this page.

Note: Triangles with the same length sides but different order are to be treated as the same.

Optional Extra credit

* How many 60° integer triples are there for sides in the range 1..10\_000 *where the sides are not all of the same length*.

Related Task

* Pythagorean triples

See also

* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video

[Assistant]
(formerly Perl 6)
In each routine, race is used to allow concurrent operations, requiring the use of the atomic increment operator, ⚛++, to safely update @triples, which must be declared fixed-sized, as an auto-resizing array is not thread-safe. At exit, default values in @triples are filtered out with the test `!eqv Any`.

```
multi triples (60, $n) {
    my %sq = (1..$n).map: { .² => $_ };
    my atomicint $i = 0;
    my @triples[2*$n];
    (1..^$n).race(:8degree).map: -> $a {
        for $a^..$n -> $b {
            my $cos = $a * $a + $b * $b - $a * $b;
            @triples[$i⚛++] = $a, %sq{$cos}, $b if %sq{$cos}:exists;
        }
    }
    @triples.grep: so *;
}

multi triples (90, $n) {
    my %sq = (1..$n).map: { .² => $_ };
    my atomicint $i = 0;
    my @triples[2*$n];
    (1..^$n).race(:8degree).map: -> $a {
        for $a^..$n -> $b {
            my $cos = $a * $a + $b * $b;
            @triples[$i⚛++] = $a, $b, %sq{$cos} and last if %sq{$cos}:exists;
        }
    }
    @triples.grep: so *;
}

multi triples (120, $n) {
    my %sq = (1..$n).map: { .² => $_ };
    my atomicint $i = 0;
    my @triples[2*$n];
    (1..^$n).race(:8degree).map: -> $a {
        for $a^..$n -> $b {
            my $cos = $a * $a + $b * $b + $a * $b;
            @triples[$i⚛++] = $a, $b, %sq{$cos} and last if %sq{$cos}:exists;
        }
    }
    @triples.grep: so *;
}

use Sort::Naturally;

my $n = 13;
say "Integer triangular triples for sides 1..$n:";
for 120, 90, 60 -> $angle {
    my @itt = triples($angle, $n);
    if $angle == 60 { push @itt, "$_ $_ $_" for 1..$n }
    printf "Angle %3d° has %2d solutions: %s\n", $angle, +@itt, @itt.sort(&naturally).join(', ');
}

my ($angle, $count) = 60, 10_000;
say "\nExtra credit:";
say "$angle° integer triples in the range 1..$count where the sides are not all the same length: ", +triples($angle, $count);

```

Output:

```
Integer triangular triples for sides 1..13:
Angle 120° has  2 solutions: 3 5 7, 7 8 13
Angle  90° has  3 solutions: 3 4 5, 5 12 13, 6 8 10
Angle  60° has 15 solutions: 1 1 1, 2 2 2, 3 3 3, 3 7 8, 4 4 4, 5 5 5, 5 7 8, 6 6 6, 7 7 7, 8 8 8, 9 9 9, 10 10 10, 11 11 11, 12 12 12, 13 13 13

Extra credit:
60° integer triples in the range 1..10000 where the sides are not all the same length: 18394
```


[User]
Task

Determine whether a given year is a leap year in the Gregorian calendar.

See also

* Leap year (wiki)

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2010.07

```
say "$year is a {Date.is-leap-year($year) ?? 'leap' !! 'common'} year."
```

In Rakudo 2010.07, `Date.is-leap-year` is implemented as

```
multi method is-leap-year($y = $!year) {
    $y %% 4 and not $y %% 100 or $y %% 400
}
```


[User]
Task

Compute the   least common multiple   (LCM)   of two integers.

Given   *m*   and   *n*,   the least common multiple is the smallest positive integer that has both   *m*   and   *n*   as factors.

Example

The least common multiple of   **12**   and   **18**   is   **36**,       because:

:   * **12**   is a factor     (**12** × **3** = **36**),     and
    * **18**   is a factor     (**18** × **2** = **36**),     and
    * there is no positive integer less than   **36**   that has both factors.

As a special case,   if either   *m*   or   *n*   is zero,   then the least common multiple is zero.

One way to calculate the least common multiple is to iterate all the multiples of   *m*,   until you find one that is also a multiple of   *n*.

If you already have   *gcd*   for greatest common divisor,   then this formula calculates   *lcm*.

:   :   :   :   lcm

                (
                m
                ,
                n
                )
                =

                |
                m
                ×
                n

                |

                gcd

                (
                m
                ,
                n
                )
                {\displaystyle {\displaystyle \operatorname {lcm} (m,n)={\frac {|m\times n|}{\operatorname {gcd} (m,n)}}}}

One can also find   *lcm*   by merging the prime decompositions of both   *m*   and   *n*.

Related task
:   * greatest common divisor.

See also

* MathWorld entry:   Least Common Multiple.
* Wikipedia entry:   Least common multiple.

[Assistant]
(formerly Perl 6)
This function is provided as an infix so that it can be used productively with various metaoperators.

```
say 3 lcm 4;            # infix
say [lcm] 1..20;        # reduction
say ~(1..10 Xlcm 1..10) # cross

```

Output:

```
12
232792560
1 2 3 4 5 6 7 8 9 10 2 2 6 4 10 6 14 8 18 10 3 6 3 12 15 6 21 24 9 30 4 4 12 4 20 12 28 8 36 20 5 10 15 20 5 30 35 40 45 10 6 6 6 12 30 6 42 24 18 30 7 14 21 28 35 42 7 56 63 70 8 8 24 8 40 24 56 8 72 40 9 18 9 36 45 18 63 72 9 90 10 10 30 20 10 30 70 40 90 10
```


[User]
Find the minimum positive integer **m** such that **n** factorial plus **m** is prime.

E.G.

```
   0! = 1. The next prime greater than 1 is 2. 2 - 1 = 1, so a(0) = 1.
   1! = 1. The next prime greater than 1 is 2. 2 - 1 = 1, so a(1) = 1.
   2! = 2. The next prime greater than 2 is 3. 3 - 2 = 1, so a(2) = 1.
   3! = 6. The next prime greater than 6 is 7. 7 - 6 = 1, so a(3) = 1.
   4! = 24. The next prime greater than 24 is 29. 29 - 24 = 5, so a(4) = 5.

```

and so on...

Task

* Find and display the first fifty terms in the series. (**0!** through **49!**)
* Find and display the position and value of the first **m** greater than **1000**.

Stretch

* Find and display the position and value of each the first **m** greater than **2000, 3000, 4000** ... **10,000**.

See also

* OEIS:A033932 - Least positive m such that n! + m is prime

[Assistant]
```
my @f = lazy flat 1, [\×] 1..*;

sink @f[700]; # pre-reify for concurrency

my @least-m = lazy (^∞).hyper(:2batch).map: {(1..*).first: -> \n {(@f[$_] + n).is-prime}};

say "Least positive m such that n! + m is prime; first fifty:\n"
 ~ @least-m[^50].batch(10)».fmt("%3d").join: "\n";

for (1..10).map: * × 1e3 {
    my $key = @least-m.first: * > $_, :k;
    printf "\nFirst m > $_ is %d at position %d\n", @least-m[$key], $key;
}

```

Output:

```
Least positive m such that n! + m is prime; first fifty:
  1   1   1   1   5   7   7  11  23  17
 11   1  29  67  19  43  23  31  37  89
 29  31  31  97 131  41  59   1  67 223
107 127  79  37  97  61 131   1  43  97
 53   1  97  71  47 239 101 233  53  83

First m > 1000 is 1069 at position 107

First m > 2000 is 3391 at position 192

First m > 3000 is 3391 at position 192

First m > 4000 is 4943 at position 284

First m > 5000 is 5233 at position 384

First m > 6000 is 6131 at position 388

First m > 7000 is 9067 at position 445

First m > 8000 is 9067 at position 445

First m > 9000 is 9067 at position 445

First m > 10000 is 12619 at position 599
```


[User]
**Left factorials**,   !n,   may refer to either   *subfactorials*   or to   *factorial sums*;

the same notation can be confusingly seen being used for the two different definitions.

Sometimes,   *subfactorials*   (also known as *derangements*)   may use any of the notations:

:   :   :   :   :   :   :   * **!*n*`**
                            * **!*n***
                            * ***n*¡**

(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)

This Rosetta Code task will be using this formula   (*factorial sums*)   for   **left factorial**:

:   :   :   :   :   !
                    n
                    =

                    ∑

                    k
                    =
                    0

                    n
                    −
                    1
                    k
                    !
                    {\displaystyle {\displaystyle !n=\sum \_{k=0}^{n-1}k!}}

:   :   :   :   where

:   :   :   :   :   !
                    0
                    =
                    0
                    {\displaystyle {\displaystyle !0=0}}

Task

Display the left factorials for:

* zero through ten     (inclusive)
* 20   through   110   (inclusive)   by tens

Display the length (in decimal digits) of the left factorials for:

* 1,000   through   10,000   (inclusive), by thousands.

Also see

* The OEIS entry: A003422 left factorials
* The MathWorld entry: left factorial
* The MathWorld entry: factorial sums
* The MathWorld entry: subfactorial

Related task

* permutations/derangements (subfactorials)

[Assistant]
(formerly Perl 6)

Implement left factorial as a prefix !. Note that this redefines the core prefix ! (not) function.

```
sub prefix:<!> ($k) { (constant l = 0, |[\+] 1, (|[\*] 1..*))[$k] }

$ = !10000; # Pre-initialize

.say for ( 0 … 10, 20 … 110 ).hyper(:4batch).map: { sprintf "!%d  = %s", $_, !$_ };
.say for (1000, 2000 … 10000).hyper(:4batch).map: { sprintf "!%d has %d digits.", $_, chars !$_ };

```

Output:

```
!0  = 0
!1  = 1
!2  = 2
!3  = 4
!4  = 10
!5  = 34
!6  = 154
!7  = 874
!8  = 5914
!9  = 46234
!10  = 409114
!20  = 128425485935180314
!30  = 9157958657951075573395300940314
!40  = 20935051082417771847631371547939998232420940314
!50  = 620960027832821612639424806694551108812720525606160920420940314
!60  = 141074930726669571000530822087000522211656242116439949000980378746128920420940314
!70  = 173639511802987526699717162409282876065556519849603157850853034644815111221599509216528920420940314
!80  = 906089587987695346534516804650290637694024830011956365184327674619752094289696314882008531991840922336528920420940314
!90  = 16695570072624210767034167688394623360733515163575864136345910335924039962404869510225723072235842668787507993136908442336528920420940314
!100  = 942786239765826579160595268206839381354754349601050974345395410407078230249590414458830117442618180732911203520208889371641659121356556442336528920420940314
!110  = 145722981061585297004706728001906071948635199234860720988658042536179281328615541936083296163475394237524337422204397431927131629058103519228197429698252556442336528920420940314
!1000 has 2565 digits.
!2000 has 5733 digits.
!3000 has 9128 digits.
!4000 has 12670 digits.
!5000 has 16322 digits.
!6000 has 20062 digits.
!7000 has 23875 digits.
!8000 has 27749 digits.
!9000 has 31678 digits.
!10000 has 35656 digits.
```

If you would rather not override prefix ! operator and you can live with just defining lazy lists and indexing into them, this should suffice; (and is in fact very slightly faster than the first example since it avoids routine dispatch overhead):

```
constant leftfact = 0, |[\+] 1, (|[\*] 1..*);

$ = leftfact[10000]; # Pre-initialize

.say for ( 0 … 10, 20 … 110 ).hyper(:4batch).map: { sprintf "!%d  = %s", $_, leftfact[$_] };
.say for (1000, 2000 … 10000).hyper(:4batch).map: { sprintf "!%d has %d digits.", $_, chars leftfact[$_] };

```

Same output.


[User]
The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.

To calculate:

Define

```
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.

```

then

```
π(n) = 0 when n < 2
π(n) = φ(n, a) + a - 1, where a = π(√n), n ≥ 2

```

The Legendre formula still requires the use of a sieve to enumerate primes; however it's only required to sieve up to the √n, and for counting primes, the Legendre method is generally much faster than sieving up to n.

Task

Calculate π(n) for values up to 1 billion. Show π(n) for n = 1, 10, 100, ... 109.

For this task, you may refer to a prime number sieve (such as the Sieve of Eratosthenes or the extensible sieve) in an external library to enumerate the primes required by the formula. Also note that it will be necessary to memoize the results of φ(x, a) in order to have reasonable performance, since the recurrence relation would otherwise take exponential time.

**Comments on Task**

Regarding "it will be necessary to memoize the results of φ(x, a)", it will have exponential time performance without memoization only if a very small optimization that should be obvious is not done: it should be obvious that one can stop "splitting" the φ(x, a) "tree" when 'x' is zero, and even before that since the real meaning of the "phi"/φ function is to produce a count of all of the values greater than zero (including one) up to `x` that have been culled of all multiples of the primes up to and including the `pa` prime value, if `x` is less than or equal to `pa`, then the whole "tree" must result in a value of just one. If this minor (and obvious) optimization is done, the "exponential time" performance goes away, memoization is not absolutely necessary (saving the overhead in time and space of doing the memoization), and the time complexity becomes O(n/(log n2) and the space complexity becomes O(n1/2/log n) as they should be.

This is the problem when non-mathematician programmers blindly apply such a general formula as the recursive Legendre one without doing any work to understand it or even doing some trivial hand calculations to better understand how it works just because they have very powerful computers which mask the limitations: a few minutes of hand calculation would make it obvious that there is no need to "split"/recursively call for "phi" nodes where the first argument is zero, and someone with a mathematics interest would then investigate to see if that limit can be pushed a little further as here to the range of nodes whose result will always be one. Once there is no exponential growth of the number of "nodes", then there is no need for memoization as usually implemented with a hash table at a huge cost of memory overhead and constant time computation per operation.

As to "the Legendre method is generally much faster than sieving up to n.", while the number of operations for the Legendre algorithm is about a factor of `log n` squared less than the number of operations for odds-only Sieve of Eratosthenes (SoE) sieving, those operations are "divide" operations which are generally much slower than the simple array access and addition operations used in sieving and the SoE can be optimized further using wheel factorization so that the required time for a given range can be less for a fully optimized SoE than for the common implementation of the Legendre algorithm; the trade off is that a fully optimized SoE is at least 500 lines of code, whereas the basic version of the Legendre prime counting algorithm is only about 40 to 50 lines of code (depending somewhat on the language used).

Also note that the Legendre prime counting function was never used practically at the time it was invented other than to demonstrate that it would find the count of primes to a trivial range only knowing the primes up to the square root of that range and there were too many operations (especially long integer division operations) to actually use it for any reasonably range even with this optimization (about 250 thousand divisions to count primes to ten million), but the follow-on work by Meissel in the 1800's definitely would have used this optimization and others in order to hand calculate the number of primes to a billion (1e9) in about ten years. Even with this optimization, Meissel would have had to hand calculate over five million divisions, so certainly used other Look Up Tables (LUT's) although certainly not caching of Phi/φ values in order to reduce the work to something possible in this amount of time. A "TinyPhi" LUT table for the first six primes of thirteen and less would have reduced the amount of work Meissel did to about 600 thousand divisions, but even that would have been perhaps too much and it is very likely that he also used "partial sieving" techniques, although that would have meant that as well as a table of the primes up to a million, he would have also needed 161 other tables of that range to a million sieved by the primes up to 13, 17, 19, to 997; however, that extra work in building these tables (which might have been done mechanically) would pay off in reducing the number of divisions to about seven thousand so the divisions become a minor problem possible to do over months and the majority of the time would be spent producing the partial sieving tables up to a million.

The reason that Meissel refined the Legendre method would have been that, even applying all of the optimizations including "partial sieving", he would still have had to do about three and a half million divisions to count the primes to a billion even if the number of primes and "partial sieve tables" only needed to be known to about 32 thousand, where his "Meissel" algorithm reduced the number of divisions to only a few thousand as per the above. Without a computer, he could never have completed the calculation of the number of primes to a billion using an optimized Legendre algorithm where he could using his modification. However, modern computers make (reasonably) quick work of integer divisions so that optimized algorithms of the Legendre type become moderately useful although at the cost of memory use as compared to Meissel type algorithms.

[Assistant]
Seems like an awful lot of pointless work. Using prime sieve anyway, why not just use it?

```
use Math::Primesieve;

my $sieve = Math::Primesieve.new;

say "10^$_\t" ~ $sieve.count: exp($_,10) for ^10;

say (now - INIT now) ~ ' elapsed seconds';

```

Output:

```
10^0	0
10^1	4
10^2	25
10^3	168
10^4	1229
10^5	9592
10^6	78498
10^7	664579
10^8	5761455
10^9	50847534
0.071464489 elapsed seconds

```


[User]
Task

Write a method (function, procedure etc.) in your language which calculates the length of the major arc of a circle of given radius between two angles.

In this diagram the major arc is colored green   (note: this website leaves cookies).

Illustrate the use of your method by calculating the length of the major arc of a circle of radius 10 units, between angles of 10 and 120 degrees.

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

Taking a slightly different approach. Rather than the simplest thing that
could possibly work, implements a reusable arc-length routine. Standard notation
for angles has the zero to the right along an 'x' axis with a
counter-clockwise rotation for increasing angles. This version follows
convention and assumes the first given angle is "before" the second when
rotating counter-clockwise. In order to return the major swept angle in the
task example, you need to supply the "second" angle first. (The measurement
will be from the first given angle counter-clockwise to the second.)

If you don't supply a radius, returns the radian arc angle which may then be
multiplied by the radius to get actual circumferential length.

Works in radian angles by default but provides a postfix ° operator to convert
degrees to radians and a postfix ᵍ to convert gradians to radians.

```
sub arc ( Real \a1, Real \a2, :r(:$radius) = 1 ) {
    ( ([-] (a2, a1).map((* + τ) % τ)) + τ ) % τ × $radius
}

sub postfix:<°> (\d) { d × τ / 360 }
sub postfix:<ᵍ> (\g) { g × τ / 400 }

say 'Task example: from 120° counter-clockwise to 10° with 10 unit radius';
say arc(:10radius, 120°, 10°), ' engineering units';

say "\nSome test examples:";
for \(120°, 10°), # radian magnitude (unit radius)
    \(10°, 120°), # radian magnitude (unit radius)
    \(:radius(10/π), 180°, -90°), # 20 unit circumference for ease of comparison
    \(0°, -90°, :r(10/π),),       #  ↓  ↓  ↓  ↓  ↓  ↓  ↓
    \(:radius(10/π), 0°, 90°),
    \(π/4, 7*π/4, :r(10/π)),
    \(175ᵍ, -45ᵍ, :r(10/π)) {  # test gradian parameters
    printf "Arc length: %8s  Parameters: %s\n", arc(|$_).round(.000001), $_.raku
}

```

Output:

```
Task example: from 120° counter-clockwise to 10° with 10 unit radius
43.63323129985824 engineering units

Some test examples:
Arc length: 4.363323  Parameters: \(2.0943951023931953e0, 0.17453292519943295e0)
Arc length: 1.919862  Parameters: \(0.17453292519943295e0, 2.0943951023931953e0)
Arc length:        5  Parameters: \(3.141592653589793e0, -1.5707963267948966e0, :radius(3.183098861837907e0))
Arc length:       15  Parameters: \(0e0, -1.5707963267948966e0, :r(3.183098861837907e0))
Arc length:        5  Parameters: \(0e0, 1.5707963267948966e0, :radius(3.183098861837907e0))
Arc length:       15  Parameters: \(0.7853981633974483e0, 5.497787143782138e0, :r(3.183098861837907e0))
Arc length:        9  Parameters: \(2.7488935718910685e0, -0.7068583470577035e0, :r(3.183098861837907e0))
```


[User]
*Leonardo numbers*   are also known as the   *Leonardo series*.

The   **Leonardo numbers**   are a sequence of numbers defined by:

```
       L(0) = 1                                          [1st equation]
       L(1) = 1                                          [2nd equation]
       L(n) = L(n-1)  +    L(n-2)   +  1                 [3rd equation]
                    ─── also ───
       L(n) =      2  *  Fib(n+1)   -  1                 [4th equation]

```

:   :   :   :   where the   **+ 1**   will herein be known as the   *add*   number.
            :   where the   **FIB**   is the   Fibonacci numbers.

This task will be using the 3rd equation (above) to calculate the Leonardo numbers.

Edsger W. Dijkstra   used   Leonardo numbers   as an integral part of
his   smoothsort   algorithm.

The first few Leonardo numbers are:

```
    1   1   3   5   9   15   25   41   67   109   177   287   465   753   1219   1973   3193   5167   8361  ···

```

Task
:   :   * show the 1st   **25**   Leonardo numbers, starting at **L(0)**.
        * allow the first two Leonardo numbers to be specified   [for **L(0)** and **L(1)**].
        * allow the   *add*   number to be specified   (**1** is the default).
        * show the 1st   **25**   Leonardo numbers, specifying **0** and **1** for **L(0)** and **L(1)**, and **0** for the *add* number.

(The last task requirement will produce the Fibonacci numbers.)

Show all output here on this page.

Related tasks

* Fibonacci number
* Fibonacci n-step number sequences

See also

* Wikipedia, Leonardo numbers
* Wikipedia, Fibonacci numbers
* OEIS Leonardo numbers

[Assistant]
(formerly Perl 6)

```
sub 𝑳 ( $𝑳0 = 1, $𝑳1 = 1, $𝑳add = 1 ) { $𝑳0, $𝑳1, { $^n2 + $^n1 + $𝑳add } ... * }

# Part 1
say "The first 25 Leonardo numbers:";
put 𝑳()[^25];

# Part 2
say "\nThe first 25 numbers using 𝑳0 of 0, 𝑳1 of 1, and adder of 0:";
put 𝑳( 0, 1, 0 )[^25];

```

Output:

```
The first 25 Leonardo numbers:
1 1 3 5 9 15 25 41 67 109 177 287 465 753 1219 1973 3193 5167 8361 13529 21891 35421 57313 92735 150049

The first 25 numbers using 𝑳0 of 0, 𝑳1 of 1, and adder of 0:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368
```


[User]
Task

Open a text file and count the occurrences of each letter.

Some of these programs count all characters (including punctuation),
but some only count letters A to Z.

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)

In Raku, whenever you want to count things in a collection, the rule of thumb is to use the Bag structure.

*In response to some of the breathless exposition in the Frink entry.*

* Has a Unicode-aware function, which intelligently enumerates through what a human would consider to be a single visible character. - Raku doesn't have **a** special Unicode aware string processing function, rather **all** of Rakus text/string wrangling functions are Unicode aware by default.

* Unicode-aware lowercase function. - See above: lowercase, uppercase, fold-case, title-case, all Unicode aware by default.

* Uses full Unicode tables to determine what is a "letter." - Um... Yeah, Unicode aware by default.

* Works with high Unicode characters, that is above \uFFFF. - OK, now we're just repeating ourselves.

* Normalize Unicode characters with its normalizeUnicode function. - Raku; normalized by default.

* Implements all of (NFC, NFD, NFKC, NFKD). NFC is the default. - Yep.

"How many other languages in this page do all or any of this correctly?" Quite a few I suspect. Some even moreso than Frink.

```
.&ws.say for slurp.comb.Bag.sort: -*.value;

sub ws ($pair) {
    $pair.key ~~ /\n/
    ?? ('NEW LINE' => $pair.value)
    !! $pair.key ~~ /\s/
    ?? ($pair.key.uniname => $pair.value)
    !! $pair
}

```

Output when fed the same Les Misérables text file as used in the Word frequency task:

```
SPACE => 522095
e => 325692
t => 222916
a => 199790
o => 180974
h => 170210
n => 167006
i => 165201
s => 157585
r => 145118
d => 106987
l => 97131
NEW LINE => 67662
u => 67340
c => 62717
m => 56021
f => 53494
w => 53301
, => 48784
g => 46060
p => 39932
y => 37985
b => 34276
. => 30589
v => 24045
" => 14340
k => 14169
T => 12547
- => 11037
I => 10067
A => 7355
H => 6600
M => 6206
; => 5885
E => 4968
C => 4583
S => 4392
' => 3938
x => 3692
! => 3539
R => 3531
P => 3424
O => 3401
j => 3390
B => 3185
W => 3180
N => 3053
? => 2976
F => 2754
G => 2508
: => 2468
J => 2448
L => 2444
q => 2398
V => 2200
_ => 2070
z => 1847
D => 1756
é => 1326
Y => 1238
U => 895
1 => 716
8 => 412
X => 333
K => 321
è => 292
3 => 259
2 => 248
5 => 220
0 => 218
* => 181
4 => 181
) => 173
( => 173
6 => 167
É => 146
7 => 143
Q => 135
] => 122
[ => 122
9 => 117
æ => 106
= => 75
ê => 74
Z => 59
à => 59
â => 56
> => 50
< => 50
/ => 50
ç => 48
NO-BREAK SPACE => 45
î => 39
ü => 37
| => 36
ô => 34
# => 26
ù => 18
ï => 18
Æ => 10
û => 9
+ => 5
È => 5
ë => 5
À => 4
@ => 2
ñ => 2
Ç => 2
$ => 2
% => 1
& => 1
{ => 1
} => 1
½ => 1

```


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

In information theory and computer science, the **Levenshtein distance** is a metric for measuring the amount of difference between two sequences (i.e. an edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.

Example

The Levenshtein distance between "**kitten**" and "**sitting**" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:

:   :   1. **k**itten   **s**itten   (substitution of 'k' with 's')
        2. sitt**e**n   sitt**i**n   (substitution of 'e' with 'i')
        3. sittin   sittin**g**   (insert 'g' at the end).

*The Levenshtein distance between   "**rosettacode**",   "**raisethysword**"   is   **8**.*

*The distance between two strings is same as that when both strings are reversed.*

Task

Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between   "kitten"   and   "sitting".

Related task

* Longest common subsequence

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)

Implementation of the Wikipedia algorithm. Since column 0 and row 0 are used for base distances, the original algorithm would require us to compare "@s[$i-1] eq @t[$j-1]", and reference $m and $n separately. Prepending an unused value (undef) onto @s and @t makes their indices align with the $i,$j numbering of @d, and lets us use .end instead of $m,$n.

```
sub levenshtein-distance ( Str $s, Str $t --> Int ) {
    my @s = *, |$s.comb;
    my @t = *, |$t.comb;

    my @d;
    @d[$_;  0] = $_ for ^@s.end;
    @d[ 0; $_] = $_ for ^@t.end;

    for 1..@s.end X 1..@t.end -> ($i, $j) {
        @d[$i; $j] = @s[$i] eq @t[$j]
            ??   @d[$i-1; $j-1]    # No operation required when eq
            !! ( @d[$i-1; $j  ],   # Deletion
                 @d[$i  ; $j-1],   # Insertion
                 @d[$i-1; $j-1],   # Substitution
               ).min + 1;
    }

    @d[*-1][*-1];
}

for <kitten sitting>, <saturday sunday>, <rosettacode raisethysword> -> ($s, $t) {
    say "Levenshtein distance('$s', '$t') == ", levenshtein-distance($s, $t)
}
```

Output:

```
Levenshtein distance('kitten', 'sitting') == 3
Levenshtein distance('saturday', 'sunday') == 3
Levenshtein distance('rosettacode', 'raisethysword') == 8
```


[User]
The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.

An alignment is a notation used to describe the operations used to turn a string into an other. At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place. For instance, an alignment between the words 'place' and 'palace' is:

```
P-LACE
PALACE

```

Task

Write a function that shows the alignment of two strings for the corresponding levenshtein distance.

As an example, use the words "rosettacode" and "raisethysword".

You can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

```
sub align ( Str $σ, Str $t ) {
    my @s = flat *, $σ.comb;
    my @t = flat *, $t.comb;

    my @A;
    @A[$_][ 0]<d s t> = $_, @s[1..$_].join, '-' x $_ for ^@s;
    @A[ 0][$_]<d s t> = $_, '-' x $_, @t[1..$_].join for ^@t;

    for 1 ..^ @s X 1..^ @t -> (\i, \j) {
	if @s[i] ne @t[j] {
	    @A[i][j]<d> = 1 + my $min =
	    min @A[i-1][j]<d>, @A[i][j-1]<d>, @A[i-1][j-1]<d>;
	    @A[i][j]<s t> =
	    @A[i-1][j]<d> == $min ??  (@A[i-1][j]<s t> Z~ @s[i], '-') !!
	    @A[i][j-1]<d> == $min ??  (@A[i][j-1]<s t> Z~ '-', @t[j]) !!
	    (@A[i-1][j-1]<s t> Z~ @s[i], @t[j]);
	} else {
	    @A[i][j]<d s t> = @A[i-1][j-1]<d s t> Z~ '', @s[i], @t[j];
	}
    }

    return @A[*-1][*-1]<s t>;
}

.say for align 'rosettacode', 'raisethysword';

```

Output:

```
ro-settac-o-de
raisethysword-
```


[User]
In plane geometry, a line (or segment) may intersect a circle at 0, 1 or 2 points.

Task

Implement a method (function, procedure etc.) in your language which takes as parameters:

* the starting point of a line;
* the point where the line ends;
* the center point of a circle;
* the circle's radius; and
* whether the line is a segment or extends to infinity beyond the above points.

The method should return the intersection points (if any) of the circle and the line.

Illustrate your method with some examples (or use the Go examples below).

Stretch Task

Include results for a circle with center at (10, 10) and radius 5 combined with a line through points (5, 0) and (5, 20) and that same circle combined with a line segment from (-5, 10) to (5, 10).

References

* See Math Stack Exchange for development of the formulae needed.
* See Wolfram for the formulae needed.

[Assistant]
(formerly Perl 6)
Extend solution space to 3D. Reference: this SO question and answers

```
sub LineCircularOBJintersection(@P1, @P2, @Centre, \Radius) {
   my @d = @P2 »-« @P1 ;           # d
   my @f = @P1 »-« @Centre ;       # c

   my \a = [+] @d»²;               # d dot d
   my \b = 2 * ([+] @f »*« @d);    # 2 * f dot d
   my \c = ([+] @f»²) - Radius²;   # f dot f - r²
   my \Δ =  b²-(4*a*c);            # discriminant

   if (Δ < 0) {
      return [];
   } else {
      my (\t1,\t2) = (-b - Δ.sqrt)/(2*a), (-b + Δ.sqrt)/(2*a);
      if 0 ≤ t1|t2 ≤ 1 {
         return @P1 »+« ( @P2 »-« @P1 ) »*» t1, @P1 »+« ( @P2 »-« @P1 ) »*» t2
      } else {
         return []
      }
   }
}

my \DATA = [
   [ <-10 11>, < 10 -9>, <3 -5>, 3 ],
   [ <-10 11>, <-11 12>, <3 -5>, 3 ],
   [ <  3 -2>, <  7 -2>, <3 -5>, 3 ],
   [ <  3 -2>, <  7 -2>, <0  0>, 4 ],
   [ <  0 -3>, <  0  6>, <0  0>, 4 ],
   [ <  6  3>, < 10  7>, <4  2>, 5 ],
   [ <  7  4>, < 11 18>, <4  2>, 5 ],
   [ <5  2 −2.26 >, <0.77 2 4>, <1 4 0>, 4 ]
];

for DATA {
   my @solution = LineCircularOBJintersection $_[0] , $_[1] , $_[2], $_[3];
   say "For data set: ", $_;
   say "Solution(s) is/are: ", @solution.Bool ?? @solution !! "None";
}

```

Output:

```
For data set: [(-10 11) (10 -9) (3 -5) 3]
Solution(s) is/are: [(3 -2) (6 -5)]
For data set: [(-10 11) (-11 12) (3 -5) 3]
Solution(s) is/are: None
For data set: [(3 -2) (7 -2) (3 -5) 3]
Solution(s) is/are: [(3 -2) (3 -2)]
For data set: [(3 -2) (7 -2) (0 0) 4]
Solution(s) is/are: [(-3.4641016151377544 -2) (3.4641016151377544 -2)]
For data set: [(0 -3) (0 6) (0 0) 4]
Solution(s) is/are: [(0 -4) (0 4)]
For data set: [(6 3) (10 7) (4 2) 5]
Solution(s) is/are: [(1 -2) (8 5)]
For data set: [(7 4) (11 18) (4 2) 5]
Solution(s) is/are: [(5.030680985703315 -2.892616550038399) (7.459885052032535 5.60959768211387)]
For data set: [(5 2 −2.26) (0.77 2 4) (1 4 0) 4]
Solution(s) is/are: [(4.2615520237084015 2 -1.1671668246843006) (1.13386504516801 2 3.461514141193441)]

```