[User]
Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication

**Algorithm:**

Given two numbers where the **dividend** is to be divided by the **divisor**:

1. Start the construction of a table of two columns: **`powers_of_2`**, and **`doublings`**; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
2. Create the second row with columns of 2 (i.e 2^1), and 2 \* divisor in order.
3. Continue with successive i’th rows of 2^i and 2^i \* divisor.
4. Stop adding rows, and keep only those rows, where 2^i \* divisor is less than or equal to the dividend.
5. We now assemble two separate sums that both start as zero, called here **answer** and **accumulator**
6. Consider each row of the table, in the *reverse* order of its construction.
7. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers\_of\_2 cell value to the answer.
8. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
    (And the remainder is given by the absolute value of accumulator - dividend).

**Example: 580 / 34**

**Table creation:**

:   :   :   | powers\_of\_2 | doublings |
            | --- | --- |
            | 1 | 34 |
            | 2 | 68 |
            | 4 | 136 |
            | 8 | 272 |
            | 16 | 544 |

**Initialization of sums:**

:   :   :   | powers\_of\_2 | doublings | answer | accumulator |
            | --- | --- | --- | --- |
            | 1 | 34 |  |  |
            | 2 | 68 |  |  |
            | 4 | 136 |  |  |
            | 8 | 272 |  |  |
            | 16 | 544 |  |  |
            |  |  | 0 | 0 |

**Considering table rows, bottom-up:**

When a row is considered it is shown ~~crossed out~~ if it is not accumulated, or **bold** if the row causes summations.

:   :   :   | powers\_of\_2 | doublings | answer | accumulator |
            | --- | --- | --- | --- |
            | 1 | 34 |  |  |
            | 2 | 68 |  |  |
            | 4 | 136 |  |  |
            | 8 | 272 |  |  |
            | **16** | **544** | 16 | 544 |

:   :   :   | powers\_of\_2 | doublings | answer | accumulator |
            | --- | --- | --- | --- |
            | 1 | 34 |  |  |
            | 2 | 68 |  |  |
            | 4 | 136 |  |  |
            | ~~8~~ | ~~272~~ | 16 | 544 |
            | **16** | **544** |  |  |

:   :   :   | powers\_of\_2 | doublings | answer | accumulator |
            | --- | --- | --- | --- |
            | 1 | 34 |  |  |
            | 2 | 68 |  |  |
            | ~~4~~ | ~~136~~ | 16 | 544 |
            | ~~8~~ | ~~272~~ |  |  |
            | **16** | **544** |  |  |

:   :   :   | powers\_of\_2 | doublings | answer | accumulator |
            | --- | --- | --- | --- |
            | 1 | 34 |  |  |
            | ~~2~~ | ~~68~~ | 16 | 544 |
            | ~~4~~ | ~~136~~ |  |  |
            | ~~8~~ | ~~272~~ |  |  |
            | **16** | **544** |  |  |

:   :   :   | powers\_of\_2 | doublings | answer | accumulator |
            | --- | --- | --- | --- |
            | **1** | **34** | 17 | 578 |
            | ~~2~~ | ~~68~~ |  |  |
            | ~~4~~ | ~~136~~ |  |  |
            | ~~8~~ | ~~272~~ |  |  |
            | **16** | **544** |  |  |

Answer

So 580 divided by 34 using the Egyptian method is **`17`** remainder (578 - 580) or **`2`**.

Task

The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.

* Functions should be clear interpretations of the algorithm.
* Use the function to divide 580 by 34 and show the answer **here, on this page**.

Related tasks
:   * Egyptian fractions
    * Ethiopian multiplication

References
:   * Egyptian Number System

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.07

### Normal version

Only works with positive real numbers, not negative or complex.

```
sub egyptian-divmod (Real $dividend is copy where * >= 0, Real $divisor where * > 0) {
    my $accumulator = 0;
    ([1, $divisor], { [.[0] + .[0], .[1] + .[1]] } … ^ *.[1] > $dividend)
      .reverse.map: { $dividend -= .[1], $accumulator += .[0] if $dividend >= .[1] }
    $accumulator, $dividend;
}

#TESTING
for 580,34, 578,34, 7532795332300578,235117 -> $n, $d {
    printf "%s divmod %s = %s remainder %s\n",
        $n, $d, |egyptian-divmod( $n, $d )
}

```

Output:

```
580 divmod 34 = 17 remainder 2
578 divmod 34 = 17 remainder 0
7532795332300578 divmod 235117 = 32038497141 remainder 81
```

### More "Egyptian" version

As a preceding version was determined to be "let's just say ... not Egyptian" we submit an alternate which is hopefully more "Egyptian". Now only handles positive Integers up to 10 million, mostly due to limitations on Egyptian notation for numbers.

Note: if the below is just a mass of "unknown glyph" boxes, try installing Googles free Noto Sans Egyptian Hieroglyphs font.

This is intended to be humorous and should not be regarded as good (or even sane) programming practice. That being said, 𓂽 & 𓂻 really are the ancient Egyptian symbols for addition and subtraction, and the Egyptian number notation is as accurate as possible. Everything else owes more to whimsy than rigor.

```
my (\𓄤, \𓄊, \𓎆, \𓄰) = (0, 1, 10, 10e7);
sub infix:<𓂽> { $^𓃠 + $^𓃟 }
sub infix:<𓂻> { $^𓃲 - $^𓆊 }
sub infix:<𓈝> { $^𓃕 < $^𓃢 }
sub 𓁶 (Int \𓆉) {
    my \𓁢 = [«'' 𓏺 𓏻 𓏼 𓏽 𓏾 𓏿 𓐀 𓐁 𓐂»], [«'' 𓎆 𓎏 𓎐 𓎑 𓎊 𓎋 𓎌 𓎍 𓎎»],
      [«'' 𓍢 𓍣 𓍤 𓍥 𓍦 𓍧 𓍨 𓍩 𓍪»], [«'' 𓆼 𓆽 𓆾 𓆿 𓇀 𓇁 𓇂 𓇃 𓇄»],
      [«'' 𓂭 𓂮 𓂯 𓂰 𓂱 𓂲 𓂳 𓂴 𓂵»], ['𓆐' Xx ^𓎆], ['𓁨' Xx ^𓎆];
    ([~] 𓆉.polymod( 𓎆 xx * ).map( { 𓁢[$++;$_] } ).reverse) || '𓄤'
}

sub infix:<𓅓> (Int $𓂀 is copy where 𓄤 𓂻 𓄊 𓈝 * 𓈝 𓄰, Int \𓌳 where 𓄤 𓈝 * 𓈝 𓄰) {
    my $𓎦 = 𓄤;
    ([𓄊,𓌳], { [.[𓄤] 𓂽 .[𓄤], .[𓄊] 𓂽 .[𓄊]] } … ^$𓂀 𓈝 *.[𓄊])
      .reverse.map: { $𓂀 𓂻= .[𓄊], $𓎦 𓂽= .[𓄤] if .[𓄊] 𓈝 ($𓂀 𓂽 𓄊) }
    $𓎦, $𓂀;
}

#TESTING
for 580,34, 578,34, 2300578,23517 -> \𓃾, \𓆙 {
    printf "%s divmod %s = %s remainder %s =OR= %s 𓅓 %s = %s remainder %s\n",
        𓃾, 𓆙, |(𓃾 𓅓 𓆙), (𓃾, 𓆙, |(𓃾 𓅓 𓆙))».&𓁶;
}

```

Output:

```
580 divmod 34 = 17 remainder 2 =OR= 𓍦𓎍 𓅓 𓎐𓏽 = 𓎆𓐀 remainder 𓏻
578 divmod 34 = 17 remainder 0 =OR= 𓍦𓎌𓐁 𓅓 𓎐𓏽 = 𓎆𓐀 remainder 𓄤
2300578 divmod 23517 = 97 remainder 19429 =OR= 𓁨𓁨𓆐𓆐𓆐𓍦𓎌𓐁 𓅓 𓂮𓆾𓍦𓎆𓐀 = 𓎎𓐀 remainder 𓂭𓇄𓍥𓎏𓐂
```


[User]
An *Eisenstein integer* is a non-unit Gaussian integer a + bω where ω(1+ω) = -1, and a and b are integers.

ω is generally chosen as a cube root of unity:

ω
=

−
1
+
i

3
2
=

e

i
2
π

/
3
{\displaystyle {\displaystyle {\displaystyle \omega ={\frac {-1+i{\sqrt {3}}}{2}}=e^{i2\pi /3}}}}

As with a Gaussian integer, any Eisenstein integer is either a unit (an integer with a multiplicative inverse [±1, ±ω, ±(ω^-1)]),
a prime (a number p such that if p divides xy, then p necessarily divides either x or y), or composite (a product of primes).

An Eisenstein integer a + bω is a prime if either it is a product of a unit and an integer prime p such that p % 3 == 2 or norm(a + bω) is an integer prime.

Eisenstein numbers can be generated by choosing any a and b such that a and b are integers. To allow generation in a relatively fixed order, such numbers can be ordered by their 2-norm or *norm*:

```
    norm(eisenstein integer(a, b)) = |a + bω|² =

              a

                2

            −
            a
            b
            +

              b

                2

    {\displaystyle {\displaystyle a^{2}-ab+b^{2}}}

```

Task

* Find, and show here as their complex number values, the first **100** (by norm order) Eisenstein primes nearest 0.

Stretch

* Plot in the complex plane at least the first 2000 such numbers (again, as found with norm closest to 0).

See also

* [Wikipedia entry for Eisenstein\_integer] * [Observable entry on Eisenstein primes]

[Assistant]
```
my \ω = exp 2i × π/3;

sub norm    (@p) { @p[0]² - @p[0]×@p[1] + @p[1]² }
sub display (@p) { (@p[0] + ω×@p[1]).reals».fmt('%+8.4f').join ~ 'i' }

my @E = gather (-10..10 X -10..10).map: -> (\a,\b) {
    take (a,b) if 0 == a|b || a == b ?? (.is-prime and 2 == $_ mod 3 given (a,b)».abs.max) !! norm((a,b)).is-prime
}

(@E.sort: *.&norm).head(100).map(*.&display).batch(4).join("\n").say;

```

Output:

```
 -1.5000 -0.8660i  -0.0000 -1.7321i  -1.5000 +0.8660i  +1.5000 -0.8660i
 +0.0000 +1.7321i  +1.5000 +0.8660i  -1.0000 -1.7321i  -2.0000 +0.0000i
 +1.0000 -1.7321i  -1.0000 +1.7321i  +2.0000 +0.0000i  +1.0000 +1.7321i
 -2.0000 -1.7321i  -2.5000 -0.8660i  -0.5000 -2.5981i  -2.5000 +0.8660i
 +0.5000 -2.5981i  -2.0000 +1.7321i  +2.0000 -1.7321i  -0.5000 +2.5981i
 +2.5000 -0.8660i  +0.5000 +2.5981i  +2.5000 +0.8660i  +2.0000 +1.7321i
 -2.5000 -2.5981i  -3.5000 -0.8660i  -1.0000 -3.4641i  -3.5000 +0.8660i
 +1.0000 -3.4641i  -2.5000 +2.5981i  +2.5000 -2.5981i  -1.0000 +3.4641i
 +3.5000 -0.8660i  +1.0000 +3.4641i  +3.5000 +0.8660i  +2.5000 +2.5981i
 -3.5000 -2.5981i  -4.0000 -1.7321i  -0.5000 -4.3301i  -4.0000 +1.7321i
 +0.5000 -4.3301i  -3.5000 +2.5981i  +3.5000 -2.5981i  -0.5000 +4.3301i
 +4.0000 -1.7321i  +0.5000 +4.3301i  +4.0000 +1.7321i  +3.5000 +2.5981i
 -2.5000 -4.3301i  -5.0000 +0.0000i  +2.5000 -4.3301i  -2.5000 +4.3301i
 +5.0000 +0.0000i  +2.5000 +4.3301i  -3.5000 -4.3301i  -5.5000 -0.8660i
 -2.0000 -5.1962i  -5.5000 +0.8660i  +2.0000 -5.1962i  -3.5000 +4.3301i
 +3.5000 -4.3301i  -2.0000 +5.1962i  +5.5000 -0.8660i  +2.0000 +5.1962i
 +5.5000 +0.8660i  +3.5000 +4.3301i  -5.0000 -3.4641i  -5.5000 -2.5981i
 -0.5000 -6.0622i  -5.5000 +2.5981i  +0.5000 -6.0622i  -5.0000 +3.4641i
 +5.0000 -3.4641i  -0.5000 +6.0622i  +5.5000 -2.5981i  +0.5000 +6.0622i
 +5.5000 +2.5981i  +5.0000 +3.4641i  -4.0000 -5.1962i  -6.5000 -0.8660i
 -2.5000 -6.0622i  -6.5000 +0.8660i  +2.5000 -6.0622i  -4.0000 +5.1962i
 +4.0000 -5.1962i  -2.5000 +6.0622i  +6.5000 -0.8660i  +2.5000 +6.0622i
 +6.5000 +0.8660i  +4.0000 +5.1962i  -6.5000 -4.3301i  -7.0000 -3.4641i
 -0.5000 -7.7942i  -7.0000 +3.4641i  +0.5000 -7.7942i  -6.5000 +4.3301i
 +6.5000 -4.3301i  -0.5000 +7.7942i  +7.0000 -3.4641i  +0.5000 +7.7942i

```


[User]
The sequence is from the natural numbers and is defined by:

* `a(1) = 1`;
* `a(2) = Start = 2`;
* for n > 2, `a(n)` shares at least one prime factor with `a(n-1)` and is the *smallest* such natural number *not already used*.

The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).

Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call:

* The sequence described above , starting `1, 2, ...` the `EKG(2)` sequence;
* the sequence starting `1, 3, ...` the `EKG(3)` sequence;
* ... the sequence starting `1, N, ...` the `EKG(N)` sequence.

Convergence

If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential **state**. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.
`EKG(N1)` and `EKG(N2)` are said to to have converged at and after generation `a(c)` if `state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c))`.

Task

1. Calculate and show here the first 10 members of `EKG(2)`.
2. Calculate and show here the first 10 members of `EKG(5)`.
3. Calculate and show here the first 10 members of `EKG(7)`.
4. Calculate and show here the first 10 members of `EKG(9)`.
5. Calculate and show here the first 10 members of `EKG(10)`.
6. Calculate and show here at which term `EKG(5)` and `EKG(7)` converge   (**stretch goal**).

Related Tasks

1. Greatest common divisor
2. Sieve of Eratosthenes
3. Yellowstone sequence

Reference

* The EKG Sequence and the Tree of Numbers. (Video).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo Star version 2018.04.1

```
sub infix:<shares-divisors-with> { ($^a gcd $^b) > 1 }

sub next-EKG ( *@s ) {
    return first {
        @s ∌ $_  and  @s.tail shares-divisors-with $_
    }, 2..*;
}

sub EKG ( Int $start ) {  1, $start, &next-EKG … *  }

sub converge-at ( @ints ) {
    my @ekgs = @ints.map: &EKG;

    return (2 .. *).first: -> $i {
        [==]  @ekgs.map(     *.[$i]     ) and
        [===] @ekgs.map( *.head($i).Set )
    }
}

say "EKG($_): ", .&EKG.head(10) for 2, 5, 7, 9, 10;

for [5, 7], [2, 5, 7, 9, 10] -> @ints {
    say "EKGs of (@ints[]) converge at term {$_+1}" with converge-at(@ints);
}

```

Output:

```
EKG(2): (1 2 4 6 3 9 12 8 10 5)
EKG(5): (1 5 10 2 4 6 3 9 12 8)
EKG(7): (1 7 14 2 4 6 3 9 12 8)
EKG(9): (1 9 3 6 2 4 8 10 5 15)
EKG(10): (1 10 2 4 6 3 9 12 8 14)
EKGs of (5 7) converge at term 21
EKGs of (2 5 7 9 10) converge at term 45

```


[User]
This task is similar to:

:   :   * Matrix multiplication
        * Matrix transposition

Task

Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.

Implement:

:   :   :   * addition
            * subtraction
            * multiplication
            * division
            * exponentiation

Extend the task if necessary to include additional basic operations, which should not require their own specialised task.

[Assistant]
(formerly Perl 6)
Raku already implements this and other metaoperators as higher-order functions (cross, zip, reduce, triangle, etc.) that are usually accessed through a meta-operator syntactic sugar that is productive over all appropriate operators, including user-defined ones. In this case, a dwimmy element-wise operator (generically known as a "hyper") is indicated by surrounding the operator with double angle quotes. Hypers dwim on the pointy end with cyclic APL semantics as necessary. You can turn the quote the other way to suppress dwimmery on that end. In this case we could have used »op» instead of «op» since the short side is always on the right.

```
my @a =
    [1,2,3],
    [4,5,6],
    [7,8,9];

sub msay(@x) {
    say .map( { ($_%1) ?? $_.nude.join('/') !! $_ } ).join(' ') for @x;
    say '';
}

msay @a «+» @a;
msay @a «-» @a;
msay @a «*» @a;
msay @a «/» @a;
msay @a «+» [1,2,3];
msay @a «-» [1,2,3];
msay @a «*» [1,2,3];
msay @a «/» [1,2,3];
msay @a «+» 2;
msay @a «-» 2;
msay @a «*» 2;
msay @a «/» 2;

# In addition to calling the underlying higher-order functions directly, it's possible to name a function.

sub infix:<M+> (\l,\r) { l <<+>> r }

msay @a M+ @a;
msay @a M+ [1,2,3];
msay @a M+ 2;

```

Output:

```
 2 4 6
 8 10 12
 14 16 18

 0 0 0
 0 0 0
 0 0 0

 1 4 9
 16 25 36
 49 64 81

 1 1 1
 1 1 1
 1 1 1

 2 3 4
 6 7 8
 10 11 12

 0 1 2
 2 3 4
 4 5 6

 1 2 3
 8 10 12
 21 24 27

 1 2 3
 2 5/2 3
 7/3 8/3 3

 3 4 5
 6 7 8
 9 10 11

 -1 0 1
 2 3 4
 5 6 7

 2 4 6
 8 10 12
 14 16 18

 1/2 1 3/2
 2 5/2 3
 7/2 4 9/2

 2 4 6
 8 10 12
 14 16 18

 2 3 4
 6 7 8
 10 11 12

 3 4 5
 6 7 8
 9 10 11
```


[User]
An **elementary cellular automaton** is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.

The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.

Task

Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.

The space state should *wrap*: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.

This task is basically a generalization of one-dimensional cellular automata.

Related tasks

* One-dimensional cellular automata

See also

* Cellular automata (natureofcode.com)

[Assistant]
(formerly Perl 6)

Using the Automaton class defined at One-dimensional\_cellular\_automata#Raku:

```
class Automaton {
    has $.rule;
    has @.cells;
    has @.code = $!rule.fmt('%08b').flip.comb».Int;

    method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" }

    method succ {
        self.new: :$!rule, :@!code, :cells(
            @!code[
                    4 «*« @!cells.rotate(-1)
                »+« 2 «*« @!cells
                »+«       @!cells.rotate(1)
            ]
        )
    }
}

my @padding = 0 xx 10;

my Automaton $a .= new:
    :rule(30),
    :cells(flat @padding, 1, @padding);

say $a++ for ^10;

```

Output:

```
|          #          |
|         ###         |
|        ##  #        |
|       ## ####       |
|      ##  #   #      |
|     ## #### ###     |
|    ##  #    #  #    |
|   ## ####  ######   |
|  ##  #   ###     #  |
| ## #### ##  #   ### |

```


[User]
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.

To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.

Examples:

```
1        ->   ..., 0, 0,      1,      0, 0, ...
0, 1     ->   ..., 1, 1,   0, 1,      0, 0, ...
1, 0, 1  ->   ..., 0, 0,   1, 0, 1,   0, 0, ...

```

More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.

[Assistant]
(formerly Perl 6)
This version, while it is *capable* of working with infinite length cellular automata, makes the assumption that any cells which have not been explicitly examined are in a 'null' state, neither '0' or '1'. Further it makes the assumption that a null cell, on being examined, initially contains nothing (░). Otherwise it would take infinite time to calculate every row and would be exceptionally boring to watch.

Based heavily on the code from the One-dimensional cellular automata task. Example uses rule 90 (Sierpinski triangle).

```
class Automaton {
    has $.rule;
    has @.cells;
    has @.code = $!rule.fmt('%08b').flip.comb».Int;

    method gist { @!cells.map({+$_ ?? '▲' !! '░'}).join }

    method succ {
        self.new: :$!rule, :@!code, :cells(
            ' ',
            |@!code[
                    4 «*« @!cells.rotate(-1)
                »+« 2 «*« @!cells
                »+«       @!cells.rotate(1)
            ],
            ' '
        )
    }
}

my Automaton $a .= new: :rule(90), :cells(flat '010'.comb);

# display the first 20 rows
say $a++ for ^20;

# then calculate the other infinite number of rows, (may take a while)
$a++ for ^Inf;

```

Output:

```
░▲░
░▲░▲░
░▲░░░▲░
░▲░▲░▲░▲░
░▲░░░░░░░▲░
░▲░▲░░░░░▲░▲░
░▲░░░▲░░░▲░░░▲░
░▲░▲░▲░▲░▲░▲░▲░▲░
░▲░░░░░░░░░░░░░░░▲░
░▲░▲░░░░░░░░░░░░░▲░▲░
░▲░░░▲░░░░░░░░░░░▲░░░▲░
░▲░▲░▲░▲░░░░░░░░░▲░▲░▲░▲░
░▲░░░░░░░▲░░░░░░░▲░░░░░░░▲░
░▲░▲░░░░░▲░▲░░░░░▲░▲░░░░░▲░▲░
░▲░░░▲░░░▲░░░▲░░░▲░░░▲░░░▲░░░▲░
░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░
░▲░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▲░
░▲░▲░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▲░▲░
░▲░░░▲░░░░░░░░░░░░░░░░░░░░░░░░░░░▲░░░▲░
░▲░▲░▲░▲░░░░░░░░░░░░░░░░░░░░░░░░░▲░▲░▲░▲░
^C

```


