[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Euler's\_identity. 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 mathematics, *Euler's identity* is the equality:

```
               ei

            π

    {\displaystyle {\displaystyle \pi }}

 + 1 = 0

```

where

```
   e is Euler's number, the base of natural logarithms,
   i is the imaginary unit, which satisfies i2 = −1, and

            π

    {\displaystyle {\displaystyle \pi }}

 is pi, the ratio of the circumference of a circle to its diameter.

```

Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:

```
   The number 0.
   The number 1.
   The number

            π

    {\displaystyle {\displaystyle \pi }}

 (

            π

    {\displaystyle {\displaystyle \pi }}

 = 3.14159+),
   The number e (e = 2.71828+), which occurs widely in mathematical analysis.
   The number i, the imaginary unit of the complex numbers.

```

Task

Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.

Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.

If that is the case, or there is some other limitation, show
that ei

π
{\displaystyle {\displaystyle \pi }} + 1 is *approximately* equal to zero and
show the amount of error in the calculation.

If your language is capable of symbolic calculations, show
that ei

π
{\displaystyle {\displaystyle \pi }} + 1 is *exactly* equal to zero for bonus kudos points.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

Implementing an "invisible times" operator (Unicode character (U+2062)) to more closely emulate the layout. Alas, Raku does not do symbolic calculations at this time and is limited to IEEE 754 floating point for transcendental and irrational number calculations.

e, i and π are all available as built-in constants in Raku.

```
sub infix:<> is tighter(&infix:<**>) { $^a * $^b };

say 'e**iπ + 1 ≅ 0 : ', e**iπ + 1 ≅ 0;
say 'Error: ', e**iπ + 1;

```

Output:

```
e**iπ + 1 ≅ 0 : True
Error: 0+1.2246467991473532e-16i
```


[User]
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.

This conjecture is called Euler's sum of powers conjecture and can be stated as such:

:   At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.

In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.

The task consists in writing a program to search for an integer solution of

x

0

5
+

x

1

5
+

x

2

5
+

x

3

5
=

y

5
{\displaystyle {\displaystyle x\_{0}^{5}+x\_{1}^{5}+x\_{2}^{5}+x\_{3}^{5}=y^{5}}}
 where all

x

i
{\displaystyle {\displaystyle x\_{i}}}
 and

y
{\displaystyle {\displaystyle y}}
 are distinct integers between 0 and 250 (exclusive). Show an answer here.

Related tasks are:

* Pythagorean quadruples.
* Pythagorean triples.

[Assistant]
(formerly Perl 6)

**Translation of**: Python

```
constant MAX = 250;

my  %po5{Int};
my %sum2{Int};

for 1..MAX -> \i {
    %po5{i⁵} = i;
    for 1..MAX -> \j {
        %sum2{i⁵ + j⁵} = i, j;
    }
}

%po5.keys.sort.race.map: -> \p {
    for %sum2.keys.sort -> \s {
        if p > s and %sum2{p - s} {
            say ((sort |%sum2{s},|%sum2{p - s}) X~ '⁵').join(' + '), " = %po5{p}", "⁵" and exit
        }
    }
}

```

Output:

```
27⁵ + 84⁵ + 110⁵ + 133⁵ = 144⁵
```


[User]
This programming task, is to calculate ANY binomial coefficient.

However, it has to be able to output

(

5
3

)
{\displaystyle {\displaystyle {\binom {5}{3}}}}
,   which is   **10**.

This formula is recommended:

:   :   (

        n
        k

        )
        =

        n
        !

        (
        n
        −
        k
        )
        !
        k
        !
        =

        n
        (
        n
        −
        1
        )
        (
        n
        −
        2
        )
        …
        (
        n
        −
        k
        +
        1
        )

        k
        (
        k
        −
        1
        )
        (
        k
        −
        2
        )
        …
        1
        {\displaystyle {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}}

**See Also:**

* Combinations and permutations
* Pascal's triangle

:   :   :   :   The number of samples of size k from n objects.

                With   combinations and permutations   generation tasks.

                |  | Order Unimportant | Order Important |
                | --- | --- | --- |
                | Without replacement | (  n k  )  =  n  C  k =    n ( n − 1 ) … ( n − k + 1 )  k ( k − 1 ) … 1 {\displaystyle {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} \_{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}} | n  P  k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle {\displaystyle ^{n}\operatorname {P} \_{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}} |
                | Task: Combinations | Task: Permutations |
                | With replacement | (   n + k − 1 k  )  =  n + k − 1  C  k =    ( n + k − 1 ) !  ( n − 1 ) ! k ! {\displaystyle {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} \_{k}={(n+k-1)! \over (n-1)!k!}}} | n  k {\displaystyle {\displaystyle n^{k}}} |
                | Task: Combinations with repetitions | Task: Permutations with repetitions |

[Assistant]
(formerly Perl 6)
For a start, you can get the length of the corresponding list of combinations:

```
say combinations(5, 3).elems;

```

Output:

```
10
```

This method is efficient, as Raku will not actually compute each element of the list, since it actually uses an iterator with a defined count-only method. Such method performs computations in a way similar to the following infix operator:

```
sub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. $^p }
say 5 choose 3;
```

A possible optimization would use a symmetry property of the binomial coefficient:

```
sub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. min($n - $^p, $p) }
```

One drawback of this method is that it returns a Rat, not an Int. So we actually may want to enforce the conversion:

```
sub infix:<choose> { ([*] ($^n ... 0) Z/ 1 .. min($n - $^p, $p)).Int }
```

And *this* is exactly what the count-only method does.


[User]
In 1742, Goldbach and Euler corresponded about what is now known as the Goldbach Conjecture: that all even integers greater than 2 can be written as the sum of two primes.

In 2000, Henry Dubner proposed a stronger conjecture: that every even integer greater than 4208 can be written as the sum of two twin primes.

At the time the Goldbach conjecture was made, 1 was considered a prime number - this is not so now. So, the Goldbach conjecture was originally that all even natural numbers could be written as the sum of two primes.

Task

* Find and display the positive even integers that cannot be expressed as the sum of two twin primes, up to a limit of 5,000.

:   :   E.g.: The first 3 twin primes are 3, 5 and 7, so 6 (3+3), 8 (5+3) and 10 (5+5 or 7+3) can be formed but 2 and 4 cannot.

* Show the numbers that cannot be formed by summing two twin primes when 1 is treated as a prime (and so a twin prime).

Note

* For the purposes of this task, twin prime refers to a prime that is 2 more or less than another prime, not the pair of primes.

Stretch

* Verify that there no more such numbers up to 10,000 or more, as you like (note it has been verified up to at least 10^9).

See also

* Wikipedia: Dubner's conjecture * Wikipedia: Goldbach's conjecture * OEIS:A007534 - Even numbers that are not the sum of a pair of twin primes. * Twin primes

[Assistant]
```
my $threshold = 10000;

my @twins = unique flat (3..$threshold).grep(&is-prime).map: { $_, $_+2 if ($_+2).is-prime };
my @sums;

map {++@sums[$_]}, (@twins X+ @twins);
display 'Non twin prime sums:', @sums;

map {++@sums[$_]}, flat 2, (1 X+ @twins);
display "\nNon twin prime sums (including 1):", @sums;

sub display ($msg, @p) {
    put "$msg\n" ~ @p[^$threshold].kv.map(-> $k, $v { $k if ($k %% 2) && !$v })\
    .skip(1).batch(10)».fmt("%4d").join: "\n"
}

```

Output:

```
Non twin prime sums:
   2    4   94   96   98  400  402  404  514  516
 518  784  786  788  904  906  908 1114 1116 1118
1144 1146 1148 1264 1266 1268 1354 1356 1358 3244
3246 3248 4204 4206 4208

Non twin prime sums (including 1):
  94   96   98  400  402  404  514  516  518  784
 786  788  904  906  908 1114 1116 1118 1144 1146
1148 1264 1266 1268 1354 1356 1358 3244 3246 3248
4204 4206 4208
```


[User]
Task

Test whether an integer is even or odd.

There is more than one way to solve this task:

* Use the even and odd predicates, if the language provides them.
* Check the least significant digit. With binary integers, *i bitwise-and 1* equals 0 iff *i* is even, or equals 1 iff *i* is odd.
* Divide *i* by 2. The remainder equals 0 iff *i* is even. The remainder equals +1 or -1 iff *i* is odd.
* Use modular congruences:
  + *i* ≡ 0 (mod 2) iff *i* is even.
  + *i* ≡ 1 (mod 2) iff *i* is odd.

[Assistant]
(formerly Perl 6)
Raku doesn't have a built-in for this, but with subsets it's easy to define a predicate for it.

```
subset Even of Int where * %% 2;
subset Odd of Int where * % 2;

say 1 ~~ Even; # false
say 1 ~~ Odd;  # true
say 1.5 ~~ Odd # false ( 1.5 is not an Int )
```


[User]
**Event** is a synchronization object. An event has two states *signaled* and *reset*. A task may await for the event to enter the desired state, usually the *signaled* state. It is released once the state is entered. Releasing waiting tasks is called *event notification*. Programmatically controlled events can be set by a task into one of its states.

In concurrent programming event also refers to a notification that some state has been reached through an asynchronous activity. The source of the event can be:

* *internal*, from another task, programmatically;
* *external*, from the hardware, such as user input, timer, etc. Signaling an event from the hardware is accomplished by means of hardware interrupts.

Event is a low-level synchronization mechanism. It neither identify the state that caused it signaled, nor the source of, nor who is the subject of notification. Events augmented by data and/or publisher-subscriber schemes are often referred as **messages**, **signals** etc.

In the context of general programming **event-driven architecture** refers to a design that deploy events in order to synchronize tasks with the asynchronous activities they must be aware of. The opposite approach is **polling** sometimes called **busy waiting**, when the synchronization is achieved by an explicit periodic querying the state of the activity. As the name suggests busy waiting consumes system resources even when the external activity does not change its state.

Event-driven architectures are widely used in GUI design and SCADA systems. They are flexible and have relatively short response times. At the same time event-driven architectures suffer to the problems related to their unpredictability. They face race condition, deadlocking, live locks and priority inversion. For this reason real-time systems tend to polling schemes, trading performance for predictability in the worst case scenario.

# Variants of events

## Manual-reset event

This event changes its state by an explicit request of a task. I.e. once signaled it remains in this state until it will be explicitly reset.

## Pulse event

A pulse event when signaled releases all tasks awaiting it and then is automatically reset.

# Sample implementations / APIs

Show how a manual-reset event can be implemented in the language or else use an API to a library that provides events. Write a program that waits 1s and then signals the event to a task waiting for the event.

[Assistant]
(formerly Perl 6)

**Translation of**: Go