[User]
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, for a long time rule 30 was used by the Mathematica software for its default random number generator.

Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.

The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant.

You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.

For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.

Reference

* Cellular automata: Is Rule 30 random? (PDF).

[Assistant]
(formerly Perl 6)

```
class Automaton {
    has $.rule;
    has @.cells handles <AT-POS>;
    has @.code = $!rule.fmt('%08b').flip.comb».Int;

    method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" }

    method succ {
        self.new: :$!rule, :@!code, :cells(
            @!code[
                    4 «*« @!cells.rotate(-1)
                »+« 2 «*« @!cells
                »+«       @!cells.rotate(1)
            ]
        )
    }
}

my Automaton $a .= new: :rule(30), :cells( flat 1, 0 xx 100 );

say :2[$a++[0] xx 8] xx 10;

```

Output:

```
220 197 147 174 117 97 149 171 240 241
```


[User]
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures.

The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol.

In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the **x** and **y** coordinates of any point on the curve:

:   :   :   :   y

                2
                =

                x

                3
                +
                a
                x
                +
                b
                {\displaystyle {\displaystyle y^{2}=x^{3}+ax+b}}

**a** and **b** are arbitrary parameters that define the specific curve which is used.

For this particular task, we'll use the following parameters:

:   :   :   :   a=0**,**   b=7

The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it.

To do so we define an   internal composition   rule with an additive notation **+**,   such that for any three distinct points **P**, **Q** and **R** on the curve, whenever these points are aligned, we have:

:   :   :   :   P + Q + R = 0

Here   **0**   (zero)   is the *infinity point*,   for which the **x** and **y** values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry.

We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition.

This was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such:

Given any three aligned points **P**, **Q** and **R**,   we define the sum   **S = P + Q**   as the point (possibly the infinity point) such that   **S**, **R**   and the infinity point are aligned.

Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points **S** and **R** can be aligned with the infinity point if and only if **S** and **R** are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet).

**S** is thus defined as the symmetric of **R** towards the **x** axis.

The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.

You will use the **a** and **b** parameters of secp256k1, i.e. respectively zero and seven.

*Hint*:   You might need to define a "doubling" function, that returns **P+P** for any given point **P**.

*Extra credit*:   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,

for any point **P** and integer **n**,   the point **P + P + ... + P**     (**n** times).

[Assistant]
(formerly Perl 6)

```
module EC {
  our ($A, $B) = (0, 7);

  our class Point {
    has ($.x, $.y);
    multi method new(
        $x, $y where $y**2 == $x**3 + $A*$x + $B
        ) { samewith :$x, :$y }
    multi method gist { "EC Point at x=$.x, y=$.y" }
    multi method gist(::?CLASS:U:) { 'Point at horizon' }
  }

  multi prefix:<->(Point $p) is export { Point.new: x => $p.x, y => -$p.y }
  multi prefix:<->(Point:U) is export { Point }
  multi infix:<->(Point $a, Point $b) is export { $a + -$b }

  multi infix:<+>(Point:U $, Point $p) is export { $p }
  multi infix:<+>(Point $p, Point:U) is export { $p }

  multi infix:<*>(Point $u, Int $n) is export { $n * $u }
  multi infix:<*>(Int $n, Point:U) is export { Point }
  multi infix:<*>(0, Point) is export { Point }
  multi infix:<*>(1, Point $p) is export { $p }
  multi infix:<*>(2, Point $p) is export {
    my $l = (3*$p.x**2 + $A) / (2 *$p.y);
    my $y = $l*($p.x - my $x = $l**2 - 2*$p.x) - $p.y;
    $p.new(:$x, :$y);
  }
  multi infix:<*>(Int $n where $n > 2, Point $p) is export {
    2 * ($n div 2 * $p) + $n % 2 * $p;
  }

  multi infix:<+>(Point $p, Point $q) is export {
    if $p.x ~~ $q.x {
      return $p.y ~~ $q.y ?? 2 * $p !! Point;
    }
    else {
      my $slope = ($q.y - $p.y) / ($q.x - $p.x);
      my $y = $slope*($p.x - my $x = $slope**2 - $p.x - $q.x) - $p.y;
      return $p.new(:$x, :$y);
    }
  }

}

import EC;

say my $p = EC::Point.new: x => $_, y => sqrt(abs($_**3 + $EC::A*$_ + $EC::B)) given 1;
say my $q = EC::Point.new: x => $_, y => sqrt(abs($_**3 + $EC::A*$_ + $EC::B)) given 2;
say my $s = $p + $q;

use Test;
is abs(($p.x - $q.x)*(-$s.y - $q.y) - ($p.y - $q.y)*($s.x - $q.x)), 0, "S, P and Q are aligned";

```

Output:

```
EC Point at x=1, y=2.8284271247461903
EC Point at x=2, y=3.872983346207417
EC Point at x=-1.9089023002066448, y=0.21008487055753378
ok 1 - S, P and Q are aligned
```


[User]
Elliptic curves.

An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
**y²= x³ + ax + b**, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set **E(ℤp)** consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining equation, together with 𝒪.

There is a rule for adding two points on an elliptic curve to give a third point.
This addition operation and the set of points E(ℤp) form a group with identity 𝒪.
It is this group that is used in the construction of elliptic curve cryptosystems.

The addition rule — which can be explained geometrically — is summarized as follows:

```
1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp).

2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪.

3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q.
   Then R = P + Q = (xR, yR), where

   xR = λ^2 - xP - xQ
   yR = λ·(xP - xR) - yP,

   with

   λ = (yP - yQ) / (xP - xQ) if P ≠ Q,
       (3·xP·xP + a) / 2·yP  if P = Q (point doubling).

```

Remark: there already is a task page requesting “a simplified (without modular arithmetic)
version of the elliptic curve arithmetic”.
Here we do add modulo operations. If also the domain is changed from reals to rationals,
the elliptic curves are no longer continuous but break up into a finite number of distinct points.
In that form we use them to implement ECDSA:

Elliptic curve digital signature algorithm.

A digital signature is the electronic analogue of a hand-written signature
that convinces the recipient that a message has been sent intact by the presumed sender.
Anyone with access to the public key of the signer may verify this signature.
Changing even a single bit of a signed message will cause the verification procedure to fail.

**ECDSA key generation.** Party A does the following:
1. Select an elliptic curve E defined over ℤp.
 The number of points in E(ℤp) should be divisible by a large prime r.
2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪).
3. Select a random integer s in the interval [1, r - 1].
4. Compute W = sG.
 The public key is (E, G, r, W), the private key is s.

**ECDSA signature computation.** To sign a message m, A does the following:
1. Compute message representative f = H(m), using a
cryptographic hash function.
 Note that f can be greater than r but not longer (measuring bits).
2. Select a random integer u in the interval [1, r - 1].
3. Compute V = uG = (xV, yV) and c ≡ xV mod r  (goto (2) if c = 0).
4. Compute d ≡ u^-1·(f + s·c) mod r  (goto (2) if d = 0).
 The signature for the message m is the pair of integers (c, d).

**ECDSA signature verification.** To verify A's signature, B should do the following:
1. Obtain an authentic copy of A's public key (E, G, r, W).
 Verify that c and d are integers in the interval [1, r - 1].
2. Compute f = H(m) and h ≡ d^-1 mod r.
3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r.
4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r.
 Accept the signature if and only if c1 = c.

To be cryptographically useful, the parameter r should have at least 250 bits.
The basis for the security of elliptic curve cryptosystems
is the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size:
given two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G,
determine an integer k such that W = kG and 0 ≤ k < r.

Task.

The task is to write a **toy version** of the ECDSA, quasi the equal of a real-world
implementation, but utilizing parameters that fit into standard arithmetic types.
To keep things simple there's no need for key export or a hash function (just a sample
hash value and a way to tamper with it). The program should be lenient where possible
(for example: if it accepts a composite modulus N it will either function as expected,
or demonstrate the principle of elliptic curve factorization)
— but strict where required (a point G that is not on E will always cause failure).
Toy ECDSA is of course completely useless for its cryptographic purpose.
If this bothers you, please add a multiple-precision version.

Reference.

Elliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see:

7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.)

7.1 The EC setting
7.1.2 EC domain parameters
7.1.3 EC key pairs

7.2 Primitives
7.2.7 ECSP-DSA (p. 35)
7.2.8 ECVP-DSA (p. 36)

Annex A. Number-theoretic background
A.9 Elliptic curves: overview (p. 115)
A.10 Elliptic curves: algorithms (p. 121)

[Assistant]
(formerly Perl 6)

```
module EC {
  use FiniteField;

  our class Point {
    has ($.x, $.y);
    submethod TWEAK { fail unless $!y**2 == $!x**3 + $*a*$!x + $*b }
    multi method gist(::?CLASS:U:) { "Point at Horizon" }
    multi method new($x, $y) { samewith :$x, :$y }
  }
  multi infix:<==>(Point:D $A, Point:D $B) is export { $A.x == $B.x and $A.y == $B.y }

  multi prefix:<->(Point $P) returns Point is export { Point.new: $P.x, -$P.y }
  multi infix:<+>(Point $A, Point:U) is export { $A }
  multi infix:<+>(Point:U, Point $B) is export { $B }
  multi infix:<+>(Point:D $A, Point:D $B) returns Point is export {
    my $λ;
    if $A.x == $B.x and $A.y == -$B.y { return Point }
    elsif $A == $B {
      return Point if $A.y == 0;
      $λ = (3*$A.x² + $*a) / (2*$A.y);
    }
    else { $λ = ($A.y - $B.y) / ($A.x - $B.x); }

    given $λ**2 - $A.x - $B.x {
      return Point.new: $_, $λ*($A.x - $_) - $A.y;
    }
  }
  multi infix:<*>(0, Point     ) is export { Point }
  multi infix:<*>(1, Point   $p) is export { $p }
  multi infix:<*>(2, Point:D $p) is export { $p + $p }
  multi infix:<*>(Int $n, Point $p) is export { 2*(($n div 2)*$p) + ($n mod 2)*$p }
}

import EC;

module ECDSA {
  use Digest::SHA256::Native;
  our class Signature {
    has UInt ($.c, $.d);
    multi method new(Str $message, UInt :$private-key) {
      my $z = :16(sha256-hex $message) % $*n;
      loop (my $k = my $s = my $r = 0; $r == 0; ) {
        loop ( $r = $s = 0 ; $r == 0 ; ) {
          $r = (( $k = (1..^$*n).roll ) * $*G).x % $*n;
        }
        {
          use FiniteField; my $*modulus = $*n;
          $s = ($z + $r*$private-key) / $k;
        }
      }
      samewith c => $r, d => $s;
    }
    multi method verify(Str $message, EC::Point :$public-key) {
      my $z = :16(sha256-hex $message) % $*n;
      my ($u1, $u2);
      {
        use FiniteField;
        my $*modulus = $*n;
        my $w = 1/$!d;
        ($u1, $u2) = $z*$w, $!c*$w;
      }
      my $p = ($u1 * $*G) + ($u2 * $public-key);
      die unless ($p.x mod $*n) == ($!c mod $*n);
    }
  }
}

my ($*a, $*b) = 355, 671;
my $*modulus = my $*p = 1073741789;

my $*G = EC::Point.new: 13693, 10088;
my $*n = 1073807281;

die "G is not of order n" if $*n*$*G;

my $private-key = ^$*n .pick;
my $public-key = $private-key*$*G;

my $message = "Show me the monKey";
my $signature = ECDSA::Signature.new: $message, :$private-key;

printf "The curve E is        : 𝑦² = 𝑥³ + %s 𝑥 + %s (mod %s)\n", $*a, $*b, $*p;
printf "with generator G at   : (%s, %s)\n", $*G.x, $*G.y;
printf "G's order is          : %d\n", $*n;
printf "The private key is    : %d\n", $private-key;
printf "The public key is at  : (%s, %s)\n", $public-key.x, $public-key.y;
printf "The message is        : %s\n", $message;
printf "The signature is      : (%s, %s)\n", $signature.c, $signature.d;

{
  use Test;

  lives-ok {
    $signature.verify: $message, :$public-key;
  }, "good signature for <$message>";

  my $altered = $message.subst(/monKey/, "money");
  dies-ok {
    $signature.verify: $altered, :$public-key
  }, "wrong signature for <$altered>";
}

```