```
note now, " program start";
my $event = Channel.new;

my $todo = start {
    note now, " task start";
    $event.receive;
    note now, " event reset by task";
}

note now, " program sleeping";
sleep 1;
note now, " program signaling event";
$event.send(0);
await $todo;

```

Output:

```
Instant:1403880984.089974 program start
Instant:1403880984.095400 program sleeping
Instant:1403880984.095491 task start
Instant:1403880985.099381 program signaling event
Instant:1403880985.109395 event reset by task
```

See also Handle\_a\_signal#Raku for an example of using Supplies to do reactive programming based on events (Unix signals in this case).


[User]
Starting with:

* The `target` string: `"METHINKS IT IS LIKE A WEASEL"`.
* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the `parent`).
* A `fitness` function that computes the ‘closeness’ of its argument to the target string.
* A `mutate` function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
* While the `parent` is not yet the `target`:

:   * copy the `parent` C times, each time allowing some random probability that another character might be substituted using `mutate`.
    * Assess the `fitness` of the parent and all the copies to the `target` and make the most fit string the new `parent`, discarding the others.
    * repeat until the parent converges, (hopefully), to the target.

See also

* Wikipedia entry:   Weasel algorithm.
* Wikipedia entry:   Evolutionary algorithm.

Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions

A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,

* While the `parent` is not yet the `target`:

:   * copy the `parent` C times, each time allowing some random probability that another character might be substituted using `mutate`.

Note that some of the the solutions given retain characters in the mutated string that are *correct* in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"

```
(:* repeat until the parent converges, (hopefully), to the target.

```

Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by *not* being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!

As illustration of this error, the code for 8th has the following remark.

```
Create a new string based on the TOS, changing randomly any characters which
don't already match the target:

```

*NOTE:* this has been changed, the 8th version is completely random now

Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!

To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2022-07-09

```
constant target = "METHINKS IT IS LIKE A WEASEL";
constant @alphabet = flat 'A'..'Z',' ';
constant C = 10;

sub mutate(Str $string, Real $mutate-chance where 0 ≤ * < 1) {
  $string.subst: /<?{ rand < $mutate-chance }> . /, @alphabet.pick, :global
}
sub fitness(Str $string) { [+] $string.comb Zeq target.comb }

printf "\r%6d: '%s'", $++, $_ for
  @alphabet.roll(target.chars).join,
  { max :by(&fitness), mutate($_, .001) xx C } ... target;
print "\n";

```


[User]
Task

Given 5 lists of ints:

list[1] = [9,3,3,3,2,1,7,8,5]

list[2] = [5,2,9,3,3,7,8,4,1]

list[3] = [1,4,3,6,7,3,8,3,2]

list[4] = [1,2,3,4,5,6,7,8,9]

list[5] = [4,6,8,7,2,3,3,3,1]

For each list, print 'true' if the list contains exactly three '3's that form a consecutive subsequence, otherwise print 'false'.
That is, print false unless there is exactly one run of three '3's and there is no other occurrence of a '3'.

[Assistant]
Generalized

```
for 1 .. 4 -> $n {

    say "\nExactly $n {$n}s, and they are consecutive:";

    say .gist, ' ', lc (.Bag{$n} == $n) && ( so .rotor($n=>-($n - 1)).grep: *.all == $n ) for
    [9,3,3,3,2,1,7,8,5],
    [5,2,9,3,3,7,8,4,1],
    [1,4,3,6,7,3,8,3,2],
    [1,2,3,4,5,6,7,8,9],
    [4,6,8,7,2,3,3,3,1],
    [3,3,3,1,2,4,5,1,3],
    [0,3,3,3,3,7,2,2,6],
    [3,3,3,3,3,4,4,4,4]
}

```

Output:

```
Exactly 1 1s, and they are consecutive:
[9 3 3 3 2 1 7 8 5] true
[5 2 9 3 3 7 8 4 1] true
[1 4 3 6 7 3 8 3 2] true
[1 2 3 4 5 6 7 8 9] true
[4 6 8 7 2 3 3 3 1] true
[3 3 3 1 2 4 5 1 3] false
[0 3 3 3 3 7 2 2 6] false
[3 3 3 3 3 4 4 4 4] false

Exactly 2 2s, and they are consecutive:
[9 3 3 3 2 1 7 8 5] false
[5 2 9 3 3 7 8 4 1] false
[1 4 3 6 7 3 8 3 2] false
[1 2 3 4 5 6 7 8 9] false
[4 6 8 7 2 3 3 3 1] false
[3 3 3 1 2 4 5 1 3] false
[0 3 3 3 3 7 2 2 6] true
[3 3 3 3 3 4 4 4 4] false

Exactly 3 3s, and they are consecutive:
[9 3 3 3 2 1 7 8 5] true
[5 2 9 3 3 7 8 4 1] false
[1 4 3 6 7 3 8 3 2] false
[1 2 3 4 5 6 7 8 9] false
[4 6 8 7 2 3 3 3 1] true
[3 3 3 1 2 4 5 1 3] false
[0 3 3 3 3 7 2 2 6] false
[3 3 3 3 3 4 4 4 4] false

Exactly 4 4s, and they are consecutive:
[9 3 3 3 2 1 7 8 5] false
[5 2 9 3 3 7 8 4 1] false
[1 4 3 6 7 3 8 3 2] false
[1 2 3 4 5 6 7 8 9] false
[4 6 8 7 2 3 3 3 1] false
[3 3 3 1 2 4 5 1 3] false
[0 3 3 3 3 7 2 2 6] false
[3 3 3 3 3 4 4 4 4] true
```


[User]
This task is to give an example of an exception handling routine
and to "throw" a new exception.

Related task

* Exceptions Through Nested Calls

[Assistant]
(formerly Perl 6)

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

The Raku equivalent to Perl 5's eval {...} is try {...}. A try block by default has a CATCH block that handles all fatal exceptions by ignoring them. If you define a CATCH block within the try, it replaces the default CATCH. It also makes the try keyword redundant, because any block can function as a try block if you put a CATCH block within it. The inside of a CATCH functions as a switch statement on the current exception.

```
try {
    die "Help I'm dieing!";
    CATCH {
        when X::AdHoc { note .Str.uc; say "Cough, Cough, Aiee!!" }
        default { note "Unexpected exception, $_!" }
    }
}

say "Yay. I'm alive.";

die "I'm dead.";

say "Arrgh.";

CATCH {
    default { note "No you're not."; say $_.Str; }
}
```

```
HELP I'M DIEING!
Cough, Cough, Aiee!!
Yay. I'm alive.
No you're not.
I'm dead.

```

Rake comes with phasers, that are called when certain conditions in the life of a program, routine or block are met. CATCH is one of them and works nicely together with LEAVE that is called even if an exception would force the current block to be left immediately. It's a nice place to put your cleanup code.

```
sub f(){
        ENTER { note '1) f has been entered' }
        LEAVE { note '2) f has been left' }
        say '3) here be dragons';
        die '4) that happend to be deadly';
}

f();
say '5) am I alive?';

CATCH {
        when X::AdHoc { note q{6) no, I'm dead}; }
}
```

```
1) f has been entered
3) here be dragons
6) no, I'm dead
2) f has been left
```


[User]
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.

:   1. Create two user-defined exceptions,   **U0**   and   **U1**.
    2. Have function   **foo**   call function   **bar**   twice.
    3. Have function   **bar**   call function   **baz**.
    4. Arrange for function   **baz**   to raise, or throw exception   **U0**   on its first call, then exception   **U1**   on its second.
    5. Function   **foo**   should catch only exception   **U0**,   not   **U1**.

Show/describe what happens when the program is run.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

```
sub foo() {
    for 0..1 -> $i {
        bar $i;
        CATCH {
            when /U0/ { say "Function foo caught exception U0" }
        }
    }
}

sub bar($i) { baz $i }

sub baz($i) { die "U$i" }

foo;

```

Output:

```
Function foo caught exception U0
U1
  in sub baz at catch:12
  in sub bar at catch:10
  in sub foo at catch:4
  in block  at catch:14
```


[User]
The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.

**Task detail**

* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.

* The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:

:   :   2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
    :   3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.

* Create a second executable to calculate the following:
  + Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.

* Explain any extra setup/run steps needed to complete the task.

**Notes:**

* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed *not* to be present in the runtime environment.
* Interpreters are present in the runtime environment.

[Assistant]
(formerly Perl 6)
The library can be written as a module:

```
module Hailstone {
    our sub hailstone($n) is export {
	$n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1
    }
}

sub MAIN {
    say "hailstone(27) = {.[^4]} [...] {.[*-4 .. *-1]}" given Hailstone::hailstone 27;
}

```

It can be run with:

```
$ raku Hailstone.rakumod

```

Output:

```
hailstone(27) = 27 82 41 124 [...] 8 4 2 1
```

It can then be used with a program such as:

```
use Hailstone;
my %score;
(1 .. 100_000).race.map: { %score{hailstone($_).elems}++ };
say "Most common length is {.key}, occurring {.value} times." given max :by(*.value), %score;

```

Called with a command line as:

```
$ RAKULIB=. raku test-hailstone.raku
```

The environment variable RAKULIB might be necessary if the file Hailstone.rakumod is not in the standard library path for Raku.


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

Task

Create an interpreter for a Markov Algorithm.

Rules have the syntax:

```
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]

```

There is one rule per line.

If there is a   **.**   (period)   present before the   **<replacement>**,   then this is a terminating rule in which case the interpreter must halt execution.

A ruleset consists of a sequence of rules, with optional comments.

Rulesets

Use the following tests on entries:

Ruleset 1

```
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule

```

Sample text of:

:   `I bought a B of As from T S.`

Should generate the output:

:   `I bought a bag of apples from my brother.`

Ruleset 2

A test of the terminating rule

```
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
```

Sample text of:

:   `I bought a B of As from T S.`

Should generate:

:   `I bought a bag of apples from T shop.`

Ruleset 3

This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.

```
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule

```

Sample text of:

:   `I bought a B of As W my Bgage from T S.`

Should generate:

:   `I bought a bag of apples with my money from T shop.`

Ruleset 4

This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.)

```
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->

```

Sample text of:

:   `_1111*11111_`

should generate the output:

:   `11111111111111111111`

Ruleset 5

A simple Turing machine,
implementing a three-state busy beaver.