Output:

```
The curve E is        : 𝑦² = 𝑥³ + 355 𝑥 + 671 (mod 1073741789)
with generator G at   : (13693, 10088)
G's order is          : 1073807281
The private key is    : 405586338
The public key is at  : (457744420, 236326628)
The message is        : Show me the monKey
The signature is      : (839907635, 23728690)
ok 1 - good signature for <Show me the monKey>
ok 2 - wrong signature for <Show me the money>
```


[User]
An   *emirp*   (**prime** spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime.

(This rules out palindromic primes.)

Task
:   :   * show the first   twenty   emirps
        * show all emirps between   7,700   and   8,000
        * show the   10,000th   emirp

In each list, the numbers should be in order.

Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.

The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.

See also

* Wikipedia, Emirp.
* The Prime Pages, emirp.
* Wolfram MathWorld™, Emirp.
* The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.10

For better performance, build the lazy list using module `Math::Primesieve`, not the built-in, then display results based on parameters passed in. The default is to display an array slice starting and stopping at the given indices. Alternately, ask for all values between two endpoints.

```
use Math::Primesieve;

sub prime-hash (Int $max) {
    my $sieve = Math::Primesieve.new;
    my @primes = $sieve.primes($max);
    @primes.Set;
}

sub MAIN ($start, $stop = Nil, $display = <slice>) {
    my $end = $stop // $start;
    my %primes = prime-hash(100*$end);
    my @emirps = lazy gather for 1 .. * -> $n {
        take $n if %primes{$n} and %primes{$n.flip} and $n != $n.flip
    }

    given $display {
        when 'slice'  { return @emirps[$start-1 .. $end-1] };
        when 'values' {
            my @values = gather for @emirps {
                .take if $start < $_ < $end;
                last if $_> $end
            }
            return @values
        }
    }
}

```

Output:

Run with passed parameters: 1 20

('slice' is the default. you *could* pass it in, but it isn't necessary.)

```
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
```

Run with passed parameters: 7700 8000 values

```
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
```

Run with passed parameter: 10000

```
948349
```


[User]
Starting with a path to some directory, determine whether the directory is empty.

An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “`.`” and almost every directory contains “`..`” (except for a root directory); an empty directory contains no other entries.

[Assistant]
(formerly Perl 6)

```
sub dir-is-empty ($d) { not dir $d }

```

The dir function returns a lazy list of filenames, excluding "." and ".." automatically. Any boolean context (in this case the not function) will do just enough work on the lazy list to determine whether there are any elements, so we don't have to count the directory entries, or even read them all into memory, if there are more than one buffer's worth.


[User]
Task

Create the simplest possible program that is still considered "correct."

[Assistant]
(formerly Perl 6)

The empty program is valid and does nothing but return a successful exit code:

It is also possible to just specify that the program is written in Raku:

```
use v6;
```

or even:

```
v6;
```


[User]
Languages may have features for dealing specifically with empty strings
(those containing no characters).

Task
:   :   * Demonstrate how to assign an empty string to a variable.
        * Demonstrate how to check that a string is empty.
        * Demonstrate how to check that a string is not empty.

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)

```
my $s = '';
say 'String is empty' unless $s;
say 'String is not empty' if $s;
```

Unlike in Perl 5, only empty strings test as false - the string "0" tests as true now.


[User]
Task

Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.

[Assistant]
(formerly Perl 6)
You can create constants in Raku with `constant`:

```
constant $pi = 3.14159;
constant $msg = "Hello World";

constant @arr = (1, 2, 3, 4, 5);

```

Immutability is abstract enough that you can define an infinite constant lazily:

```
constant fibonacci = 0, 1, *+* ... *;

```

Variables are considered mutable by default, but may be marked as readonly after initialization:

```
my $pi := 3 + rand;

```

Unlike variables, formal parameters are considered readonly by default even if bound to a mutable container.

```
sub sum (Num $x, Num $y) {
	$x += $y;  # ERROR
}

# Explicitly ask for pass-by-reference semantics
sub addto (Num $x is rw, Num $y) {
    $x += $y;  # ok, propagated back to caller
}

# Explicitly ask for pass-by-value semantics
sub sum (Num $x is copy, Num $y) {
    $x += $y;  # ok, but NOT propagated back to caller
    $x;
}

```

A number of built-in types are considered immutable value types, including:

```
Str         String (finite sequence of Unicode characters)
Int         Integer (allows Inf/NaN, arbitrary precision, etc.)
Num         Number (approximate Real, generally via floating point)
Rat         Rational (exact Real, limited denominator)
FatRat      Rational (unlimited precision in both parts)
Complex     Complex number
Bool        Boolean
Exception   Exception
Block       Executable objects that have lexical scopes
Seq         A list of values (can be generated lazily)
Range       A pair of Ordered endpoints
Set         Unordered collection of values that allows no duplicates
Bag         Unordered collection of values that allows duplicates
Enum        An immutable Pair
Map         A mapping of Enums with no duplicate keys
Signature   Function parameters (left-hand side of a binding)
Capture     Function call arguments (right-hand side of a binding)
Blob        An undifferentiated mass of ints, an immutable Buf
Instant     A point on the continuous atomic timeline
Duration    The difference between two Instants
```

These values, though objects, can't mutate; they may only be "changed" by modifying a mutable container holding one of them to hold a different value instead. (In the abstract, that is. In the interests of efficiency, a string or list implementation would be allowed to cheat as long as it doesn't get caught cheating.) Some of these types have corresponding "unboxed" native representations, where the container itself must carry the type information since the value can't. In this case, it's still the container that might be
considered mutable as an lvalue location, not the value stored in that location.

By default, object attributes are not modifiable from outside a class, though this is usually viewed more as encapsulation than as mutability control.


[User]
The Engel expansion of a positive real number x is the unique non-decreasing sequence of positive integers ***{ a1, a2, a3 ... }*** such that

```
    x = 1 / a1 + 1 / a1a2  + 1 / a1a2a3 ...

```

In other words, each term is the reciprocal of the cumulative product of the expansion and *x* is the sum of those terms.

Rational numbers have a finite Engel expansion, while irrational numbers have an infinite Engel expansion.

Tiny amounts of imprecision can cause wild variation from actual values as the (reciprocal) terms grow smaller. It can be quite challenging to maintain precision in later terms.

Task

* Write routines (functions, procedures, whatever it may be called in your language) to convert a rational number to an Engel expansion representation and from an Engle expansion to a rational number.
* Demonstrate converting some rational numbers to an Engel expansion and back.

Test it with at least the following rational approximations of:

* 𝜋 - 3.14159265358979
* 𝑒 - 2.71828182845904
* √2 - 1.414213562373095

Stretch

* If your language supports high precision rational numbers, do the same with at least:

* 𝜋 - 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211
* 𝑒 - 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642743
* √2 - 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927558

There almost definitely *will* be some imprecision in the later terms. Feel free to limit the display of the expansion to the first 30 terms.

See also

* Wikipedia: Engel expansion * OEIS:A006784 - Engel expansion of Pi * OEIS:A028310 - Engel expansion of 𝑒 * OEIS:A028254 - Engel expansion of sqrt(2)

[Assistant]
```
sub to-engel ($rat is copy) { do while $rat { my $a = ceiling 1 / $rat; $rat = $rat × $a - 1; $a } }

sub from-engel (@expanded) { sum [\×] @expanded.map: { FatRat.new: 1, $_ } }

for #  low precision 𝜋, 𝑒, √2 and 1.5 to a power
    3.14159265358979, 2.71828182845904, 1.414213562373095, 1.5 ** 5,

    # high precision 𝜋, 𝑒, and √2 and 1.5 to a power
    3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211.FatRat,

    2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642743.FatRat,

    1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927558.FatRat,

    1.5 ** 8
  -> $rat {
    say "Rational number: $rat";
    my @expanded = $rat.&to-engel;
    put "Engel expansion: " ~ @expanded.head(30);
    say " Converted back: " ~ @expanded.&from-engel;
    put '';
}

```

Output:

```
Rational number: 3.14159265358979
Engel expansion: 1 1 1 8 8 17 19 300 1991 2768 4442 4830 10560 37132 107315 244141 651042 1953125
 Converted back: 3.14159265358979

Rational number: 2.71828182845904
Engel expansion: 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 82 144 321 2289 9041 21083 474060 887785 976563 1953125
 Converted back: 2.71828182845904

Rational number: 1.414213562373095
Engel expansion: 1 3 5 5 16 18 78 102 120 144 260 968 18531 46065 63005 65105 78125
 Converted back: 1.414213562373095

Rational number: 7.59375
Engel expansion: 1 1 1 1 1 1 1 2 6 8
 Converted back: 7.59375

Rational number: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211
Engel expansion: 1 1 1 8 8 17 19 300 1991 2492 7236 10586 34588 63403 70637 1236467 5417668 5515697 5633167 7458122 9637848 9805775 41840855 58408380 213130873 424342175 2366457522 4109464489 21846713216 27803071890
 Converted back: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211

Rational number: 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642743
Engel expansion: 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 Converted back: 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642743

Rational number: 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927558
Engel expansion: 1 3 5 5 16 18 78 102 120 144 251 363 1402 31169 88630 184655 259252 298770 4196070 38538874 616984563 1975413035 5345718057 27843871197 54516286513 334398528974 445879679626 495957494386 2450869042061 2629541150527
 Converted back: 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927558

Rational number: 25.628906
Engel expansion: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 4 32
 Converted back: 25.628906
```


[User]
Certain numbers, when spelled out in their English cardinal representation, are anagrams of other numbers.

Some are very obvious: **sixty-seven <=> seventy-six**

Others are a little more subtle: **one hundred twelve <=> two hundred eleven**

Task

* Find and display the first thirty numbers that are a member of English cardinal anagrams, starting from **zero**.
* Find and display the **count** of English cardinal anagrams from **zero** to **one thousand**.
* Find and display the **largest group(s)** of English cardinal anagrams from **zero** to **one thousand**.

Stretch

* Find and display the **count** of English cardinal anagrams from **zero** to **ten thousand**, restricted to numbers within those bounds. *(Ignore anagrams of numbers outside those bounds. **E.G. 1010 <=> 10001**)*
* Find and display the **largest group(s)** of English cardinal anagrams from **zero** to **ten thousand**.

See also

* OEIS::A169936 - Numbers whose name in English is an anagram of the name of another number * Related task: Number names

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

for 1_000, 10_000 {
    my %eca; # English cardinal anagrams
    (^$_).map: { %eca{.&cardinal.comb.sort.join}.push: $_ }

    once say "\nFirst 30 English cardinal anagrams:\n " ~
    (sort flat %eca.grep(+*.value > 1)».value.map: *.flat)[^30]\
    .batch(10)».fmt("%3d").join: "\n ";

    say "\nCount of English cardinal anagrams up to {.&comma}: " ~
        +%eca.grep(+*.value > 1)».value.map: *.flat;

    say "\nLargest group(s) of English cardinal anagrams up to {.&comma}:\n [" ~
        %eca.&all-max( :by(+*.value) )».value.sort.join("]\n [") ~ ']'
}

```

Output:

```
First 30 English cardinal anagrams:
  67  69  76  79  96  97 102 103 104 105
 106 107 108 109 112 122 123 124 125 126
 127 128 129 132 133 134 135 136 137 138

Count of English cardinal anagrams up to 1,000: 317

Largest group(s) of English cardinal anagrams up to 1,000:
 [679 697 769 796 967 976]

Count of English cardinal anagrams up to 10,000: 2534

Largest group(s) of English cardinal anagrams up to 10,000:
 [1679 1697 1769 1796 1967 1976 6179 6197 6791 6971 7169 7196 7691 7961 9167 9176 9671 9761]
 [2679 2697 2769 2796 2967 2976 6279 6297 6792 6972 7269 7296 7692 7962 9267 9276 9672 9762]
 [3679 3697 3769 3796 3967 3976 6379 6397 6793 6973 7369 7396 7693 7963 9367 9376 9673 9763]
 [4679 4697 4769 4796 4967 4976 6479 6497 6794 6974 7469 7496 7694 7964 9467 9476 9674 9764]
 [5679 5697 5769 5796 5967 5976 6579 6597 6795 6975 7569 7596 7695 7965 9567 9576 9675 9765]
 [6798 6879 6897 6978 7698 7869 7896 7968 8679 8697 8769 8796 8967 8976 9678 9768 9867 9876]
```


[User]
Task

Calculate the Shannon entropy   H   of a given input string.

Given the discrete random variable

X
{\displaystyle {\displaystyle X}}
 that is a string of

N
{\displaystyle {\displaystyle N}}
 "symbols" (total characters) consisting of

n
{\displaystyle {\displaystyle n}}
 different characters (n=2 for binary), the Shannon entropy of X in **bits/symbol** is :

:   H

    2
    (
    X
    )
    =
    −

    ∑

    i
    =
    1

    n

    c
    o
    u
    n

    t

    i
    N

    log

    2

    (

    c
    o
    u
    n

    t

    i
    N
    )
    {\displaystyle {\displaystyle H\_{2}(X)=-\sum \_{i=1}^{n}{\frac {count\_{i}}{N}}\log \_{2}\left({\frac {count\_{i}}{N}}\right)}}

where

c
o
u
n

t

i
{\displaystyle {\displaystyle count\_{i}}}
 is the count of character

n

i
{\displaystyle {\displaystyle n\_{i}}}
.

For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.

This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where

S
=

k

B
N
H
{\displaystyle {\displaystyle S=k\_{B}NH}}
 where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.

The "total", "absolute", or "extensive" information entropy is

:   S
    =

    H

    2
    N
    {\displaystyle {\displaystyle S=H\_{2}N}}
     bits

This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have

S
=
N

log

2

(
16
)
{\displaystyle {\displaystyle S=N\log \_{2}(16)}}
 bits of entropy. The total entropy in bits of the example above is S= 10\*18.4644 = 18.4644 bits.

The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.

Two other "entropies" are useful:

Normalized specific entropy:

:   H

    n
    =

    H

    2
    ∗
    log

    (
    2
    )

    log

    (
    n
    )
    {\displaystyle {\displaystyle H\_{n}={\frac {H\_{2}\*\log(2)}{\log(n)}}}}

which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.

Normalized total (extensive) entropy:

:   S

    n
    =

    H

    2
    N
    ∗
    log

    (
    2
    )

    log

    (
    n
    )
    {\displaystyle {\displaystyle S\_{n}={\frac {H\_{2}N\*\log(2)}{\log(n)}}}}

which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.

Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".

In keeping with Landauer's limit, the physics entropy generated from erasing N bits is

S
=

H

2
N

k

B
ln

(
2
)
{\displaystyle {\displaystyle S=H\_{2}Nk\_{B}\ln(2)}}
 if the bit storage device is perfectly efficient. This can be solved for H2\*N to (arguably) get the number of bits of information that a physical entropy represents.

Related tasks
:   * Fibonacci\_word
    * Entropy/Narcissist

[Assistant]
(formerly Perl 6)

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

```
sub entropy(@a) {
    [+] map -> \p { p * -log p }, bag(@a).values »/» +@a;
}

say log(2) R/ entropy '1223334444'.comb;

```

Output:

```
1.84643934467102
```

In case we would like to add this function to Raku's core, here is one way it could be done:

```
use MONKEY-TYPING;
augment class Bag {
    method entropy {
	[+] map -> \p { - p * log p },
	self.values »/» +self;
    }
}

say '1223334444'.comb.Bag.entropy / log 2;

```


[User]
Task

Write a computer program that computes and shows its own   entropy.

Related Tasks
:   * Fibonacci\_word
    * Entropy

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.05

```
say log(2) R/ [+] map -> \p { p * -log p }, $_.comb.Bag.values >>/>> +$_
    given slurp($*PROGRAM-NAME).comb

```

Result should be in the neighborhood of 4.9

Output:

```
4.89351613053006
```


[User]
Task

Create an enumeration of constants with and without explicit values.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.01

```
enum Fruit <Apple Banana Cherry>; # Numbered 0 through 2.

enum ClassicalElement (
    Earth => 5,
    'Air',  # gets the value 6
    'Fire', # gets the value 7
    Water => 10,
);
```


[User]
Task

Show how to get one of your process's environment variables.

The available variables vary by system;   some of the common ones available on Unix include:

:   :   :   * PATH
            * HOME
            * USER

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version #24 "Seoul"

The `%*ENV` hash maps environment variables to their values:

```
say %*ENV<HOME>;

```


[User]
Suppose we have a sequence of prime sums, where each term **Pn** is the sum of the first **n** primes.

```
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...

```

```
P = 2, 5, 10, 17, 28, etc.

```

Further; suppose we have a sequence of composite sums, where each term **Cm** is the sum of the first **m** composites.

```
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...

```

```
C = 4, 10, 18, 27, 37, etc.

```

Notice that the third term of **P**; **P3** (**10**) is equal to the second term of **C**; **C2** (**10**);

Task

* Find and display the indices (**n**, **m**) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first **n** primes and the first **m** composites.

See also

* OEIS:A007504 - Sum of the first n primes * OEIS:A053767 - Sum of first n composite numbers * OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites

[Assistant]
Let it run until I got bored and killed it. Time is total accumulated seconds since program start.

```
use Lingua::EN::Numbers:ver<2.8.2+>;

my $prime-sum =     [\+] (2..*).grep:  *.is-prime;
my $composite-sum = [\+] (2..*).grep: !*.is-prime;

my $c-index = 0;

for ^∞ -> $p-index {
    next if $prime-sum[$p-index] < $composite-sum[$c-index];
    printf( "%20s - %11s prime sum, %12s composite sum   %5.2f seconds\n",
      $prime-sum[$p-index].&comma, ordinal-digit($p-index + 1, :u, :c),
      ordinal-digit($c-index + 1, :u, :c), now - INIT now )
      and next if $prime-sum[$p-index] == $composite-sum[$c-index];
    ++$c-index;
    redo;
};

```

Output:

```
                  10 -         3ʳᵈ prime sum,          2ⁿᵈ composite sum    0.01 seconds
               1,988 -        33ʳᵈ prime sum,         51ˢᵗ composite sum    0.01 seconds
              14,697 -        80ᵗʰ prime sum,        147ᵗʰ composite sum    0.02 seconds
              83,292 -       175ᵗʰ prime sum,        361ˢᵗ composite sum    0.03 seconds
           1,503,397 -       660ᵗʰ prime sum,      1,582ⁿᵈ composite sum    0.04 seconds
          18,859,052 -     2,143ʳᵈ prime sum,      5,699ᵗʰ composite sum    0.08 seconds
          93,952,013 -     4,556ᵗʰ prime sum,     12,821ˢᵗ composite sum    0.14 seconds
      89,171,409,882 -   118,785ᵗʰ prime sum,    403,341ˢᵗ composite sum    4.23 seconds
   9,646,383,703,961 - 1,131,142ⁿᵈ prime sum,  4,229,425ᵗʰ composite sum   76.23 seconds
 209,456,854,921,713 - 5,012,372ⁿᵈ prime sum, 19,786,181ˢᵗ composite sum  968.26 seconds
^C
```


[User]
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.

For example, in a sequence

A
{\displaystyle {\displaystyle A}}
:

:   :   :   :   :   A

                    0
                    =
                    −
                    7
                    {\displaystyle {\displaystyle A\_{0}=-7}}
                :   A

                    1
                    =
                    1
                    {\displaystyle {\displaystyle A\_{1}=1}}
                :   A

                    2
                    =
                    5
                    {\displaystyle {\displaystyle A\_{2}=5}}
                :   A

                    3
                    =
                    2
                    {\displaystyle {\displaystyle A\_{3}=2}}
                :   A

                    4
                    =
                    −
                    4
                    {\displaystyle {\displaystyle A\_{4}=-4}}
                :   A

                    5
                    =
                    3
                    {\displaystyle {\displaystyle A\_{5}=3}}
                :   A

                    6
                    =
                    0
                    {\displaystyle {\displaystyle A\_{6}=0}}

3   is an equilibrium index, because:

:   :   :   :   :   A

                    0
                    +

                    A

                    1
                    +

                    A

                    2
                    =

                    A

                    4
                    +

                    A

                    5
                    +

                    A

                    6
                    {\displaystyle {\displaystyle A\_{0}+A\_{1}+A\_{2}=A\_{4}+A\_{5}+A\_{6}}}

6   is also an equilibrium index, because:

:   :   :   :   :   A

                    0
                    +

                    A

                    1
                    +

                    A

                    2
                    +

                    A

                    3
                    +

                    A

                    4
                    +

                    A

                    5
                    =
                    0
                    {\displaystyle {\displaystyle A\_{0}+A\_{1}+A\_{2}+A\_{3}+A\_{4}+A\_{5}=0}}

(sum of zero elements is zero)

7   is not an equilibrium index, because it is not a valid index of sequence

A
{\displaystyle {\displaystyle A}}
.

Task;

Write a function that, given a sequence, returns its equilibrium indices (if any).

Assume that the sequence may be very long.

[Assistant]
(formerly Perl 6)

```
sub equilibrium_index(@list) {
    my ($left,$right) = 0, [+] @list;

    gather for @list.kv -> $i, $x {
        $right -= $x;
        take $i if $left == $right;
        $left += $x;
    }
}