The tape consists of **0**s and **1**s,   the states are **A**, **B**, **C** and **H** (for **H**alt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.

Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.

```
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11

```

This ruleset should turn

:   `000000A000000`

into

:   `00011H1111000`

[Assistant]
(formerly Perl 6)
Run this without arguments and it will scan the cwd for rules.\* files and their corresponding test.\*.

Run it with two filenames or one filename and some text to run a rulefile on the file contents or the given text.

Add --verbose to see the replacements step-by-step.

```
grammar Markov {
    token TOP {
        ^ [^^ [<rule> | <comment>] $$ [\n|$]]* $
        { make $<rule>>>.ast }
    }
    token comment {
        <before ^^> '#' \N*
        { make Nil }
    }
    token ws {
        [' '|\t]*
    }
    rule rule {
        <before ^^>$<pattern>=[\N+?] '->'
        $<terminal>=[\.]?$<replacement>=[\N*]
        { make {:pattern($<pattern>.Str),
                :replacement($<replacement>.Str),
                :terminal($<terminal>.Str eq ".")} }
    }
}

sub run(:$ruleset, :$start_value, :$verbose?) {
    my $value = $start_value;
    my @rules = Markov.parse($ruleset).ast.list;
    loop {
        my $beginning = $value;
        for @rules {
            my $prev = $value;
            $value = $value.subst(.<pattern>, .<replacement>);
            say $value if $verbose && $value ne $prev;
            return $value if .<terminal>;
            last if $value ne $prev;
        }
        last if $value eq $beginning;
    }
    return $value;
}

multi sub MAIN(Bool :$verbose?) {
    my @rulefiles = dir.grep(/rules.+/).sort;
    for @rulefiles -> $rulefile {
        my $testfile = $rulefile.subst("rules", "test");
        my $start_value = (try slurp($testfile).trim-trailing)
                          // prompt("please give a start value: ");

        my $ruleset = slurp($rulefile);
        say $start_value;
        say run(:$ruleset, :$start_value, :$verbose);
        say '';
    }
}

multi sub MAIN(Str $rulefile where *.IO.f, Str $input where *.IO.f, Bool :$verbose?) {
    my $ruleset = slurp($rulefile);
    my $start_value = slurp($input).trim-trailing;
    say "starting with: $start_value";
    say run(:$ruleset, :$start_value, :$verbose);
}

multi sub MAIN(Str $rulefile where *.IO.f, *@pieces, Bool :$verbose?) {
    my $ruleset = slurp($rulefile);
    my $start_value = @pieces.join(" ");
    say "starting with: $start_value";
    say run(:$ruleset, :$start_value, :$verbose);
}

```


[User]
Task

Run either the   **ls**   system command   (**dir**   on Windows),   or the   **pause**   system command.

Related task

* Get system command output

[Assistant]
(formerly Perl 6)

```
run "ls" orelse .die; # output to stdout

my @ls = qx/ls/;    # output to variable

my $cmd = 'ls';
@ls = qqx/$cmd/;  # same thing with interpolation
```


[User]
RCBF is a set of Brainf\*\*\* compilers and interpreters written for Rosetta Code in a variety of languages.

Below are links to each of the versions of RCBF.

An implementation need only properly implement the following instructions:

| Command | Description |
| --- | --- |
| `>` | Move the pointer to the right |
| `<` | Move the pointer to the left |
| `+` | Increment the memory cell under the pointer |
| `-` | Decrement the memory cell under the pointer |
| `.` | Output the character signified by the cell at the pointer |
| `,` | Input a character and store it in the cell at the pointer |
| `[` | Jump past the matching `]` if the cell under the pointer is 0 |
| `]` | Jump back to the matching `[` if the cell under the pointer is nonzero |

Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.

[Assistant]
(formerly Perl 6)

See Execute\_Brain\*\*\*\*/Raku.


[User]
Task

Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7\*8" found there.

:   * The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.
    * For output, it is sufficient to have the implementation of the `STP` opcode return the accumulator to your actual language, and then use your standard printing routines to output it.

Bonus Points
:   Run all 5 sample programs at the aforementioned website and output their results.

[Assistant]
Didn't bother implementing an assembler or disassembler.

```
my (@mem, $ip, $acc); # memory, instruction pointer, accumulator

sub load (@program) {
    die "memory exceeded" if +@program > 32;
    $ip = 0;
    $acc = 0;
    @mem = @program »%» 256;
}

sub execute (*@program) {
    load @program;
    loop {
        my $reg = @mem[$ip];
        quietly my ($inst, $data) = $reg +> 5 +& 7, $reg +& 31;
        given $inst {
            when 0 { #`{ NOP } }
            when 1 { #`{ LDA } $acc = @mem[$data] }
            when 2 { #`{ STA } @mem[$data] = $acc }
            when 3 { #`{ ADD } $acc += @mem[$data] }
            when 4 { #`{ SUB } $acc -= @mem[$data] }
            when 5 { #`{ BRZ } $ip = $data - 1 unless $acc }
            when 6 { #`{ JMP } $ip = $data - 1 }
            when 7 { #`{ STP } last }
            default { die 'Invalid instruction' }
        }
        ++$ip;
        last if $ip == 32;
    }
    $acc
}

say "2 + 2 = " ~ execute 35,100,224,2,2;
say "7 x 8 = " ~ execute 44,106,76,43,141,75,168,192,44,224,8,7,0,1;
say "Fibonacci: " ~
execute 46,79,109,78,47,77,48,145,171,80,192,46,224,1,1,0,8,1;
say "Linked list: " ~
execute 45,111,69,112,71,0,78,0,171,79,192,46,
224,32,0,28,1,0,0,0,6,0,2,26,5,20,3,30,1,22,4,24;
say "Prisoners dilemma: " ~
execute 0,0,224,0,35,157,178,35,93,174,33,127,65,194,
32,127,64,194,35,93,33,126,99,65,32,126,99,64,194,0,1,3;

```

Output:

```
2 + 2 = 4
7 x 8 = 56
Fibonacci: 55
Linked list: 6
Prisoners dilemma: 0
```


[User]
Task

Implement a **CopyPasta Language** interpreter or compiler. These are the commands used by CopyPasta Language:

| Command | Description |
| --- | --- |
| `Copy` | Copy the text of the following line to the clipboard |
| `CopyFile` | Copy the text of the file cited in the following line to the clipboard or in the case where the next line is TheF\*ckingCode copies the code to the clipboard |
| `Duplicate` | Duplicate the text in the clipboard as many times as the following line specifies |
| `Pasta!` | Display the clipboard and stop the program |

[Assistant]
(formerly Perl 6)

```
sub CopyPasta ($code) {
    my @code = $code.split("\n")>>.trim.grep: *.so;
    return "Program never ends!" unless grep { $_ eq 'Pasta!' }, @code;

    my @cb;
    my $PC = 0;
    loop {
        given @code[$PC] {
            when 'Copy'      {        @cb.push: @code[++$PC] }
            when 'CopyFile'  { $PC++; @cb.push: @code[$PC] eq 'TheF*ckingCode' ?? @code !! slurp @code[$PC] }
            when 'Duplicate' {        @cb = (flat @cb) xx @code[++$PC] }
            when 'Pasta!'    { return @cb }
            default          { return "Does not compute: @code[$PC]" }
        }
        $PC++;
    }
}

spurt 'pasta.txt', "I'm the pasta.txt file.";

(say $_ for .&CopyPasta; say '')
    for
    "Copy \nRosetta Code\n\tDuplicate\n2\n\nPasta!\nLa Vista",
    "CopyFile\npasta.txt\nDuplicate\n1\nPasta!",
    "Copy\nInvalid\n Duplicate\n1\n\nGoto\n3\nPasta!",
    "CopyFile\nTheF*ckingCode\nDuplicate\n2\nPasta!",
    "Copy\nRosetta Code\nDuplicate\n2\n\nPasta";

unlink 'pasta.txt';

```

Output:

```
Rosetta Code
Rosetta Code

I'm the pasta.txt file.

Does not compute: Goto

CopyFile TheF*ckingCode Duplicate 2 Pasta!
CopyFile TheF*ckingCode Duplicate 2 Pasta!

Program never ends!
```


[User]
Task

Implement a    **HQ9+**    interpreter or compiler.

[Assistant]
(formerly Perl 6)

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

The spec is kind of vague about how to do error handling... and whether white space is significant... and how the accumulator should be accessed... and pretty much everything else too.

```
class HQ9Interpreter {
    has @!code;
    has $!accumulator;
    has $!pointer;

    method run ($code) {
        @!code = $code.comb;
        $!accumulator = 0;
        $!pointer = 0;
        while $!pointer < @!code {
            given @!code[$!pointer].lc {
                when 'h' { say 'Hello world!' }
                when 'q' { say @!code }
                when '9' { bob(99) }
                when '+' { $!accumulator++ }
                default  { note "Syntax error: Unknown command \"{@!code[$!pointer]}\"" }
            }
	    $!pointer++;
        }
    }
    sub bob ($beer is copy) {
        sub what  { "{$beer??$beer!!'No more'} bottle{$beer-1??'s'!!''} of beer" };
        sub where { 'on the wall' };
        sub drink { $beer--; "Take one down, pass it around," }
        while $beer {
            .say for "&what() &where(),", "&what()!",
                     "&drink()", "&what() &where()!", ''
        }
    }
}

# Feed it a command string:

my $hq9 = HQ9Interpreter.new;
$hq9.run("hHq+++Qq");
say '';
$hq9.run("Jhq.k+hQ");

```

Output:

```
Hello world!
Hello world!
hHq+++Qq
hHq+++Qq
hHq+++Qq

Syntax error: Unknown command "J"
Hello world!
Jhq.k+hQ
Syntax error: Unknown command "."
Syntax error: Unknown command "k"
Hello world!
Jhq.k+hQ

```

Or start a REPL (Read Execute Print Loop) and interact at the command line:

```
my $hq9 = HQ9Interpreter.new;
while 1 {
    my $in = prompt('HQ9+>').chomp;
    last unless $in.chars;
    $hq9.run($in)
}

```


[User]
**RCSNUSP** is a set of SNUSP compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCSNUSP.

An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.02

Implementation of modular SNUSP.

```
class SNUSP {

    has @!inst-pointer;
    has @!call-stack;
    has @!direction;
    has @!memory;
    has $!mem-pointer;

    method run ($code) {
        init();
        my @code = pad( |$code.lines );
        for @code.kv -> $r, @l {
           my $index = @l.grep( /'$'/, :k );
           if $index {
               @!inst-pointer = $r, $index;
               last
           }
        }

        loop {
            my $instruction = @code[@!inst-pointer[0]; @!inst-pointer[1]];
            given $instruction {
                when '>'  { $!mem-pointer++ }
                when '<'  { $!mem-pointer-- }
                when '+'  { @!memory[$!mem-pointer]++ }
                when '-'  { @!memory[$!mem-pointer]-- }
                when '.'  { print @!memory[$!mem-pointer].chr }
                when ','  { @!memory[$!mem-pointer] = $*IN.getc.ord }
                when '/'  { @!direction = @!direction.reverse «*» -1 }
                when '\\' { @!direction = @!direction.reverse }
                when '!'  { nexti() }
                when '?'  { nexti() unless @!memory[$!mem-pointer] }
                when '@'  { @!call-stack.push: @!inst-pointer.Array }
                when '#'  {
                    last unless +@!call-stack;
                    @!inst-pointer = |@!call-stack.pop;
                    nexti();
                }
            }
            nexti();
            last if @!inst-pointer[0] > +@code or
                    @!inst-pointer[1] > +@code[0];
        }

        sub init () {
            @!inst-pointer = 0, 0;
            @!direction    = 0, 1;
            $!mem-pointer  = 0;
            @!memory       = ()
        }

        sub nexti () { @!inst-pointer Z+= @!direction }

        sub pad ( *@lines ) {
            my $max = max @lines».chars;
            my @pad = @lines.map: $max - *.chars;
            map -> $i { flat @lines[$i].comb, ' ' xx @pad[$i] }, ^@lines;
        }
    }
}

# TESTING
my $hw = q:to/END/;
    /++++!/===========?\>++.>+.+++++++..+++\
    \+++\ | /+>+++++++>/ /++++++++++<<.++>./
    $+++/ | \+++++++++>\ \+++++.>.+++.-----\
          \==-<<<<+>+++/ /=.>.+>.--------.-/
    END

my $snusp = SNUSP.new;
$snusp.run($hw)

```

Output:

```
Hello World!
```


[User]
Some integers (greater than 1), have the property that the digital sum of that integer raised to some integer power greater than 1, is equal to the original integer.

E.G.

:   |  |  |
    | --- | --- |
    | **92 == 81** | **8 + 1 == 9** |

Some integers have this property using more than one exponent.

:   |  |  |
    | --- | --- |
    | **183 == 5832** | **5 + 8 + 3 + 2 == 18** |
    | **186 == 34012224** | **3 + 4 + 0 + 1 + 2 + 2 + 2 + 4 == 18** |
    | **187 == 612220032** | **6 + 1 + 2 + 2 + 2 + 0 + 0 + 3 + 2 == 18** |

*Note: **every** integer has an exponential digital sum equal to the original integer when using an exponent of 1. And, 0 and 1 raised to any power will have a digital sum of 0 and 1 respectively.*

Task

* Find and show the first twenty integers (with their exponents), that satisfy this condition.
* Find and show at least the first ten integers with their exponents, that satisfy this condition in three or more ways.

[Assistant]
Implement a lazy generator. Made some assumptions about search limits. May be poor assumptions, but haven't been able to find any counterexamples. (Edit: and some were bad.)

```
my @expsum = lazy (2..*).hyper.map( -> $Int {
    my atomicint $miss = 0;
    (2..$Int).map( -> $exp {
        if (my $sum = ($Int ** $exp).comb.sum) > $Int { last if ++⚛$miss > 20 }
        $sum == $Int ?? "$Int^$exp" !! Empty;
    }) || Empty;
});

say "First twenty-five integers that are equal to the digital sum of that integer raised to some power:";
put .join(', ') for @expsum[^25];
say "\nFirst thirty that satisfy that condition in three or more ways:";
put .join(', ') for @expsum.grep({.elems≥3})[^30];

```

Output:

```
First twenty-five integers that are equal to the digital sum of that integer raised to some power:
7^4
8^3
9^2
17^3
18^3, 18^6, 18^7
20^13
22^4
25^4
26^3
27^3, 27^7
28^4, 28^5
31^7
34^7
35^5
36^4, 36^5
40^13
43^7
45^6
46^5, 46^8
53^7
54^6, 54^8, 54^9
58^7
63^8
64^6
68^7

First thirty that satisfy that condition in three or more ways:
18^3, 18^6, 18^7
54^6, 54^8, 54^9
90^19, 90^20, 90^21, 90^22, 90^28
107^11, 107^13, 107^15
181^16, 181^18, 181^19, 181^20
360^45, 360^46, 360^49, 360^51
370^48, 370^54, 370^57, 370^59
388^32, 388^35, 388^36
523^39, 523^42, 523^44, 523^45
603^44, 603^47, 603^54
667^48, 667^54, 667^58
793^57, 793^60, 793^64
1062^72, 1062^77, 1062^81
1134^78, 1134^80, 1134^82, 1134^86
1359^92, 1359^98, 1359^102
1827^121, 1827^126, 1827^131
1828^123, 1828^127, 1828^132
2116^140, 2116^143, 2116^147
2330^213, 2330^215, 2330^229
2430^217, 2430^222, 2430^223, 2430^229, 2430^230
2557^161, 2557^166, 2557^174
2610^228, 2610^244, 2610^246
2656^170, 2656^172, 2656^176
2700^406, 2700^414, 2700^420, 2700^427
2871^177, 2871^189, 2871^190
2934^191, 2934^193, 2934^195
3077^187, 3077^193, 3077^199
3222^189, 3222^202, 3222^210
3231^203, 3231^207, 3231^209
3448^215, 3448^221, 3448^227
```


[User]
Most programming languages have a built-in implementation of exponentiation.

Task

Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition).

If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants.

Related tasks

* Exponentiation order
* arbitrary-precision integers (included)
* Exponentiation with infix operators in (or operating on) the base

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2023.09

```
proto pow (Real, Int --> Real) {*}
multi pow (0,     0)         { fail '0**0 is undefined' }
multi pow ($base, UInt $exp) { [*] $base xx $exp }
multi pow ($base, $exp)  { 1 / samewith $base, -$exp }

multi infix:<**> (Real $a, Int $b) { pow $a, $b }

# Testing

say pow .75, -5;
say .75 ** -5;

```


[User]
This task will demonstrate the order of exponentiation   (**xy**)    when there are multiple exponents.

(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of  `**`, `^`, `↑`  or some such for exponentiation.)

Task requirements

Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).

If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.

Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):

:   :   :   :   * 5\*\*3\*\*2
                * (5\*\*3)\*\*2
                * 5\*\*(3\*\*2)

If there are other methods (or formats) of multiple exponentiations, show them as well.

See also

* MathWorld entry:   exponentiation

Related tasks

* exponentiation operator
* arbitrary-precision integers (included)
* Exponentiation with infix operators in (or operating on) the base

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.08

Note that the reduction forms automatically go right-to-left because the base operator is right-associative. Most other operators are left-associative and would automatically reduce left-to-right instead.

```
use MONKEY-SEE-NO-EVAL;
sub demo($x) { say "  $x\t───► ", EVAL $x }

demo '5**3**2';      # show ** is right associative
demo '(5**3)**2';
demo '5**(3**2)';

demo '[**] 5,3,2';   # reduction form, show only final result
demo '[\**] 5,3,2';  # triangle reduction, show growing results

# Unicode postfix exponents are supported as well:

demo '(5³)²';
demo '5³²';

```

Output:

```
  5**3**2	───► 1953125
  (5**3)**2	───► 15625
  5**(3**2)	───► 1953125
  [**] 5,3,2	───► 1953125
  [\**] 5,3,2	───► 2 9 1953125
  (5³)²	───► 15625
  5³²	───► 23283064365386962890625

```

The Unicode exponent form without parentheses ends up raising to the 32nd power. Nor are you even allowed to parenthesize it the other way: 5(³²) would be a syntax error. Despite all that, for programs that do a lot of squaring or cubing, the postfix forms can enhance both readability and concision.


[User]
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually
support one of  `**`, `^`, `↑`  or some such for exponentiation.)

Some languages treat/honor infix operators when performing exponentiation   (raising
numbers to some power by the language's exponentiation operator,   if the computer
programming language has one).

Other programming languages may make use of the   **POW**   or some other BIF
  (**B**uilt─**I**n **F**function),   or some other library service.

If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.

This task will deal with the case where there is some form of an   *infix operator*   operating
in   (or operating on)   the base.

Example

A negative five raised to the 3rd power could be specified as:

```
   -5  ** 3          or as
  -(5) ** 3          or as
  (-5) ** 3          or as something else

```

(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).

Task
:   * compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
    * Raise the following numbers   (integer or real):

    :   :   * -5     and
            * +5

    * to the following powers:

    :   :   * 2nd     and
            * 3rd

    * using the following expressions   (if applicable in your language):

    :   :   * -x\*\*p
            * -(x)\*\*p
            * (-x)\*\*p
            * -(x\*\*p)

    * Show here (on this page) the four (or more) types of symbolic expressions for each number and power.

Try to present the results in the same format/manner as the other programming entries to make any differences apparent.

The variables may be of any type(s) that is/are applicable in your language.

Related tasks

* Exponentiation order
* Exponentiation operator
* Arbitrary-precision integers (included)
* Parsing/RPN to infix conversion
* Operator precedence

References

* Wikipedia: Order of operations in Programming languages

[Assistant]
In Raku by default, infix exponentiation binds tighter than unary negation. It is trivial however to define your own infix operators with whatever precedence level meets the needs of your program.

A slight departure from the task specs. Use `1 + {expression}` rather than just `{expression}` to better demonstrate the relative precedence levels. Where `{expression}` is one of:

* `-x{exponential operator}p`
* `-(x){exponential operator}p`
* `((-x){exponential operator}p)`
* `-(x{exponential operator}p)`

Also add a different grouping: `(1 + -x){exponential operator}p`

```
sub infix:<↑> is looser(&prefix:<->) { $^a ** $^b }
sub infix:<∧> is looser(&infix:<->)  { $^a ** $^b }

for
   ('Default precedence: infix exponentiation is tighter (higher) precedence than unary negation.',
     '1 + -$x**$p',   {1 + -$^a**$^b},   '1 + (-$x)**$p', {1 + (-$^a)**$^b},  '1 + (-($x)**$p)', {1 + (-($^a)**$^b)},
     '(1 + -$x)**$p', {(1 + -$^a)**$^b}, '1 + -($x**$p)', {1 + -($^a**$^b)}),

   ("\nEasily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation.",
     '1 + -$x↑$p ',   {1 + -$^a↑$^b},    '1 + (-$x)↑$p ', {1 + (-$^a)↑$^b},   '1 + (-($x)↑$p) ', {1 + (-($^a)↑$^b)},
     '(1 + -$x)↑$p ', {(1 + -$^a)↑$^b},  '1 + -($x↑$p) ', {1 + -($^a↑$^b)}),

   ("\nEven more so: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.",
     '1 + -$x∧$p ',   {1 + -$^a∧$^b},    '1 + (-$x)∧$p ', {1 + (-$^a)∧$^b},   '1 + (-($x)∧$p) ', {1 + (-($^a)∧$^b)},
     '(1 + -$x)∧$p ', {(1 + -$^a)∧$^b},  '1 + -($x∧$p) ', {1 + -($^a∧$^b)})
-> $case {
    my ($title, @operations) = $case<>;
    say $title;
    for -5, 5 X 2, 3 -> ($x, $p) {
        printf "x = %2d  p = %d", $x, $p;
        for @operations -> $label, &code { print " │ $label = " ~ $x.&code($p).fmt('%4d') }
        say ''
    }
}

```

Output:

```
Default precedence: infix exponentiation is tighter (higher) precedence than unary negation.
x = -5  p = 2 │ 1 + -$x**$p =  -24 │ 1 + (-$x)**$p =   26 │ 1 + (-($x)**$p) =  -24 │ (1 + -$x)**$p =   36 │ 1 + -($x**$p) =  -24
x = -5  p = 3 │ 1 + -$x**$p =  126 │ 1 + (-$x)**$p =  126 │ 1 + (-($x)**$p) =  126 │ (1 + -$x)**$p =  216 │ 1 + -($x**$p) =  126
x =  5  p = 2 │ 1 + -$x**$p =  -24 │ 1 + (-$x)**$p =   26 │ 1 + (-($x)**$p) =  -24 │ (1 + -$x)**$p =   16 │ 1 + -($x**$p) =  -24
x =  5  p = 3 │ 1 + -$x**$p = -124 │ 1 + (-$x)**$p = -124 │ 1 + (-($x)**$p) = -124 │ (1 + -$x)**$p =  -64 │ 1 + -($x**$p) = -124

Easily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation.
x = -5  p = 2 │ 1 + -$x↑$p  =   26 │ 1 + (-$x)↑$p  =   26 │ 1 + (-($x)↑$p)  =   26 │ (1 + -$x)↑$p  =   36 │ 1 + -($x↑$p)  =  -24
x = -5  p = 3 │ 1 + -$x↑$p  =  126 │ 1 + (-$x)↑$p  =  126 │ 1 + (-($x)↑$p)  =  126 │ (1 + -$x)↑$p  =  216 │ 1 + -($x↑$p)  =  126
x =  5  p = 2 │ 1 + -$x↑$p  =   26 │ 1 + (-$x)↑$p  =   26 │ 1 + (-($x)↑$p)  =   26 │ (1 + -$x)↑$p  =   16 │ 1 + -($x↑$p)  =  -24
x =  5  p = 3 │ 1 + -$x↑$p  = -124 │ 1 + (-$x)↑$p  = -124 │ 1 + (-($x)↑$p)  = -124 │ (1 + -$x)↑$p  =  -64 │ 1 + -($x↑$p)  = -124

Even more so: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.
x = -5  p = 2 │ 1 + -$x∧$p  =   36 │ 1 + (-$x)∧$p  =   36 │ 1 + (-($x)∧$p)  =   26 │ (1 + -$x)∧$p  =   36 │ 1 + -($x∧$p)  =  -24
x = -5  p = 3 │ 1 + -$x∧$p  =  216 │ 1 + (-$x)∧$p  =  216 │ 1 + (-($x)∧$p)  =  126 │ (1 + -$x)∧$p  =  216 │ 1 + -($x∧$p)  =  126
x =  5  p = 2 │ 1 + -$x∧$p  =   16 │ 1 + (-$x)∧$p  =   16 │ 1 + (-($x)∧$p)  =   26 │ (1 + -$x)∧$p  =   16 │ 1 + -($x∧$p)  =  -24
x =  5  p = 3 │ 1 + -$x∧$p  =  -64 │ 1 + (-$x)∧$p  =  -64 │ 1 + (-($x)∧$p)  = -124 │ (1 + -$x)∧$p  =  -64 │ 1 + -($x∧$p)  = -124
```


[User]
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.

If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:

Occasionally, code must be written that depends on *two* conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:

```
  if (condition1isTrue) {
     if (condition2isTrue)
        bothConditionsAreTrue();
     else
        firstConditionIsTrue();
  }
  else if (condition2isTrue)
     secondConditionIsTrue();
  else
     noConditionIsTrue();

```

Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.

This can be improved by introducing a new keyword **if2**. It is similar to **if**, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:

```
  if2 (condition1isTrue) (condition2isTrue)
     bothConditionsAreTrue();
  else1
     firstConditionIsTrue();
  else2
     secondConditionIsTrue();
  else
     noConditionIsTrue();

```

Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.

[Assistant]
(formerly Perl 6)
Writing the conditional blocks is no problem, since there's no distinction between built-in closures and user-defined. The if2 is currently just a function call, which requires a comma after the second condition; eventually we will be able to drop that in user-defined code, but none of our implementations can define parse actions in the statement\_control category quite yet. (That syntax is special insofar as it's the only place Raku allows two terms in a row.) So currently it requires the comma until the implementations catch up with the spec on that subject.

This solution is hygienic in both lexical and dynamic variables; the only caveat is that the user's program must avoid the dynamic variable being used by the implementation of conditional, $\*IF2. This does not seem like a great hardship. (The conditionals will also nest correctly since that's how dynamic variables behave.)

```
my &if2  = -> \a, \b, &x { my @*IF2 = ?a,?b; x }

my &if-both    = -> &x { x if @*IF2 eq (True,True)  }
my &if-first   = -> &x { x if @*IF2 eq (True,False) }
my &if-second  = -> &x { x if @*IF2 eq (False,True) }
my &if-neither = -> &x { x if @*IF2 eq (False,False)}

sub test ($a,$b) {
    $_ = "G";          # Demo correct scoping of topic.
    my $got = "o";     # Demo correct scoping of lexicals.
    my $*got = "t";    # Demo correct scoping of dynamics.

    if2 $a, $b, {
        if-both { say "$_$got$*got both" }
        if-first { say "$_$got$*got first" }
        if-second { say "$_$got$*got second" }
        if-neither { say "$_$got$*got neither" }
    }
}

say test |$_ for 1,0 X 1,0;

```

Output:

```
Got both
Got first
Got second
Got neither
```


[User]
Task

Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.

The routine should demonstrably rely on either:

1. Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
2. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
3. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.

The routine should be used to:

* Show the first twenty primes.
* Show the primes between 100 and 150.
* Show the *number* of primes between 7,700 and 8,000.
* Show the 10,000th prime.

Show output on this page.

**Note:** You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).

**Note 2:** If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).

**Note 3:**The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency).

Reference

* Prime Numbers. Website with large count of primes.

[Assistant]
(formerly Perl 6)
Build a lazy infinite list of primes using the Raku builtin is-prime method. ( A lazy list will not bother to calculate the values until they are actually used. ) That is the first line. If you choose to calculate the entire list, it is fairly certain that you will run out of process / system memory before you finish... (patience too probably) but there aren't really any other constraints. The is-prime builtin uses a Miller-Rabin primality test with 100 iterations, so while it is not 100% absolutely guaranteed that every number it flags as prime actually is, the chances that it is wrong are about 4-100. Much less than the chance that a cosmic ray will cause an error in your computers CPU. Everything after the first line is just display code for the various task requirements.

```
my @primes = lazy gather for 1 .. * { .take if .is-prime }

say "The first twenty primes:\n   ", "[{@primes[^20].fmt("%d", ', ')}]";
say "The primes between 100 and 150:\n   ", "[{@primes.&between(100, 150).fmt("%d", ', ')}]";
say "The number of primes between 7,700 and 8,000:\n   ", +@primes.&between(7700, 8000);
say "The 10,000th prime:\n   ", @primes[9999];

sub between (@p, $l, $u) {
    gather for @p { .take if $l < $_ < $u; last if $_ >= $u }
}

```

Output:

```
The first twenty primes:
   [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
The primes between 100 and 150:
   [101, 103, 107, 109, 113, 127, 131, 137, 139, 149]
The number of primes between 7,700 and 8,000:
   30
The 10,000th prime:
   104729
```


[User]
Sort a huge file too large to fit into memory.

The algorithm consists in reading a large file to be sorted in chunks of data small enough to fit in main memory, sort each of the chunks, write them out to a temporary file, and finally combined the smaller subfiles into a single larger file.

For more info see: https://en.wikipedia.org/wiki/External\_sorting

The sorting algorithm can be any popular sort, like quicksort.

For simplicity one can assume that the file consists of fixed length integers and that the sort function is less-than (<).

[Assistant]
(formerly Perl 6)
Borrowing from Stream\_Merge here. Temporary files are automatically deleted when program is done, so no explicit clean-up required.

```
use File::Temp;

sub merge_streams ( @streams ) {
    my @s = @streams.map({ hash( STREAM => $_, HEAD => .get ) }).grep({ .<HEAD>.defined });

    return gather while @s {
        my $h = @s.min: +*.<HEAD>;
        take $h<HEAD>;
        $h<HEAD> := $h<STREAM>.get
            orelse @s .= grep( { $_ !=== $h } );
    }
}

sub store (@values) {
    my ($filename,$filehandle) = tempfile(:prefix('external-sort.'));
    $filehandle.say: join "\n", @values.sort: +*;
    $filename
}

# we're going to pretend that this is a long stream of input from stdin...
my (@chunk,@files);
for (<43 2 45 32 15 4 3 -9 45 66 0 42 78 123 -11 76 55 87 -2 64 92 34>) {
    @chunk.push: $_;
    @files.push: store(@chunk) and @chunk = () if @chunk.elems == 4; # limit of records per merge file
}
@files.push: store(@chunk) if @chunk;

say join ' ', merge_streams @files».&open;

```

Output:

```
-11 -9 -2 0 2 3 4 15 32 34 42 43 45 45 55 64 66 76 78 87 92 123
```


[User]
Definition

**n**   is an   *extra prime*   if   **n**   is prime and its decimal digits and sum of digits are also primes.

Task

Show the extra primes under   **10,000**.

Reference

OEIS:A062088 - Primes with every digit a prime and the sum of the digits a prime.

Related tasks

* Numbers with prime digits whose sum is 13
* Smarandache prime-digital sequence
* Category:Prime Numbers

[Assistant]
For the time being, (Doctor?), I'm going to assume that the task is really "Sequence of primes with every digit a prime and the sum of the digits a prime". Outputting my own take on a reasonable display of results, compact and easily doable but exercising it a bit.

```
my @ppp = lazy flat 2, 3, 5, 7, 23, grep { .is-prime && .comb.sum.is-prime },
               flat (2..*).map: { flat ([X~] (2, 3, 5, 7) xx $_) X~ (3, 7) };

put 'Terms < 10,000: '.fmt('%34s'), @ppp[^(@ppp.first: * > 1e4, :k)];
put '991st through 1000th: '.fmt('%34s'), @ppp[990 .. 999];
put 'Crossing 10th order of magnitude: ', @ppp[9055..9060];

```

Output:

```
                  Terms < 10,000: 2 3 5 7 23 223 227 337 353 373 557 577 733 757 773 2333 2357 2377 2557 2753 2777 3253 3257 3323 3527 3727 5233 5237 5273 5323 5527 7237 7253 7523 7723 7727
            991st through 1000th: 25337353 25353227 25353373 25353577 25355227 25355333 25355377 25357333 25357357 25357757
Crossing 10th order of magnitude: 777777227 777777577 777777773 2222222377 2222222573 2222225273
```


[User]
Filename extensions are a rudimentary but commonly used way of identifying files types.

Task

Write a function or program that

* takes one string argument representing the path/URL to a file
* returns the filename extension according to the below specification, or an empty string if the filename has no extension.

If your programming language  (or standard library)  has built-in functionality for extracting a filename extension,

show how it would be used and how exactly its behavior differs from this specification.

Specification

For the purposes of this task, a filename extension:

* occurs at the very end of the filename
* consists of a period, followed solely by one or more ASCII letters or digits (A-Z, a-z, 0-9)

Test cases

:   :   :   :   | Input | Output | Comment |
                | --- | --- | --- |
                | `http://example.com/download.tar.gz` | `.gz` |  |
                | `CharacterModel.3DS` | `.3DS` |  |
                | `.desktop` | `.desktop` |  |
                | `document` |  | *empty string* |
                | `document.txt_backup` |  | *empty string, because `_` is not a letter or number* |
                | `/etc/pam.d/login` |  | *empty string, as the period is in the parent directory name rather than the filename* |

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)

The built-in `IO::Path` class has an `.extension` method:

```
say $path.IO.extension;

```

Contrary to this task's specification, it

* doesn't include the dot in the output
* doesn't restrict the extension to letters and numbers.

Here's a custom implementation which does satisfy the task requirements:

```
sub extension (Str $path --> Str) {
    $path.match(/:i ['.' <[a..z0..9]>+]? $ /).Str
}

# Testing:

printf "%-35s %-11s %-12s\n", $_, extension($_).perl, $_.IO.extension.perl
for <
    http://example.com/download.tar.gz
    CharacterModel.3DS
    .desktop
    document
    document.txt_backup
    /etc/pam.d/login
>;

```

Output:

```
http://example.com/download.tar.gz  ".gz"       "gz"
CharacterModel.3DS                  ".3DS"      "3DS"
.desktop                            ".desktop"  "desktop"
document                            ""          ""
document.txt_backup                 ""          "txt_backup"
/etc/pam.d/login                    ""          ""

```


[User]
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.

The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.

Print the values of these variables if possible; and show some arithmetic with these values and variables.

If your language can directly enter these extreme floating point values then show it.

See also

* What Every Computer Scientist Should Know About Floating-Point Arithmetic

Related tasks

* Infinity
* Detect division by zero
* Literals/Floating point

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

Floating point limits are to a large extent implementation dependent, but currently both Raku backends (MoarVM, JVM) running on a 64 bit OS have an infinity threshold of just under 1.8e308.

```
print qq:to 'END'
positive infinity: {1.8e308}
negative infinity: {-1.8e308}
negative zero: {0e0 * -1}
not a number: {0 * 1e309}
+Inf + 2.0 = {Inf + 2}
+Inf - 10.1 = {Inf - 10.1}
0 * +Inf = {0 * Inf}
+Inf + -Inf = {Inf + -Inf}
+Inf == -Inf = {+Inf == -Inf}
(-Inf+0i)**.5 = {(-Inf+0i)**.5}
NaN + 1.0 = {NaN + 1.0}
NaN + NaN = {NaN + NaN}
NaN == NaN = {NaN == NaN}
0.0 == -0.0 = {0e0 == -0e0}
END

```

`0e0` is used to have floating point number.
Simply using `0.0` makes rational number that doesn't recognize `-0`.
`qq:to` is heredoc syntax, where `qq` means
that variables and closures (between braces) are interpolated.

Output:

```
positive infinity: Inf
negative infinity: -Inf
negative zero: -0
not a number: NaN
+Inf + 2.0 = Inf
+Inf - 10.1 = Inf
0 * +Inf = NaN
+Inf + -Inf = NaN
+Inf == -Inf = False
(-Inf+0i)**.5 = Inf+Inf\i
NaN + 1.0 = NaN
NaN + NaN = NaN
NaN == NaN = False
0.0 == -0.0 = True
```


[User]
Definition

Write down the first prime number, add the next prime number and if it is prime, add it to the series and so on. These primes are called **extreme primes**.

Task

Find and display the first **30 extreme primes** on this page.

Stretch

Find and display the **1,000th**, **2,000th**, **3,000th**, **4,000th** and **5,000th** extreme primes and for each one show the prime number **p** up to and including which primes need to be summed to obtain it.

Related (and near duplicate) tasks

* Prime numbers p for which the sum of primes less than or equal to p is prime
* Summarize primes

Reference

OEIS sequence A013918

[Assistant]
So we're just gonna keep doing the same task over and over with slightly different names?

Primes equal to the sum of the first k primes for some k.

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

say $_».&comma».fmt("%7s").batch(10).join: "\n" for
(([\+] (^∞).grep: &is-prime).grep: &is-prime)[^30,999,1999,2999,3999,4999];

```

Output:

```
      2       5      17      41     197     281   7,699   8,893  22,039  24,133
 25,237  28,697  32,353  37,561  38,921  43,201  44,683  55,837  61,027  66,463
 70,241  86,453 102,001 109,147 116,533 119,069 121,631 129,419 132,059 263,171
1,657,620,079
9,744,982,591
24,984,473,177
49,394,034,691
82,195,983,953
```

You may Attempt This Online!


[User]
A mesh defining a surface has uniquely numbered vertices, and named,
simple-polygonal faces described usually by an ordered list of edge numbers
going around the face,

For example:
External image of two faces
Rough textual version without edges:

```

      1
                        17
 7   A
             B

       11
                  23

```

* A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or

any of all the rotations of those ordered vertices.

```
      1

 7   A

       11
```

* B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any

of their rotations.

```
1
                  17

       B

 11
            23
```

Let's call the above the **perimeter format** as it traces around the perimeter.

A second format

A separate algorithm returns polygonal faces consisting of a face name and an unordered
set of edge definitions for each face.

* A single edge is described by the vertex numbers at its two ends, always in

ascending order.

* All edges for the face are given, but in an undefined order.

For example face A could be described by the edges (1, 11), (7, 11), and (1, 7)
(The order of each vertex number in an edge is ascending, but the order in
which the edges are stated is arbitrary).

Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23),
and (1, 11) in arbitrary order of the edges.

Let's call this second format the **edge format**.

Task

**1.** Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:

```
 Q: (8, 1, 3)
 R: (1, 3, 8)

 U: (18, 8, 14, 10, 12, 17, 19)
 V: (8, 14, 10, 12, 17, 19, 18)

```

**2.** Write a routine and use it to transform the following faces from edge to perimeter format.

```
 E: {(1, 11), (7, 11), (1, 7)}
 F: {(11, 23), (1, 17), (17, 23), (1, 11)}
 G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}
 H: {(1, 3), (9, 11), (3, 11), (1, 11)}

```

Show your output here.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

```
sub check-equivalence ($a, $b) { so $a.Bag eqv $b.Bag }

sub edge-to-periphery (@a is copy) {
    return Nil unless @a.List.Bag.values.all == 2;
    my @b = @a.shift.flat;
    while @a > 1 {
        for @a.kv -> $k, $v {
            if $v[0] == @b.tail {
                @b.push: $v[1];
                @a.splice($k,1);
                last
            }
            elsif $v[1] == @b.tail {
                @b.push: $v[0];
                @a.splice($k,1);
                last
            }
        }
    }
    @b
}

say 'Perimeter format equality checks:';

for (8, 1, 3), (1, 3, 8),
    (18, 8, 14, 10, 12, 17, 19), (8, 14, 10, 12, 17, 19, 18)
  -> $a, $b {
     say "({$a.join: ', '})  equivalent to  ({$b.join: ', '})? ",
         check-equivalence($a, $b)
}

say "\nEdge to perimeter format translations:";

for ((1, 11), (7, 11), (1, 7)),
    ((11, 23), (1, 17), (17, 23), (1, 11)),
    ((8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)),
    ((1, 3), (9, 11), (3, 11), (1, 11))
  {
    .gist.print;
    say "  ==>  ({.&edge-to-periphery || 'Invalid edge format'})";
}

```

Output:

```
Perimeter format equality checks:
(8, 1, 3)  equivalent to  (1, 3, 8)? True
(18, 8, 14, 10, 12, 17, 19)  equivalent to  (8, 14, 10, 12, 17, 19, 18)? True

Edge to perimeter format translations:
((1 11) (7 11) (1 7))  ==>  (1 11 7)
((11 23) (1 17) (17 23) (1 11))  ==>  (11 23 17 1)
((8 14) (17 19) (10 12) (10 14) (12 17) (8 18) (18 19))  ==>  (8 14 10 12 17 19 18)
((1 3) (9 11) (3 11) (1 11))  ==>  (Invalid edge format)
```


[User]
Consider the list of factors (divisors) of an integer, such as 12. The factors of 12 are [1, 2, 3, 4, 6, 12]. Consider all sorted sequences of the factors of n such that each succeeding number in such a sequence is a multiple of its predecessor. So, for 6,
we have the factors (divisors) [1, 2, 3, 6]. The 3 unique lists of sequential multiples starting with 1 and ending with 6 that can be derived from these factors are [1, 6], [1, 2, 6], and [1, 3, 6].

Another way to see these sequences is as an set of all the ordered factorizations of a number taken so that their product is that number (excluding 1 from the sequence). So, for 6, we would have [6], [2, 3], and [3, 2]. In this description of the sequences, we are looking at the numbers needed to multiply by, in order to generate the next element in the sequences previously listed in our first definition of the sequence type, as we described it in the preceding paragraph, above.

For example, for the factorization of 6, if the first type of sequence is [1, 6], this is generated by [6] since 1 \* 6 = 6. Similarly, the first type of sequence [1, 2, 6] is generated by the second type of sequence [2, 3] because 1 \* 2 = 2 and 2 \* 3 = 6. Similarly, [1, 3, 6] is generated by [3, 2] because 1 \* 3 = 3 and 3 \* 2 = 6.

If we count the number of such sorted sequences of multiples, or ordered factorizations, and using that count find all integers `n` for which the count of such sequences equals `n`, we have re-created the sequence of the "factor-perfect" numbers (OEIS 163272).

By some convention, on its OEIS page, the factor-perfect number sequence starts with 0 rather than 1. As might be expected
with a sequence involving factorization and combinations, finding factor-perfect numbers becomes
more demanding on CPU time as the numbers become large.

Task

* Show all 48 ordered sequences for each of the two methods for n = 48, which is the first non-trivial factor-perfect number.

According to the paper listed below by P. Erdos, the number of these sequences is

:   F
    (
    n
    )
    =

    ∑

    k
    F
    (

    n

    a

    k
    )
    +
    1
    {\displaystyle F(n)=\sum \_{k}F({\frac {n}{a\_{k}}})+1}

where a is a list of the factors of n, including n, but excluding 1. F(n) is here the same as a function for calculating the number of different factorizations according to the second definition above except that F(1)=0 (where the number of factorizations of 1 must be 1 for it to be included in the sequence of factor-perfect numbers).

* Write a program to calculate and show the first 7 numbers of the factor-perfect numbers.

Stretch task

* Calculate and show more of the subsequent numbers in the sequence.

see also

```
OEIS A163272 (Numbers k such that k = A074206(k), the number of ordered factorizations of k)
OEIS A074206 (Kalmár's [Kalmar's] problem: number of ordered factorizations of n.)
On the maximal order of numbers in the “factorisatio numerorum” problem (Klazar/Luca)
On Some Asymptotic Formulas in The Theory of The "Factorisatio Numerorum" (P. Erdos)

```

[Assistant]
**Translation of**: Wren

```
# 20221029 Raku programming solution

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

sub moreMultiples (@toSeq, @fromSeq) {
   my @oneMores = gather for @fromSeq -> \j {
      take @toSeq.clone.push(j) if j > @toSeq[*-1] and j %% @toSeq[*-1]
   }
   return () unless @oneMores.Bool;
   for 0..^@oneMores {
      @oneMores.append: moreMultiples @oneMores[$_], @fromSeq
   }
   @oneMores
}

sub erdosFactorCount (\n) {
   state %cache;
   my ($sum,@divs) = 0, |(propdiv n)[1..*];
   for @divs -> \d {
      unless %cache{my \t = n div d}:exists { %cache{t} = erdosFactorCount(t) }
      $sum += %cache{t}
   }
   ++$sum
}

my @listing = moreMultiples [1], propdiv(48);
given @listing { $_.map: *.push: 48; $_.push: [1,48] }
say @listing.elems," sequences using first definition:";
for @listing.rotor(4) -> \line { line.map: { printf "%-20s", $_ } ; say() }

my @listing2 = gather for (0..^+@listing) -> \j {
   my @seq = |@listing[j];
   @seq.append: 48 if @seq[*-1] != 48;
   take (1..^@seq).map: { @seq[$_] div @seq[$_-1] }
}
say "\n{@listing2.elems} sequences using second definition:";
for @listing2.rotor(4) -> \line { line.map: { printf "%-20s", $_ } ; say() }

say "\nOEIS A163272:";
my ($n,@fpns) = 4, 0,1;
while (@fpns < 7) { @fpns.push($n) if erdosFactorCount($n) == $n; $n += 4 }
say ~@fpns;

```

Output:

```
48 sequences using first definition:
1 2 48              1 24 48             1 3 48              1 16 48
1 4 48              1 12 48             1 6 48              1 8 48
1 2 24 48           1 2 16 48           1 2 4 48            1 2 12 48
1 2 6 48            1 2 8 48            1 2 4 24 48         1 2 4 16 48
1 2 4 12 48         1 2 4 8 48          1 2 4 12 24 48      1 2 4 8 24 48
1 2 4 8 16 48       1 2 12 24 48        1 2 6 24 48         1 2 6 12 48
1 2 6 12 24 48      1 2 8 24 48         1 2 8 16 48         1 3 24 48
1 3 12 48           1 3 6 48            1 3 12 24 48        1 3 6 24 48
1 3 6 12 48         1 3 6 12 24 48      1 4 24 48           1 4 16 48
1 4 12 48           1 4 8 48            1 4 12 24 48        1 4 8 24 48
1 4 8 16 48         1 12 24 48          1 6 24 48           1 6 12 48
1 6 12 24 48        1 8 24 48           1 8 16 48           1 48

48 sequences using second definition:
2 24                24 2                3 16                16 3
4 12                12 4                6 8                 8 6
2 12 2              2 8 3               2 2 12              2 6 4
2 3 8               2 4 6               2 2 6 2             2 2 4 3
2 2 3 4             2 2 2 6             2 2 3 2 2           2 2 2 3 2
2 2 2 2 3           2 6 2 2             2 3 4 2             2 3 2 4
2 3 2 2 2           2 4 3 2             2 4 2 3             3 8 2
3 4 4               3 2 8               3 4 2 2             3 2 4 2
3 2 2 4             3 2 2 2 2           4 6 2               4 4 3
4 3 4               4 2 6               4 3 2 2             4 2 3 2
4 2 2 3             12 2 2              6 4 2               6 2 4
6 2 2 2             8 3 2               8 2 3               48

OEIS A163272:
0 1 48 1280 2496 28672 29808
```


[User]
Definitions
:   * The factorial of   **0**   (zero)   is defined as being   1   (unity).
    * The   **Factorial Function**   of a positive integer,    *n*,    is defined as the product of the sequence:

```
                 n,   n-1,   n-2,   ...   1

```

Task

Write a function to return the factorial of a number.

Solutions can be iterative or recursive.

Support for trapping negative    *n*    errors is optional.

Related task

* Primorial numbers

[Assistant]
(formerly Perl 6)

### via User-defined Postfix Operator

[\*] is a reduction operator that multiplies all the following values together. Note that we don't need to start at 1, since the degenerate case of [\*]() correctly returns 1, and multiplying by 1 to start off with is silly in any case.

**Works with**: Rakudo version 2015.12

```
sub postfix:<!> (Int $n) { [*] 2..$n }
say 5!;
```

Output:

```
120
```

### via Memoized Constant Sequence

This approach is much more efficient for repeated use, since it automatically caches. [\\*] is the so-called triangular version of [\*]. It returns the intermediate results as a list. Note that Raku allows you to define constants lazily, which is rather helpful when your constant is of infinite size...

**Works with**: Rakudo version 2015.12

```
constant fact = 1, |[\*] 1..*;
say fact[5]
```

Output:

```
120
```


[User]
You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.

I want to produce a 1 to 1 mapping between these numbers and permutations:-

```
       0.0.0 -> 0123
       0.0.1 -> 0132
       0.1.0 -> 0213
       0.1.1 -> 0231
       0.2.0 -> 0312
       0.2.1 -> 0321
       1.0.0 -> 1023
       1.0.1 -> 1032
       1.1.0 -> 1203
       1.1.1 -> 1230
       1.2.0 -> 1302
       1.2.1 -> 1320
       2.0.0 -> 2013
       2.0.1 -> 2031
       2.1.0 -> 2103
       2.1.1 -> 2130
       2.2.0 -> 2301
       2.2.1 -> 2310
       3.0.0 -> 3012
       3.0.1 -> 3021
       3.1.0 -> 3102
       3.1.1 -> 3120
       3.2.0 -> 3201
       3.2.1 -> 3210

```

The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.

If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.

Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1

Let me work 2.0.1 and 0123

```
    step 1 n=0 g=2 Ω=2013
    step 2 n=1 g=0 so no action
    step 3 n=2 g=1 Ω=2031

```

The task:

```
 First use your function to recreate the above table.
 Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
    methods in rc's permutations task.
 Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
   39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
   51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
   use your function to crate the corresponding permutation of the following shoe of cards:
      A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
 Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe

```

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.11

Using my interpretation of the task instructions as shown on the discussion page.

```
sub postfix:<!> (Int $n) { (flat 1, [\*] 1..*)[$n] }

multi base (Int $n is copy, 'F', $length? is copy) {
    constant @fact = [\*] 1 .. *;
    my $i = $length // @fact.first: * > $n, :k;
    my $f;
    [ @fact[^$i].reverse.map: { ($n, $f) = $n.polymod($_); $f } ]
}

sub fpermute (@a is copy, *@f) { (^@f).map: { @a[$_ .. $_ + @f[$_]].=rotate(-1) }; @a }

put "Part 1: Generate table";
put $_.&base('F', 3).join('.') ~ ' -> ' ~ [0,1,2,3].&fpermute($_.&base('F', 3)).join for ^24;

put "\nPart 2: Compare 11! to 11! " ~ '¯\_(ツ)_/¯';
# This is kind of a weird request. Since we don't actually need to _generate_
# the permutations, only _count_ them: compare count of 11! vs count of 11!
put "11! === 11! : {11! === 11!}";

put "\nPart 3: Generate the given task shuffles";
my \Ω = <A♠ K♠ Q♠ J♠ 10♠ 9♠ 8♠ 7♠ 6♠ 5♠ 4♠ 3♠ 2♠ A♥ K♥ Q♥ J♥ 10♥ 9♥ 8♥ 7♥ 6♥ 5♥ 4♥ 3♥ 2♥
         A♦ K♦ Q♦ J♦ 10♦ 9♦ 8♦ 7♦ 6♦ 5♦ 4♦ 3♦ 2♦ A♣ K♣ Q♣ J♣ 10♣ 9♣ 8♣ 7♣ 6♣ 5♣ 4♣ 3♣ 2♣
>;

my @books = <
    39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
    51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
>;

put "Original deck:";
put Ω.join;

put "\n$_\n" ~ Ω[(^Ω).&fpermute($_.split: '.')].join for @books;

put "\nPart 4: Generate a random shuffle";
my @shoe = (+Ω … 2).map: { (^$_).pick };
put @shoe.join('.');
put Ω[(^Ω).&fpermute(@shoe)].join;

put "\nSeems to me it would be easier to just say: Ω.pick(*).join";
put Ω.pick(*).join;

```

Output:

```
Part 1: Generate table
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210

Part 2: Compare 11! to 11! ¯\_(ツ)_/¯
11! === 11! : True

Part 3: Generate the given task shuffles
Original deck:
A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣

39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
A♣3♣7♠4♣10♦8♦Q♠K♥2♠10♠4♦7♣J♣5♥10♥10♣K♣2♣3♥5♦J♠6♠Q♣5♠K♠A♦3♦Q♥8♣6♦9♠8♠4♠9♥A♠6♥5♣2♦7♥8♥9♣6♣7♦A♥J♦Q♦9♦2♥3♠J♥4♥K♦

51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
2♣5♣J♥4♥J♠A♠5♥A♣6♦Q♠9♣3♦Q♥J♣10♥K♣10♣5♦7♥10♦3♠8♥10♠7♠6♥5♠K♥4♦A♥4♣2♥9♦Q♣8♣7♦6♣3♥6♠7♣2♦J♦9♥A♦Q♦8♦4♠K♦K♠3♣2♠8♠9♠

Part 4: Generate a random shuffle
47.9.46.16.28.8.36.27.29.1.9.27.1.16.21.22.28.34.30.8.19.27.18.22.3.25.15.20.12.14.8.9.11.1.4.0.3.5.4.2.2.10.8.1.6.1.2.4.1.2.1
6♣5♠5♣10♥10♦6♠K♣9♦6♦K♠2♠5♦Q♠5♥Q♦8♦J♣2♣8♣A♥K♦9♣A♦2♦9♠4♣3♥A♣7♥2♥Q♥9♥4♥J♠4♠A♠3♠8♥J♥7♠K♥3♣10♣8♠Q♣6♥7♦7♣J♦3♦4♦10♠

Seems to me it would be easier to just say: Ω.pick(*).join
5♦3♠8♦10♦2♥7♠7♦Q♦A♠5♣8♣Q♠4♠2♦K♦5♠Q♥7♣10♠2♠K♠J♣9♣3♣4♥3♥4♦3♦Q♣2♣4♣J♦9♠A♣J♠10♣6♣9♦6♠10♥6♥9♥J♥7♥K♥A♦8♠A♥5♥8♥K♣6♦
```


[User]
Definition

A factorial prime is a prime number that is one less or one more than a factorial.

In other words a non-negative integer **n** corresponds to a factorial prime if either **n**! - 1 or **n**! + 1 is prime.

Examples

4 corresponds to the factorial prime 4! - 1 = 23.

5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime.

Task

Find and show here the first 10 factorial primes. As well as the prime itself show the factorial number **n** to which it corresponds and whether 1 is to be added or subtracted.

As 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!.

Stretch

If your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes.

As it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function.

If a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has.

Reference

* OEIS:A088054 - Factorial primes

Related task

* Sequence of primorial primes

[Assistant]
```
sub postfix:<!> ($n) { constant @F = (1, 1, |[\*] 2..*); @F[$n] }
sub abr ($_) { .chars < 41 ?? $_ !! .substr(0,20) ~ '..' ~ .substr(*-20) ~ " ({.chars} digits)" }

my $limit;

for 1..* {
    my \f = .!;
    ++$limit and printf "%2d: %3d! - 1 = %s\n", $limit, $_, abr f -1 if (f -1).is-prime;
    ++$limit and printf "%2d: %3d! + 1 = %s\n", $limit, $_, abr f +1 if (f +1).is-prime;
    exit if $limit >= 30
}

```

Output:

```
 1:   1! + 1 = 2
 2:   2! + 1 = 3
 3:   3! - 1 = 5
 4:   3! + 1 = 7
 5:   4! - 1 = 23
 6:   6! - 1 = 719
 7:   7! - 1 = 5039
 8:  11! + 1 = 39916801
 9:  12! - 1 = 479001599
10:  14! - 1 = 87178291199
11:  27! + 1 = 10888869450418352160768000001
12:  30! - 1 = 265252859812191058636308479999999
13:  32! - 1 = 263130836933693530167218012159999999
14:  33! - 1 = 8683317618811886495518194401279999999
15:  37! + 1 = 13763753091226345046..79581580902400000001 (44 digits)
16:  38! - 1 = 52302261746660111176..24100074291199999999 (45 digits)
17:  41! + 1 = 33452526613163807108..40751665152000000001 (50 digits)
18:  73! + 1 = 44701154615126843408..03680000000000000001 (106 digits)
19:  77! + 1 = 14518309202828586963..48000000000000000001 (114 digits)
20:  94! - 1 = 10873661566567430802..99999999999999999999 (147 digits)
21: 116! + 1 = 33931086844518982011..00000000000000000001 (191 digits)
22: 154! + 1 = 30897696138473508879..00000000000000000001 (272 digits)
23: 166! - 1 = 90036917057784373664..99999999999999999999 (298 digits)
24: 320! + 1 = 21161033472192524829..00000000000000000001 (665 digits)
25: 324! - 1 = 22889974601791023211..99999999999999999999 (675 digits)
26: 340! + 1 = 51008644721037110809..00000000000000000001 (715 digits)
27: 379! - 1 = 24840307460964707050..99999999999999999999 (815 digits)
28: 399! + 1 = 16008630711655973815..00000000000000000001 (867 digits)
29: 427! + 1 = 29063471769607348411..00000000000000000001 (940 digits)
30: 469! - 1 = 67718096668149510900..99999999999999999999 (1051 digits)
```


[User]
Definition

A factorion is a natural number that equals the sum of the factorials of its digits.

Example

**145**   is a factorion in base **10** because:

**```
          1! + 4! + 5!   =   1 + 24 + 120   =   145

```**

It can be shown (see talk page) that no factorion in base **10** can exceed   **1,499,999**.

Task

Write a program in your language to demonstrate, by calculating and printing out the factorions, that:

:   * There are   **3**   factorions in base   **9**
    * There are   **4**   factorions in base **10**
    * There are   **5**   factorions in base **11**
    * There are   **2**   factorions in base **12**     (up to the same upper bound as for base **10**)

See also
:   * **Wikipedia article**
    * **OEIS:A014080 - Factorions in base 10**
    * **OEIS:A193163 - Factorions in base n**

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

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

constant $limit = 1500000;

constant $bases = 9 .. 12;

my @result;

$bases.map: -> $base {

    @result[$base] = "\nFactorions in base $base:\n1 2";

    sink (1 .. $limit div $base).map: -> $i {
        my $product = $i * $base;
        my $partial;

        for $i.polymod($base xx *) {
            $partial += @factorial[$_];
            last if $partial > $product
        }

        next if $partial > $product;

        my $sum;

        for ^$base {
            last if ($sum = $partial + @factorial[$_]) > $product + $_;
            @result[$base] ~= " $sum" and last if $sum == $product + $_
        }
    }
}

.say for @result[$bases];

```

Output:

```
Factorions in base 9:
1 2 41282

Factorions in base 10:
1 2 145 40585

Factorions in base 11:
1 2 26 48 40472

Factorions in base 12:
1 2
```


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

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

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

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

Some basic properties:

* The only Lyndon word that ends with 0 is 0.
* **Proof.** If s0 is a Lyndon word, and s is not empty, then s0 < 0s. If s contains 1 somewhere, then s0 > 0s. Therefore s has only 0. But then s0 = 0s, contradiction.
* The lexicographic order *is* a total order on the Lyndon words.
* **Proof.** For, the only way for two different strings s, s' to have the same lexicographic ordering is for one of them to pad to the other. We can assume that s00...0 = s'. If that is so, then s00...0 is a Lyndon word that ends with 0, so it is just 0, and so s is a Lyndon word that is also empty, contradiction.

The Chen–Fox–Lyndon theorem states that any string is uniquely factorizable into a sequence of Lyndon words non-decreasing in lexicographic order. Duval's algorithm computes this in O(length of input) time and and O(1) space.[1] See [2] for a description of Duval's algorithm.

[Assistant]
**Translation of**: Julia

```
# 20240213 Raku programming solution

sub chenfoxlyndonfactorization(Str $s) {
   my ($n, $i, @factorization) = $s.chars, 1;
   while $i <= $n {
      my ($j, $k) = $i X+ (1, 0);
      while $j <= $n && substr($s, $k-1, 1) <= substr($s, $j-1, 1) {
         substr($s, $k-1, 1) < substr($s, $j++ -1, 1) ?? ( $k = $i ) !! $k++;
      }
      while $i <= $k {
         @factorization.push: substr($s, $i-1, $j-$k);
         $i += $j - $k
      }
   }
   die unless $s eq [~] @factorization;
   return @factorization
}

my $m = "0";
for ^7 { $m ~= $m.trans('0' => '1', '1' => '0') }
say chenfoxlyndonfactorization($m);

```

Output:

Same as Julia example.

You may Attempt This Online!


[User]
A Mersenne number is a number in the form of 2P-1.

If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).

In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test.

There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1).
Some languages already have built-in implementations of this exponent-and-mod operation (called *modPow* or similar).