my @list = -7, 1, 5, 2, -4, 3, 0;
.say for equilibrium_index(@list).grep(/\d/);

```

And here's an FP solution that manages to remain O(n):

```
sub equilibrium_index(@list) {
    my @a = [\+] @list;
    my @b = reverse [\+] reverse @list;
    ^@list Zxx (@a »==« @b);
}

```

The [\+] is a reduction that returns a list of partial results. The »==« is a vectorized equality comparison; it returns a vector of true and false. The Zxx is a zip with the list replication operator, so we return only the elements of the left list where the right list is true (which is taken to mean 1 here). And the ^@list is just shorthand for 0 ..^ @list. We could just as easily have used @list.keys there.

### Single-pass solution

The task can be restated in a way that removes the "right side" from the calculation.

C is the current element,
L is the sum of elements left of C,
R is the sum of elements right of C,
S is the sum of the entire list.

By definition, L + C + R == S for any choice of C, and L == R for any C that is an equilibrium point.
Therefore (by substituting L for R), L + C + L == S at all equilibrium points.
Restated, 2L + C == S.

```
# Original example, with expanded calculations:
    0    1    2    3    4    5    6   # Index
   -7    1    5    2   -4    3    0   # C (Value at index)
    0   -7   -6   -1    1   -3    0   # L (Sum of left)
   -7  -13   -7    0   -2   -3    0   # 2L+C

```

If we build a hash as we walk the list, with 2L+C as hash keys, and arrays of C-indexes as hash values, we get:

```
{
     -7 => [ 0, 2 ],
    -13 => [ 1    ],
      0 => [ 3, 6 ],
     -2 => [ 4    ],
     -3 => [ 5    ],
}

```

After we have finished walking the list, we will have the sum (S), which we look up in the hash. Here S=0, so the equilibrium points are 3 and 6.

Note: In the code below, it is more convenient to calculate 2L+C \*after\* L has already been incremented by C; the calculation is simply 2L-C, because each L has an extra C in it. 2(L-C)+C == 2L-C.

```
sub eq_index ( *@list ) {
    my $sum = 0;

    my %h = @list.keys.classify: {
        $sum += @list[$_];
        $sum * 2 - @list[$_];
    };

    return %h{$sum} // [];
}

say eq_index < -7  1  5  2 -4  3  0 >; # 3 6
say eq_index <  2  4  6             >; # (no eq point)
say eq_index <  2  9  2             >; # 1
say eq_index <  1 -1  1 -1  1 -1  1 >; # 0 1 2 3 4 5 6

```

The .classify method creates a hash, with its code block's return value as key. Each hash value is an Array of all the inputs that returned that key.

We could have used .pairs instead of .keys to save the cost of @list lookups, but that would change each %h value to an Array of Pairs, which would complicate the return line.


[User]
A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1.

The task is first to display the first 200 primes allocated to their category, then assign the first million primes to their category, displaying the smallest prime, the largest prime, and the count of primes allocated to each category.

[Assistant]
```
use Prime::Factor;
use Lingua::EN::Numbers;
use Math::Primesieve;
my $sieve = Math::Primesieve.new;

my %cat = 2 => 1, 3 => 1;

sub Erdös-Selfridge ($n) {
    my @factors = prime-factors $n + 1;
    my $category = max %cat{ @factors };
    unless %cat{ @factors[*-1] } {
        $category max= ( 1 + max %cat{ prime-factors 1 + @factors[*-1] } );
        %cat{ @factors[*-1] } = $category;
    }
    $category
}

my $upto = 200;

say "First { cardinal $upto } primes; Erdös-Selfridge categorized:";
.say for sort $sieve.n-primes($upto).categorize: &Erdös-Selfridge;

$upto = 1_000_000;

say "\nSummary of first { cardinal $upto } primes; Erdös-Selfridge categorized:";
printf "Category %2d: first: %9s  last: %10s  count: %s\n", ++$, |(.[0], .[*-1], .elems).map: &comma
for $sieve.n-primes($upto).categorize( &Erdös-Selfridge ).sort(+*.key)».value;

```

Output:

```
First two hundred primes; Erdös-Selfridge categorized:
1 => [2 3 5 7 11 17 23 31 47 53 71 107 127 191 383 431 647 863 971 1151]
2 => [13 19 29 41 43 59 61 67 79 83 89 97 101 109 131 137 139 149 167 179 197 199 211 223 229 239 241 251 263 269 271 281 283 293 307 317 349 359 367 373 419 433 439 449 461 479 499 503 509 557 563 577 587 593 599 619 641 643 659 709 719 743 751 761 769 809 827 839 881 919 929 953 967 991 1019 1033 1049 1069 1087 1103 1187 1223]
3 => [37 103 113 151 157 163 173 181 193 227 233 257 277 311 331 337 347 353 379 389 397 401 409 421 457 463 467 487 491 521 523 541 547 569 571 601 607 613 631 653 683 701 727 733 773 787 797 811 821 829 853 857 859 877 883 911 937 947 983 997 1009 1013 1031 1039 1051 1061 1063 1091 1097 1117 1123 1153 1163 1171 1181 1193 1217]
4 => [73 313 443 617 661 673 677 691 739 757 823 887 907 941 977 1093 1109 1129 1201 1213]
5 => [1021]

Summary of first one million primes; Erdös-Selfridge categorized:
Category  1: first:         2  last: 10,616,831  count: 46
Category  2: first:        13  last: 15,482,669  count: 10,497
Category  3: first:        37  last: 15,485,863  count: 201,987
Category  4: first:        73  last: 15,485,849  count: 413,891
Category  5: first:     1,021  last: 15,485,837  count: 263,109
Category  6: first:     2,917  last: 15,485,857  count: 87,560
Category  7: first:    15,013  last: 15,484,631  count: 19,389
Category  8: first:    49,681  last: 15,485,621  count: 3,129
Category  9: first:   532,801  last: 15,472,811  count: 363
Category 10: first: 1,065,601  last: 15,472,321  count: 28
Category 11: first: 8,524,807  last:  8,524,807  count: 1
```


[User]
Definition

An Erdős–Nicolas number is a positive integer which is not perfect but is equal to the sum of its first **k** divisors (arranged in ascending order and including one) for some value of **k** greater than one.

Examples

24 is an Erdős–Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor.

6 is not an Erdős–Nicolas number because it is perfect (1 + 2 + 3 = 6).

48 is not an Erdős–Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48.

Task

Find and show here the first 8 Erdős–Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition.

Stretch

Do the same for any further Erdős–Nicolas numbers which you have the patience for.

Note

As all known Erdős–Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case.

Reference

* OEIS:A194472 - Erdős–Nicolas numbers

[Assistant]
```
use Prime::Factor;

sub is-Erdős-Nicolas ($n) {
    my @divisors = $n.&proper-divisors: :s;
    ((@divisors.sum > $n) && (my $key = ([\+] @divisors).first: $n, :k)) ?? 1 + $key !! False
}

my $count;

(1..*).hyper(:2000batch).map( * × 2 ).map: {
    if my $key = .&is-Erdős-Nicolas {
        printf "%8d == sum of its first %3d divisors\n", $_, $key;
        exit if ++$count >= 8;
    }
}

```

Output:

```
      24 == sum of its first   6 divisors
    2016 == sum of its first  31 divisors
    8190 == sum of its first  43 divisors
   42336 == sum of its first  66 divisors
   45864 == sum of its first  66 divisors
  392448 == sum of its first  68 divisors
  714240 == sum of its first 113 divisors
 1571328 == sum of its first 115 divisors
```


[User]
Definitions

In mathematics, **Erdős primes** are prime numbers such that all p-k! for 1<=k!<p are composite.

Task

Write a program to determine (and show here) all **Erdős primes** less than **2500**.

Optionally, show the **number** of Erdős primes.

Stretch goal

Show that the 7,875th Erdős prime is 999,721 (the highest below 1,000,000)

Also see
:   * the OEIS entry:   A064152 Erdos primes.

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

my @factorial = 1, |[\*] 1..*;
my @Erdős = ^Inf .grep: { .is-prime and none($_ «-« @factorial[^(@factorial.first: * > $_, :k)]).is-prime }

put 'Erdős primes < 2500:';
put @Erdős[^(@Erdős.first: * > 2500, :k)]».,
put "\nThe 7,875th Erdős prime is: " ~ @Erdős[7874].,

```

Output:

```
Erdős primes < 2500:
2 101 211 367 409 419 461 557 673 709 769 937 967 1,009 1,201 1,259 1,709 1,831 1,889 2,141 2,221 2,309 2,351 2,411 2,437

The 7,875th Erdős prime is: 999,721
```

Alternately, using fewer hard coded values:

```
use Lingua::EN::Numbers;
use List::Divvy;

my @factorial = 1, |[\*] 1..*;
my @Erdős = ^∞ .grep: { .is-prime and none($_ «-« @factorial.&upto: $_).is-prime }

put "Erdős primes < 2500:\n" ~ @Erdős.&before(2500)».&comma.batch(8)».fmt("%5s").join: "\n";
put "\nThe largest Erdős prime less than {comma 1e6.Int} is {comma .[*-1]} in {.&ordinal-digit} position."
  given @Erdős.&before(1e6);

```

Output:

```
Erdős primes < 2500:
    2   101   211   367   409   419   461   557
  673   709   769   937   967 1,009 1,201 1,259
1,709 1,831 1,889 2,141 2,221 2,309 2,351 2,411
2,437

The largest Erdős prime less than 1,000,000 is 999,721 in 7875th position.
```


[User]
Description

A positive integer **k** is said to be an Erdős–Woods number if it has the following property: there exists a positive integer **a** such that in the sequence (a, a + 1, …, a + k) of consecutive integers, each of the elements has a non-trivial common factor with one of the endpoints. In other words, **k** is an Erdős–Woods number if there exists a positive integer **a** such that for each integer **i** between 0 and k, at least one of the greatest common divisors gcd(a, a + i) or gcd(a + i, a + k) is greater than 1.

It can be shown that there are infinitely many such numbers. Moreover, if **k** is an E-W number for some integer **a**, then one can find an infinite number of other **a'**s using the formula **a(jq + 1)** where:

* **q** is the product of all odd prime factors of **a + k**; and
* **j** is any positive integer.

Example

16 is an E-W number (and also the first) for which the smallest value of **a** is 2184. This is because in the sequence 2184 to 2200 inclusive, the prime factors of the endpoints are:

* 2³ x 3 x 7 x 13 = 2184
* 2³ x 5² x 11 = 2200

and, if you check all the numbers between them, you will find that they all have a prime factor in common with at least one of the endpoints (2189 is divisible by 11, 2191 by 7, 2197 by 13 and the rest by either 2, 3, or 5).

Task

Compute and show here the first **20** E-W numbers together with their corresponding smallest value of **a**. If your language doesn't support arbitrary precision arithmetic, just compute and show as many as you can.

Extra credit

Do the same for the **next 20** E-W numbers.

Note

Although all the E-W numbers relevant to this task are even, odd examples do exist the first one being **k** = 903.

References

* OEIS sequence A059756: Erdős–Woods numbers.
* OEIS sequence A059757: Smallest values of a for a given E-W number k.
* Planet Math: Erdős–Woods numbers.

[Assistant]
**Translation of**: Wren

**Translation of**: Julia

```
# 20220308 Raku programming solution

sub ew (\n) {

   my @primes = (^n).grep: *.is-prime;

   # rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation#Raku
   my @divs = (^n).map: -> \p { ([o] map { p%%$_.Int + 2 * * }, @primes)(0) }

   my @partitions = [ 0, 0, 2**@primes.elems - 1 ] , ;

   sub ort(\x) { (@divs[x] +| @divs[n -x]).base(2).flip.index(1) }

   for ((n^...1).sort: *.&ort).reverse {
      my \newPartitions = @ = ();
      my (\factors,\otherFactors) = @divs[$_, n-$_];

      for @partitions -> \p {
         my (\setA, \setB, \rPrimes) = p[0..2];

         if (factors +& setA) or (otherFactors +& setB) {
            newPartitions.push: p and next
         }
         for (factors +& rPrimes).base(2).flip.comb.kv -> \k,\v {
            if (v == 1) {
               my \w = 1 +< k;
               newPartitions.push: [ setA +^ w, setB, rPrimes +^ w ]
            }
         }
         for (otherFactors +& rPrimes).base(2).flip.comb.kv -> \k,\v {
            if (v == 1) {
               my \w = 1 +< k;
               newPartitions.push: [ setA, setB +^ w, rPrimes +^ w ]
            }
         }
      }
      @partitions = newPartitions
   }

   my \result = $ = -1;
   for @partitions -> \p {
      my ($px,$py,$x,$y) = p[0],p[1],1,1;
      for @primes -> $p {
         $px % 2 and $x *= $p;
         $py % 2 and $y *= $p;
         ($px,$py) >>div=>> 2
      }
      my \newresult = ((n * expmod($x, -1, $y)) % $y) * $x - n;
      result = result == -1 ?? newresult !! min(result, newresult)
   }
   return result
}

say "The first 20 Erdős–Woods numbers and their minimum interval start values are:";
for (16..116) { if (my $ew = ew $_) > 0 { printf "%3d -> %d\n",$_,$ew } } ;

```

Output:

Same as Wren example.


[User]
An **esthetic number** is a positive integer where every adjacent digit differs from its neighbour by 1.

E.G.

:   * **12** is an esthetic number. One and two differ by 1.

:   * **5654** is an esthetic number. Each digit is exactly 1 away from its neighbour.

:   * **890** is **not** an esthetic number. Nine and zero differ by 9.

These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers *are* included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.

Esthetic numbers are also sometimes referred to as stepping numbers.

Task

:   * Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.

:   * Use that routine to find esthetic numbers in bases **2** through **16** and display, here on this page, the esthectic numbers from index **(base × 4)** through index **(base × 6)**, inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)

:   * Find and display, here on this page, the **base 10** esthetic numbers with a magnitude between **1000** and **9999**.

:   * Stretch: Find and display, here on this page, the **base 10** esthetic numbers with a magnitude between **1.0e8** and **1.3e8**.

Related task

* numbers with equal rises and falls

See also
:   * OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 * Numbers Aplenty - Esthetic numbers * Geeks for Geeks - Stepping numbers

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

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

sub esthetic($base = 10) {
    my @s = ^$base .map: -> \s {
        ((s - 1).base($base) if s > 0), ((s + 1).base($base) if s < $base - 1)
    }

    flat [ (1 .. $base - 1)».base($base) ],
    { [ flat .map: { $_ xx * Z~ flat @s[.comb.tail.parse-base($base)] } ] } … *
}

for 2 .. 16 -> $b {
    put "\n{(4 × $b).&ordinal-digit} through {(6 × $b).&ordinal-digit} esthetic numbers in base $b";
    put esthetic($b)[(4 × $b - 1) .. (6 × $b - 1)]».fmt('%3s').batch(16).join: "\n"
}

my @e10 = esthetic;
put "\nBase 10 esthetic numbers between 1,000 and 9,999:";
put @e10.&between(1000, 9999).batch(20).join: "\n";

put "\nBase 10 esthetic numbers between {1e8.Int.&comma} and {1.3e8.Int.&comma}:";
put @e10.&between(1e8.Int, 1.3e8.Int).batch(9).join: "\n";

sub between (@array, Int $lo, Int $hi) {
    my $top = @array.first: * > $hi, :k;
    @array[^$top].grep: * > $lo
}

```

Output:

```
8th through 12th esthetic numbers in base 2
10101010 101010101 1010101010 10101010101 101010101010

12th through 18th esthetic numbers in base 3
1210 1212 2101 2121 10101 10121 12101

16th through 24th esthetic numbers in base 4
323 1010 1012 1210 1212 1232 2101 2121 2123

20th through 30th esthetic numbers in base 5
323 343 432 434 1010 1012 1210 1212 1232 1234 2101

24th through 36th esthetic numbers in base 6
343 345 432 434 454 543 545 1010 1012 1210 1212 1232 1234

28th through 42nd esthetic numbers in base 7
345 432 434 454 456 543 545 565 654 656 1010 1012 1210 1212 1232

32nd through 48th esthetic numbers in base 8
432 434 454 456 543 545 565 567 654 656 676 765 767 1010 1012 1210
1212

36th through 54th esthetic numbers in base 9
434 454 456 543 545 565 567 654 656 676 678 765 767 787 876 878
1010 1012 1210

40th through 60th esthetic numbers in base 10
454 456 543 545 565 567 654 656 676 678 765 767 787 789 876 878
898 987 989 1010 1012

44th through 66th esthetic numbers in base 11
456 543 545 565 567 654 656 676 678 765 767 787 789 876 878 898
89A 987 989 9A9 A98 A9A 1010

48th through 72nd esthetic numbers in base 12
543 545 565 567 654 656 676 678 765 767 787 789 876 878 898 89A
987 989 9A9 9AB A98 A9A ABA BA9 BAB

52nd through 78th esthetic numbers in base 13
545 565 567 654 656 676 678 765 767 787 789 876 878 898 89A 987
989 9A9 9AB A98 A9A ABA ABC BA9 BAB BCB CBA

56th through 84th esthetic numbers in base 14
565 567 654 656 676 678 765 767 787 789 876 878 898 89A 987 989
9A9 9AB A98 A9A ABA ABC BA9 BAB BCB BCD CBA CBC CDC

60th through 90th esthetic numbers in base 15
567 654 656 676 678 765 767 787 789 876 878 898 89A 987 989 9A9
9AB A98 A9A ABA ABC BA9 BAB BCB BCD CBA CBC CDC CDE DCB DCD

64th through 96th esthetic numbers in base 16
654 656 676 678 765 767 787 789 876 878 898 89A 987 989 9A9 9AB
A98 A9A ABA ABC BA9 BAB BCB BCD CBA CBC CDC CDE DCB DCD DED DEF
EDC

Base 10 esthetic numbers between 1,000 and 9,999:
1010 1012 1210 1212 1232 1234 2101 2121 2123 2321 2323 2343 2345 3210 3212 3232 3234 3432 3434 3454
3456 4321 4323 4343 4345 4543 4545 4565 4567 5432 5434 5454 5456 5654 5656 5676 5678 6543 6545 6565
6567 6765 6767 6787 6789 7654 7656 7676 7678 7876 7878 7898 8765 8767 8787 8789 8987 8989 9876 9878
9898

Base 10 esthetic numbers between 100,000,000 and 130,000,000:
101010101 101010121 101010123 101012101 101012121 101012123 101012321 101012323 101012343
101012345 101210101 101210121 101210123 101212101 101212121 101212123 101212321 101212323
101212343 101212345 101232101 101232121 101232123 101232321 101232323 101232343 101232345
101234321 101234323 101234343 101234345 101234543 101234545 101234565 101234567 121010101
121010121 121010123 121012101 121012121 121012123 121012321 121012323 121012343 121012345
121210101 121210121 121210123 121212101 121212121 121212123 121212321 121212323 121212343
121212345 121232101 121232121 121232123 121232321 121232323 121232343 121232345 121234321
121234323 121234343 121234345 121234543 121234545 121234565 121234567 123210101 123210121
123210123 123212101 123212121 123212123 123212321 123212323 123212343 123212345 123232101
123232121 123232123 123232321 123232323 123232343 123232345 123234321 123234323 123234343
123234345 123234543 123234545 123234565 123234567 123432101 123432121 123432123 123432321
123432323 123432343 123432345 123434321 123434323 123434343 123434345 123434543 123434545
123434565 123434567 123454321 123454323 123454343 123454345 123454543 123454545 123454565
123454567 123456543 123456545 123456565 123456567 123456765 123456767 123456787 123456789
```


[User]
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.

**Method:**

1. Take two numbers to be multiplied and write them down at the top of two columns.
2. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
3. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
4. Examine the table produced and discard any row where the value in the left column is even.
5. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together

**For example:**   17 × 34

```
       17    34

```

Halving the first column:

```
       17    34
        8
        4
        2
        1

```

Doubling the second column:

```
       17    34
        8    68
        4   136
        2   272
        1   544

```

Strike-out rows whose first cell is even:

```
       17    34
        8    68
        4   136
        2   272
        1   544

```

Sum the remaining numbers in the right-hand column:

```
       17    34
        8    --
        4   ---
        2   ---
        1   544
           ====
            578

```

So 17 multiplied by 34, by the Ethiopian method is 578.

Task

The task is to **define three named functions**/methods/procedures/subroutines:

1. one to **halve an integer**,
2. one to **double an integer**, and
3. one to **state if an integer is even**.

Use these functions to **create a function that does Ethiopian multiplication**.

Related tasks

* Egyptian division

References

* Ethiopian multiplication explained (BBC Video clip)
* A Night Of Numbers - Go Forth And Multiply (Video)
* Russian Peasant Multiplication
* Programming Praxis: Russian Peasant Multiplication

[Assistant]
(formerly Perl 6)

```
sub halve  (Int $n is rw)    { $n div= 2 }
sub double (Int $n is rw)    { $n *= 2 }
sub even   (Int $n --> Bool) { $n %% 2 }

sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) {
    my Int $r = 0;
    while $a {
	even $a or $r += $b;
	halve $a;
	double $b;
    }
    return $r;
}

say ethiopic-mult(17,34);
```

Output:

```
578

```

More succinctly using implicit typing, primed lambdas, and an infinite loop:

```
sub ethiopic-mult {
    my &halve  = * div= 2;
    my &double = * *= 2;
    my &even   = * %% 2;

    my ($a,$b) = @_;
    my $r;
    loop {
        even  $a or $r += $b;
        halve $a or return $r;
        double $b;
    }
}

say ethiopic-mult(17,34);
```

More succinctly still, using a pure functional approach (reductions, mappings, lazy infinite sequences):

```
sub halve  { $^n div 2 }
sub double { $^n * 2   }
sub even   { $^n %% 2  }

sub ethiopic-mult ($a, $b) {
    [+] ($b, &double ... *)
        Z*
        ($a, &halve ... 0).map: { not even $^n }
}

say ethiopic-mult(17,34);
```

(same output)


[User]
Definition

The Euclid–Mullin sequence is an infinite sequence of distinct prime numbers, in which each element is the least prime factor of one plus the product of all earlier elements.

The first element is usually assumed to be 2. So the second element is : (2) + 1 = 3 and the third element is : (2 x 3) + 1 = 7 as this is prime.

Although intermingled with smaller elements, the sequence can produce very large elements quite quickly and only the first 51 have been computed at the time of writing.

Task

Compute and show here the first **16** elements of the sequence or, if your language does not support arbitrary precision arithmetic, as many as you can.

Stretch goal

Compute the next **11** elements of the sequence.

Reference

OEIS sequence A000945

[Assistant]
```
use Prime::Factor;

my @Euclid-Mullin = 2, { state $i = 1; (1 + [×] @Euclid-Mullin[^$i++]).&prime-factors.min } … *;

put 'First sixteen: ', @Euclid-Mullin[^16];

```

Output:

```
First sixteen: 2 3 7 43 13 53 5 6221671 38709183810571 139 2801 11 17 5471 52662739 23003
```


[User]
The **Euclidean rhythm** was proposed by Godfried Toussaint in 2004 and is described in a 2005 paper "The Euclidean Algorithm Generates Traditional Musical Rhythms".[1] It generates many forms of rhythm in music around the world. The program takes 2 integers *(m, n)* and outputs a binary string with *m* ones and *(n-m)* zeros.

As an example, here is how it runs on (5, 13):

* Write 5 ones followed by (13-5) zeros, into 13 groups of 1-digit each:
  + 1 1 1 1 1 | 0 0 0 0 0 0 0 0
* Repeatedly append substitute the second group into the first group:
  + 1 1 1 1 1 | 0 0 0 0 0 0 0 0
  + 10 10 10 10 10 | 0 0 0
  + 100 100 100 10 10 |
* If the first group consists of elements of the same form, then output. Otherwise, divide the first group into two groups of the two forms, and repeat the process:
  + 100 100 100 10 10 |
  + 100 100 100 | 10 10
  + 10010 10010 100 |
* At this point, we can continue the algorithm until only one form remains, but notice that one of the groups has only one element [100], so the algorithm can actually terminate right here and output the concatenation 1001010010100.

[Assistant]
**Translation of**: Perl

```
# 20240208 Raku programming solution

say sub ($k is copy, $n is copy) {
   my @s = [ [1] xx $k ].append: [0] xx ($n - $k);
   my $z = my $d = $n - $k;
   ($k, $n) = ($d, $k).minmax.bounds;

   while $z > 0 || $k > 1 {
      ^$k .map: { @s[$_].append: @s.splice(*-1) }
      ($z, $d) = ($z, $n) X- $k;
      ($k, $n) = ($d, $k).minmax.bounds;
   }
   return [~] @s>>.List.flat;
}(5, 13);

```

You may Attempt This Online!


[User]
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.

The ODE has to be provided in the following form:

:   :   :   d
            y
            (
            t
            )

            d
            t
            =
            f
            (
            t
            ,
            y
            (
            t
            )
            )
            {\displaystyle {\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}}

with an initial value

:   :   :   y
            (

            t

            0
            )
            =

            y

            0
            {\displaystyle {\displaystyle y(t\_{0})=y\_{0}}}

To get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation:

:   :   :   d
            y
            (
            t
            )

            d
            t
            ≈

            y
            (
            t
            +
            h
            )
            −
            y
            (
            t
            )
            h
            {\displaystyle {\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}}

then solve for

y
(
t
+
h
)
{\displaystyle {\displaystyle y(t+h)}}
:

:   :   :   y
            (
            t
            +
            h
            )
            ≈
            y
            (
            t
            )
            +
            h

            d
            y
            (
            t
            )

            d
            t
            {\displaystyle {\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}}

which is the same as

:   :   :   y
            (
            t
            +
            h
            )
            ≈
            y
            (
            t
            )
            +
            h

            f
            (
            t
            ,
            y
            (
            t
            )
            )
            {\displaystyle {\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}}

The iterative solution rule is then:

:   :   :   y

            n
            +
            1
            =

            y

            n
            +
            h

            f
            (

            t

            n
            ,

            y

            n
            )
            {\displaystyle {\displaystyle y\_{n+1}=y\_{n}+h\,f(t\_{n},y\_{n})}}

where

h
{\displaystyle {\displaystyle h}}
   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.

**Example: Newton's Cooling Law**

Newton's cooling law describes how an object of initial temperature

T
(

t

0
)
=

T

0
{\displaystyle {\displaystyle T(t\_{0})=T\_{0}}}
   cools down in an environment of temperature

T

R
{\displaystyle {\displaystyle T\_{R}}}
:

:   :   :   d
            T
            (
            t
            )

            d
            t
            =
            −
            k

            Δ
            T
            {\displaystyle {\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}}

or

:   :   :   d
            T
            (
            t
            )

            d
            t
            =
            −
            k

            (
            T
            (
            t
            )
            −

            T

            R
            )
            {\displaystyle {\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T\_{R})}}

It says that the cooling rate

d
T
(
t
)

d
t
{\displaystyle {\displaystyle {\frac {dT(t)}{dt}}}}
   of the object is proportional to the current temperature difference

Δ
T
=
(
T
(
t
)
−

T

R
)
{\displaystyle {\displaystyle \Delta T=(T(t)-T\_{R})}}
   to the surrounding environment.

The analytical solution, which we will compare to the numerical approximation, is

:   :   :   T
            (
            t
            )
            =

            T

            R
            +
            (

            T

            0
            −

            T

            R
            )

            e

            −
            k
            t
            {\displaystyle {\displaystyle T(t)=T\_{R}+(T\_{0}-T\_{R})\;e^{-kt}}}

Task

Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:

:   :   :   * 2 s
            * 5 s       and
            * 10 s

and to compare with the analytical solution.

Initial values
:   :   :   * initial temperature

              T

              0
              {\displaystyle {\displaystyle T\_{0}}}
                 shall be   100 °C
            * room temperature

              T

              R
              {\displaystyle {\displaystyle T\_{R}}}
                 shall be   20 °C
            * cooling constant

              k
              {\displaystyle {\displaystyle k}}
                   shall be   0.07
            * time interval to calculate shall be from   0 s   ──►   100 s

A reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy.

[Assistant]
(formerly Perl 6)

```
sub euler ( &f, $y0, $a, $b, $h ) {
    my $y = $y0;
    my @t_y;
    for $a, * + $h ... * > $b -> $t {
        @t_y[$t] = $y;
        $y += $h × f( $t, $y );
    }
    @t_y
}

constant COOLING_RATE = 0.07;
constant AMBIENT_TEMP =   20;
constant INITIAL_TEMP =  100;
constant INITIAL_TIME =    0;
constant FINAL_TIME   =  100;

sub f ( $time, $temp ) {
    -COOLING_RATE × ( $temp - AMBIENT_TEMP )
}

my @e;
@e[$_] = euler( &f, INITIAL_TEMP, INITIAL_TIME, FINAL_TIME, $_ ) for 2, 5, 10;

say 'Time Analytic   Step2   Step5  Step10     Err2     Err5    Err10';

for INITIAL_TIME, * + 10 ... * >= FINAL_TIME -> $t {

    my $exact = AMBIENT_TEMP + (INITIAL_TEMP - AMBIENT_TEMP)
                              × (-COOLING_RATE × $t).exp;

    my $err = sub { @^a.map: { 100 × ($_ - $exact).abs / $exact } }

    my ( $a, $b, $c ) = map { @e[$_][$t] }, 2, 5, 10;

    say $t.fmt('%4d '), ( $exact, $a, $b, $c )».fmt(' %7.3f'),
                            $err([$a, $b, $c])».fmt(' %7.3f%%');
}

```

Output:

```
Time Analytic   Step2   Step5  Step10     Err2     Err5    Err10
   0  100.000 100.000 100.000 100.000   0.000%   0.000%   0.000%
  10   59.727  57.634  53.800  44.000   3.504%   9.923%  26.331%
  20   39.728  37.704  34.281  27.200   5.094%  13.711%  31.534%
  30   29.797  28.328  26.034  22.160   4.927%  12.629%  25.629%
  40   24.865  23.918  22.549  20.648   3.808%   9.313%  16.959%
  50   22.416  21.843  21.077  20.194   2.555%   5.972%   9.910%
  60   21.200  20.867  20.455  20.058   1.569%   3.512%   5.384%
  70   20.596  20.408  20.192  20.017   0.912%   1.959%   2.808%
  80   20.296  20.192  20.081  20.005   0.512%   1.057%   1.432%
  90   20.147  20.090  20.034  20.002   0.281%   0.559%   0.721%
 100   20.073  20.042  20.014  20.000   0.152%   0.291%   0.361%
```


[User]
Task.

Compute the Euler constant 0.5772...

Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.

Denoted gamma (*γ*), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).

The definition of *γ* converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.

In 1961, the young Donald Knuth used Euler's method to evaluate *γ* to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.

The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: *2d* digits of working precision obtain *d* correct places only.

This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.

Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that *γ* is neither rational nor algebraic, but this is yet to be proven.

References.

[1]
Gourdon and Sebah, The Euler constant *γ*. (for all formulas)

[2]
Euler's original journal article translated from the latin (p. 9)

[Assistant]
```
# 20211124 Raku programming solution

sub gamma (\N where N > 1) { # Vacca series https://w.wiki/4ybp
                             # convert terms to FatRat for arbitrary precision
   return  (1/2 - 1/3) + [+] (2..N).race.map: -> \n {

      my ($power, $sign, $term) = 2**n, -1;

      for ($power..^2*$power) { $term += ($sign = -$sign) / $_ }

      n*$term
   }
}

say gamma 23 ;

```

Output:

```
0.5772149198434515

```