The following is how to implement this *modPow* yourself:

For example, let's compute 223 mod 47.
Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it.
Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47.
Use the result of the modulo from the last step as the initial value of square in the next step:

```
                  remove       optional
      square      top bit   multiply by 2   mod 47
   ────────────   ───────   ─────────────   ──────
   1*1 = 1        1  0111   1*2 = 2            2
   2*2 = 4        0   111      no              4
   4*4 = 16       1    11   16*2 = 32         32
   32*32 = 1024   1     1   1024*2 = 2048     27
   27*27 = 729    1         729*2 = 1458       1

```

Since 223 mod 47 = 1, 47 is a factor of 2P-1.
(To see this, subtract 1 from both sides: 223-1 = 0 mod 47.)
Since we've shown that 47 is a factor, 223-1 is not prime.
Further properties of Mersenne numbers allow us to refine the process even more.
Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8.
Finally any potential factor q must be prime.
As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N).

These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1.

Task

Using the above method find a factor of 2929-1 (aka M929)

Related tasks

* count in factors
* prime decomposition
* factors of an integer
* Sieve of Eratosthenes
* primality by trial division
* trial factoring of a Mersenne number
* partition an integer X into N primes
* sequence of primes by Trial Division

See also

* Computers in 1948: 2127 - 1
         (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)

[Assistant]
(formerly Perl 6)

```
sub mtest($bits, $p) {
    my @bits = $bits.base(2).comb;
    loop (my $sq = 1; @bits; $sq %= $p) {
        $sq ×= $sq;
        $sq += $sq if 1 == @bits.shift;
    }
    $sq == 1;
}

for flat 2 .. 60, 929 -> $m {
    next unless is-prime($m);
    my $f = 0;
    my $x = 2**$m - 1;
    my $q;
    for 1..* -> $k {
        $q = 2 × $k × $m + 1;
        next unless $q % 8 == 1|7 or is-prime($q);
        last if $q × $q > $x or $f = mtest($m, $q);
    }

    say $f ?? "M$m = $x\n\t= $q × { $x div $q }"
           !! "M$m = $x is prime";
}

```

Output:

```
M2 = 3 is prime
M3 = 7 is prime
M5 = 31 is prime
M7 = 127 is prime
M11 = 2047
	= 23 × 89
M13 = 8191 is prime
M17 = 131071 is prime
M19 = 524287 is prime
M23 = 8388607
	= 47 × 178481
M29 = 536870911
	= 233 × 2304167
M31 = 2147483647 is prime
M37 = 137438953471
	= 223 × 616318177
M41 = 2199023255551
	= 13367 × 164511353
M43 = 8796093022207
	= 431 × 20408568497
M47 = 140737488355327
	= 2351 × 59862819377
M53 = 9007199254740991
	= 6361 × 1416003655831
M59 = 576460752303423487
	= 179951 × 3203431780337
M929 = 4538015467766671944574165338592225830478699345884382504442663144885072806275648112625635725391102144133907238129251016389326737199538896813326509341743147661691195191795226666084858428449394948944821764472508048114220424520501343042471615418544488778723282182172070046459244838911
	= 13007 × 348890248924938259750454781163390930305120269538278042934009621348894657205785201247454118966026150852149399410259938217062100192168747352450719561908445272675574320888385228421992652298715687625495638077382028762529439880103124705348782610789919949159935587158612289264184273
```