[User]
Definition

A word is an   *ABC word*   if the letters  "**a**",  "**b**"  and  "**c**"  appear in the word in alphabetical order.

If any or all of these letters occur more than once in a word, then only the first occurrence of each letter should be used to determine whether a word is an  *ABC word*  or not.

Task

Show here   (on this page)   every  *ABC word*  in unixdict.txt.

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]
```
put display 'unixdict.txt'.IO.words».fc.grep({ (.index('a')//next) < (.index('b')//next) < (.index('c')//next) }),
     :11cols, :fmt('%-12s');

sub display ($list, :$cols = 10, :$fmt = '%6d', :$title = "{+$list} matching:\n" )   {
    cache $list;
    $title ~ $list.batch($cols)».fmt($fmt).join: "\n"
}

```

Output:

```
55 matching:
aback        abacus       abc          abdicate     abduct       abeyance     abject       abreact      abscess      abscissa     abscissae
absence      abstract     abstracter   abstractor   adiabatic    aerobacter   aerobic      albacore     alberich     albrecht     algebraic
alphabetic   ambiance     ambuscade    aminobenzoic anaerobic    arabic       athabascan   auerbach     diabetic     diabolic     drawback
fabric       fabricate    flashback    halfback     iambic       lampblack    leatherback  metabolic    nabisco      paperback    parabolic
playback     prefabricate quarterback  razorback    roadblock    sabbatical   snapback     strabismic   syllabic     tabernacle   tablecloth
```


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

Implement the **Abelian sandpile model** also known as **Bak–Tang–Wiesenfeld model**. Its history, mathematical definition and properties can be found under its wikipedia article.

The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it *collapses*, resulting in **four particles being subtracted from the pile** and **distributed among its neighbors.**

It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.
Examples up to 2^30, wow!
javascript running on web
**Examples:**

```
0 0 0 0 0    0 0 0 0 0
0 0 0 0 0    0 0 1 0 0
0 0 4 0 0 -> 0 1 0 1 0
0 0 0 0 0    0 0 1 0 0
0 0 0 0 0    0 0 0 0 0

0 0 0 0 0    0 0 0 0 0
0 0 0 0 0    0 0 1 0 0
0 0 6 0 0 -> 0 1 2 1 0
0 0 0 0 0    0 0 1 0 0
0 0 0 0 0    0 0 0 0 0

0  0 0  0  0    0 0 1 0 0
0  0 0  0  0    0 2 1 2 0
0  0 16 0  0 -> 1 1 0 1 1
0  0 0  0  0    0 2 1 2 0
0  0 0  0  0    0 0 1 0 0

```

[Assistant]
(formerly Perl 6)

### Terminal based

**Works with**: Rakudo version 2019.07.1

Defaults to a stack of 1000 and showing progress. Pass in a custom stack size if desired and -hide-progress to run without displaying progress (much faster.)

```
sub cleanup { print "\e[0m\e[?25h\n"; exit(0) }

signal(SIGINT).tap: { cleanup(); exit(0) }

unit sub MAIN ($stack = 1000, :$hide-progress = False );

my @color = "\e[38;2;0;0;0m█",
            "\e[38;2;255;0;0m█",
            "\e[38;2;255;255;0m█",
            "\e[38;2;0;0;255m█",
            "\e[38;2;255;255;255m█"
            ;

my ($h, $w) = qx/stty size/.words».Int;
my $buf = $w * $h;
my @buffer = 0 xx $buf;
my $done;

@buffer[$w * ($h div 2) + ($w div 2) - 1] = $stack;

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

repeat {
    $done = True;
    loop (my int $row; $row < $h; $row = $row + 1) {
        my int $rs = $row * $w; # row start
        my int $re = $rs  + $w; # row end
        loop (my int $idx = $rs; $idx < $re; $idx = $idx + 1) {
            if @buffer[$idx] >= 4 {
                my $grains = @buffer[$idx] div 4;
                @buffer[ $idx - $w ] += $grains if $row > 0;
                @buffer[ $idx - 1  ] += $grains if $idx - 1 >= $rs;
                @buffer[ $idx + $w ] += $grains if $row < $h - 1;
                @buffer[ $idx + 1  ] += $grains if $idx + 1 < $re;
                @buffer[ $idx ] %= 4;
                $done = False;
            }
        }
    }
    unless $hide-progress {
        print "\e[1;1H", @buffer.map( { @color[$_ min 4] }).join;
    }
} until $done;

print "\e[1;1H", @buffer.map( { @color[$_ min 4] }).join;

cleanup;

```

Passing in 2048 as a stack size results in: Abelian-sandpile-model-perl6.png (offsite .png image)

### SDL2 Animation

```
use NativeCall;
use SDL2::Raw;

my ($width, $height) = 900, 900;

unit sub MAIN ($stack = 10000);

my int ($w, $h) = 160, 160;

my $buf = $w * $h;
my @buffer = 0 xx $buf;

@buffer[$w * ($h div 2) + ($w div 2) - 1] = $stack;

SDL_Init(VIDEO);

my SDL_Window $window = SDL_CreateWindow(
    "Abelian sandpile - Raku",
    SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK,
    $width, $height,
    RESIZABLE
);

my SDL_Renderer $renderer = SDL_CreateRenderer( $window, -1, ACCELERATED +| TARGETTEXTURE );

my $asp_texture = SDL_CreateTexture($renderer, %PIXELFORMAT<RGB332>, STREAMING, $w, $h);

my $pixdatabuf = CArray[int64].new(0, $w, $h, $w);

my @color = 0x00, 0xDE, 0x14, 0xAA, 0xFF;

sub render {
    my int $pitch;
    my int $cursor;

    # work-around to pass the pointer-pointer.
    my $pixdata = nativecast(Pointer[int64], $pixdatabuf);
    SDL_LockTexture($asp_texture, SDL_Rect, $pixdata, $pitch);

    $pixdata = nativecast(CArray[int8], Pointer.new($pixdatabuf[0]));

    loop (my int $row; $row < $h; $row = $row + 1) {
        my int $rs = $row * $w; # row start
        my int $re = $rs  + $w; # row end
        loop (my int $idx = $rs; $idx < $re; $idx = $idx + 1) {
            $pixdata[$idx] =  @buffer[$idx] < 4 ?? @color[@buffer[$idx]] !! @color[4];
            if @buffer[$idx] >= 4 {
                my $grains = floor @buffer[$idx] / 4;
                @buffer[ $idx - $w ] += $grains if $row > 0;
                @buffer[ $idx - 1  ] += $grains if $idx - 1 >= $rs;
                @buffer[ $idx + $w ] += $grains if $row < $h - 1;
                @buffer[ $idx + 1  ] += $grains if $idx + 1 < $re;
                @buffer[ $idx ] %= 4;
            }
        }
    }

    SDL_UnlockTexture($asp_texture);

    SDL_RenderCopy($renderer, $asp_texture, SDL_Rect, SDL_Rect.new(:x(0), :y(0), :w($width), :h($height)));
    SDL_RenderPresent($renderer);
}

my $event = SDL_Event.new;

main: loop {

    while SDL_PollEvent($event) {
        my $casted_event = SDL_CastEvent($event);

        given $casted_event {
            when *.type == QUIT {
                last main;
            }
        }
    }

    render();
    print fps;
}

say '';

sub fps {
    state $fps-frames = 0;
    state $fps-now    = now;
    state $fps        = '';
    $fps-frames++;
    if now - $fps-now >= 1 {
        $fps = [~] "\b" x 40, ' ' x 20, "\b" x 20 ,
            sprintf "FPS: %5.2f  ", ($fps-frames / (now - $fps-now)).round(.01);
        $fps-frames = 0;
        $fps-now = now;
    }
    $fps
}

```

Passing in a stack size of 20000 results in: Abelian-sandpile-sdl2.png (offsite .png image)


[User]
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).

E.g. `s1` =

```

    1 2 0
    2 1 1
    0 1 3

```

and `s2` =

```
    2 1 3
    1 0 1
    0 1 0

```

Addition on sandpiles is done by adding numbers in corresponding grid areas,
so for the above:

```
              1 2 0     2 1 3     3 3 3
    s1 + s2 = 2 1 1  +  1 0 1  =  3 1 2
              0 1 3     0 1 0     0 2 3

```

If the addition would result in more than 3 "grains of sand" in any area then
those areas cause the whole sandpile to become "unstable" and the sandpile
areas are "toppled" in an "avalanche" until the "stable" result is obtained.

Any unstable area (with a number >= 4), is "toppled" by loosing one grain of
sand to each of its four horizontal or vertical neighbours. Grains are lost
at the edge of the grid, but otherwise increase the number in neighbouring
cells by one, whilst decreasing the count in the toppled cell by four in each
toppling.

A toppling may give an adjacent area more than four grains of sand leading to
a chain of topplings called an "avalanche".
E.g.

```

    4 3 3     0 4 3     1 0 4     1 1 0     2 1 0
    3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3
    0 2 3     0 2 3     0 2 3     0 2 3     1 2 3

```

The final result is the stable sandpile on the right.

**Note:** The order in which cells are toppled does not affect the final result.

Task

* Create a class or datastructure and functions to represent and operate on sandpiles.
* Confirm the result of the avalanche of topplings shown above
* Confirm that s1 + s2 == s2 + s1 # Show the stable results
* If s3 is the sandpile with number 3 in every grid area, and s3\_id is the following sandpile:

```
    2 1 2
    1 0 1
    2 1 2

```

* Show that `s3 + s3_id == s3`
* Show that `s3_id + s3_id == s3_id`

Show confirming output here, with your examples.

References

* https://www.youtube.com/watch?v=1MtEUErz7Gg
* https://en.wikipedia.org/wiki/Abelian\_sandpile\_model

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

Most of the logic is lifted straight from the Abelian sandpile model task.

```
class ASP {
    has $.h = 3;
    has $.w = 3;
    has @.pile = 0 xx $!w * $!h;

    method topple {
        my $buf = $!w * $!h;
        my $done;
        repeat {
            $done = True;
            loop (my int $row; $row < $!h; $row = $row + 1) {
                my int $rs = $row * $!w; # row start
                my int $re = $rs  + $!w; # row end
                loop (my int $idx = $rs; $idx < $re; $idx = $idx + 1) {
                    if self.pile[$idx] >= 4 {
                        my $grain = self.pile[$idx] div 4;
                        self.pile[ $idx - $!w ] += $grain if $row > 0;
                        self.pile[ $idx - 1  ]  += $grain if $idx - 1 >= $rs;
                        self.pile[ $idx + $!w ] += $grain if $row < $!h - 1;
                        self.pile[ $idx + 1  ]  += $grain if $idx + 1 < $re;
                        self.pile[ $idx ] %= 4;
                        $done = False;
                    }
                }
            }
        } until $done;
        self.pile;
    }
}

# some handy display layout modules
use Terminal::Boxer:ver<0.2+>;
use Text::Center;

for 3, (4,3,3,3,1,2,0,2,3), (2,1,2,1,0,1,2,1,2), # 3 square task example
    3, (2,1,2,1,0,1,2,1,2), (2,1,2,1,0,1,2,1,2), # 3 square identity
    5, (4,1,0,5,1,9,3,6,1,0,8,1,2,5,3,3,0,1,7,5,4,2,2,4,0), (2,3,2,3,2,3,2,1,2,3,2,1,0,1,2,3,2,1,2,3,2,3,2,3,2) # 5 square test
  -> $size, $pile, $identity {

    my $asp = ASP.new(:h($size), :w($size));

    $asp.pile = |$pile;

    my @display;

    my %p = :col($size), :3cw, :indent("\t");

    @display.push: rs-box |%p, |$identity;

    @display.push: rs-box |%p, $asp.pile;

    @display.push: rs-box |%p, $asp.topple;

    $asp.pile Z+= $identity.list;

    @display.push: rs-box |%p, $asp.pile;

    @display.push: rs-box |%p, $asp.topple;

    put %p<indent> ~ qww<identity 'test pile' toppled 'plus identity' toppled>».&center($size * 4 + 1).join: %p<indent>;

    .put for [Z~] @display».lines;

    put '';
}

```

Output:

```
	   identity  	  test pile  	   toppled   	plus identity	   toppled
	╭───┬───┬───╮	╭───┬───┬───╮	╭───┬───┬───╮	╭───┬───┬───╮	╭───┬───┬───╮
	│ 2 │ 1 │ 2 │	│ 4 │ 3 │ 3 │	│ 2 │ 1 │ 0 │	│ 4 │ 2 │ 2 │	│ 2 │ 1 │ 0 │
	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤
	│ 1 │ 0 │ 1 │	│ 3 │ 1 │ 2 │	│ 0 │ 3 │ 3 │	│ 1 │ 3 │ 4 │	│ 0 │ 3 │ 3 │
	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤
	│ 2 │ 1 │ 2 │	│ 0 │ 2 │ 3 │	│ 1 │ 2 │ 3 │	│ 3 │ 3 │ 5 │	│ 1 │ 2 │ 3 │
	╰───┴───┴───╯	╰───┴───┴───╯	╰───┴───┴───╯	╰───┴───┴───╯	╰───┴───┴───╯

	   identity  	  test pile  	   toppled   	plus identity	   toppled
	╭───┬───┬───╮	╭───┬───┬───╮	╭───┬───┬───╮	╭───┬───┬───╮	╭───┬───┬───╮
	│ 2 │ 1 │ 2 │	│ 2 │ 1 │ 2 │	│ 2 │ 1 │ 2 │	│ 4 │ 2 │ 4 │	│ 2 │ 1 │ 2 │
	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤
	│ 1 │ 0 │ 1 │	│ 1 │ 0 │ 1 │	│ 1 │ 0 │ 1 │	│ 2 │ 0 │ 2 │	│ 1 │ 0 │ 1 │
	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤	├───┼───┼───┤
	│ 2 │ 1 │ 2 │	│ 2 │ 1 │ 2 │	│ 2 │ 1 │ 2 │	│ 4 │ 2 │ 4 │	│ 2 │ 1 │ 2 │
	╰───┴───┴───╯	╰───┴───┴───╯	╰───┴───┴───╯	╰───┴───┴───╯	╰───┴───┴───╯

	       identity      	      test pile      	       toppled       	    plus identity    	       toppled
	╭───┬───┬───┬───┬───╮	╭───┬───┬───┬───┬───╮	╭───┬───┬───┬───┬───╮	╭───┬───┬───┬───┬───╮	╭───┬───┬───┬───┬───╮
	│ 2 │ 3 │ 2 │ 3 │ 2 │	│ 4 │ 1 │ 0 │ 5 │ 1 │	│ 1 │ 3 │ 2 │ 1 │ 0 │	│ 3 │ 6 │ 4 │ 4 │ 2 │	│ 1 │ 3 │ 2 │ 1 │ 0 │
	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤
	│ 3 │ 2 │ 1 │ 2 │ 3 │	│ 9 │ 3 │ 6 │ 1 │ 0 │	│ 2 │ 2 │ 3 │ 3 │ 1 │	│ 5 │ 4 │ 4 │ 5 │ 4 │	│ 2 │ 2 │ 3 │ 3 │ 1 │
	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤
	│ 2 │ 1 │ 0 │ 1 │ 2 │	│ 8 │ 1 │ 2 │ 5 │ 3 │	│ 1 │ 1 │ 2 │ 0 │ 3 │	│ 3 │ 2 │ 2 │ 1 │ 5 │	│ 1 │ 1 │ 2 │ 0 │ 3 │
	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤
	│ 3 │ 2 │ 1 │ 2 │ 3 │	│ 3 │ 0 │ 1 │ 7 │ 5 │	│ 2 │ 0 │ 3 │ 2 │ 0 │	│ 5 │ 2 │ 4 │ 4 │ 3 │	│ 2 │ 0 │ 3 │ 2 │ 0 │
	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤	├───┼───┼───┼───┼───┤
	│ 2 │ 3 │ 2 │ 3 │ 2 │	│ 4 │ 2 │ 2 │ 4 │ 0 │	│ 3 │ 2 │ 3 │ 2 │ 1 │	│ 5 │ 5 │ 5 │ 5 │ 3 │	│ 3 │ 2 │ 3 │ 2 │ 1 │
	╰───┴───┴───┴───┴───╯	╰───┴───┴───┴───┴───╯	╰───┴───┴───┴───┴───╯	╰───┴───┴───┴───┴───╯	╰───┴───┴───┴───┴───╯

```


[User]
**Abstract type** is a type without instances or without definition.

For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called **interfaces**. In the languages that do not support multiple inheritance (Ada, Java), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like C++) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, OO languages normally prevent instantiation from them (instantiation must derived from one of their descendant classes).

The term **abstract datatype** also may denote a type, with an implementation provided by the programmer rather than directly by the language (a **built-in** or an inferred type). Here the word *abstract* means that the implementation is abstracted away, irrelevant for the user of the type. Such implementation can and should be hidden if the language supports separation of implementation and specification. This hides complexity while allowing the implementation to change without repercussions on the usage. The corresponding software design practice is said to follow the information hiding principle.

It is important not to confuse this *abstractness* (of implementation) with one of the **abstract type**. The latter is abstract in the sense that the set of its values is empty. In the sense of implementation abstracted away, all user-defined types are abstract.

In some languages, like for example in Objective Caml which is strongly statically typed, it is also possible to have **abstract types** that are not OO related and are not an abstractness too. These are *pure abstract types* without any definition even in the implementation and can be used for example for the type algebra, or for some consistence of the type inference. For example in this area, an abstract type can be used as a phantom type to augment another type as its parameter.

**Task**: show how an abstract type can be declared in the language. If the language makes a distinction between interfaces and partially implemented types illustrate both.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015.12

Raku supports roles, which are a bit like interfaces, but unlike interfaces in Java they can also contain some implementation.

```
use v6;

role A {
    # must be filled in by the class it is composed into
    method abstract() { ... };

    # can be overridden in the class, but that's not mandatory
    method concrete() { say '# 42' };
}

class SomeClass does A {
    method abstract() {
        say "# made concrete in class"
    }
}

my $obj = SomeClass.new;
$obj.abstract();
$obj.concrete();

# output:
# made concrete in class
# 42

```


[User]
An Abundant number is a number **n** for which the   *sum of divisors*   **σ
(
n
)
>
2
n
{\displaystyle {\displaystyle \sigma (n)>2n}}**,

or,   equivalently,   the   *sum of proper divisors*   (or aliquot sum)       **s
(
n
)
>
n
{\displaystyle {\displaystyle s(n)>n}}**.

E.G.

**12**   is abundant, it has the proper divisors     **1, 2, 3, 4 & 6**     which sum to   **16**   ( > **12** or **n**);

       or alternately,   has the sigma sum of   **1, 2, 3, 4, 6 & 12**   which sum to   **28**   ( > **24** or **2n**).

Abundant numbers are common, though **even** abundant numbers seem to be much more common than **odd** abundant numbers.

To make things more interesting, this task is specifically about finding   *odd abundant numbers*.

Task

* Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
* Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
* Find and display here: the first abundant odd number greater than one billion (

  10

  9
  {\displaystyle {\displaystyle 10^{9}}}
  ) and either its proper divisor sum or sigma sum.

References
:   * OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
    * American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03

```
sub odd-abundant (\x) {
    my @l = x.is-prime ?? 1 !! flat
    1, (3 .. x.sqrt.floor).map: -> \d {
         next unless d +& 1;
         my \y = x div d;
         next if y * d !== x;
         d !== y ?? (d, y) !! d
    };
    @l.sum > x ?? @l.sort !! Empty;
}

sub odd-abundants (Int :$start-at is copy) {
    $start-at = ( $start-at + 2 ) div 3;
    $start-at += $start-at %% 2;
    $start-at *= 3;
    ($start-at, *+6 ... *).hyper.map: {
        next unless my $oa = cache .&odd-abundant;
        sprintf "%6d: divisor sum: {$oa.join: ' + '} = {$oa.sum}", $_
    }
}

put 'First 25 abundant odd numbers:';
.put for odd-abundants( :start-at(1) )[^25];

put "\nOne thousandth abundant odd number:\n" ~ odd-abundants( :start-at(1) )[999] ~

"\n\nFirst abundant odd number above one billion:\n" ~ odd-abundants( :start-at(1_000_000_000) ).head;

```

Output:

```
First 25 abundant odd numbers:
   945: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 27 + 35 + 45 + 63 + 105 + 135 + 189 + 315 = 975
  1575: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 63 + 75 + 105 + 175 + 225 + 315 + 525 = 1649
  2205: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 35 + 45 + 49 + 63 + 105 + 147 + 245 + 315 + 441 + 735 = 2241
  2835: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 27 + 35 + 45 + 63 + 81 + 105 + 135 + 189 + 315 + 405 + 567 + 945 = 2973
  3465: divisor sum: 1 + 3 + 5 + 7 + 9 + 11 + 15 + 21 + 33 + 35 + 45 + 55 + 63 + 77 + 99 + 105 + 165 + 231 + 315 + 385 + 495 + 693 + 1155 = 4023
  4095: divisor sum: 1 + 3 + 5 + 7 + 9 + 13 + 15 + 21 + 35 + 39 + 45 + 63 + 65 + 91 + 105 + 117 + 195 + 273 + 315 + 455 + 585 + 819 + 1365 = 4641
  4725: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 27 + 35 + 45 + 63 + 75 + 105 + 135 + 175 + 189 + 225 + 315 + 525 + 675 + 945 + 1575 = 5195
  5355: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 17 + 21 + 35 + 45 + 51 + 63 + 85 + 105 + 119 + 153 + 255 + 315 + 357 + 595 + 765 + 1071 + 1785 = 5877
  5775: divisor sum: 1 + 3 + 5 + 7 + 11 + 15 + 21 + 25 + 33 + 35 + 55 + 75 + 77 + 105 + 165 + 175 + 231 + 275 + 385 + 525 + 825 + 1155 + 1925 = 6129
  5985: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 19 + 21 + 35 + 45 + 57 + 63 + 95 + 105 + 133 + 171 + 285 + 315 + 399 + 665 + 855 + 1197 + 1995 = 6495
  6435: divisor sum: 1 + 3 + 5 + 9 + 11 + 13 + 15 + 33 + 39 + 45 + 55 + 65 + 99 + 117 + 143 + 165 + 195 + 429 + 495 + 585 + 715 + 1287 + 2145 = 6669
  6615: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 27 + 35 + 45 + 49 + 63 + 105 + 135 + 147 + 189 + 245 + 315 + 441 + 735 + 945 + 1323 + 2205 = 7065
  6825: divisor sum: 1 + 3 + 5 + 7 + 13 + 15 + 21 + 25 + 35 + 39 + 65 + 75 + 91 + 105 + 175 + 195 + 273 + 325 + 455 + 525 + 975 + 1365 + 2275 = 7063
  7245: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 23 + 35 + 45 + 63 + 69 + 105 + 115 + 161 + 207 + 315 + 345 + 483 + 805 + 1035 + 1449 + 2415 = 7731
  7425: divisor sum: 1 + 3 + 5 + 9 + 11 + 15 + 25 + 27 + 33 + 45 + 55 + 75 + 99 + 135 + 165 + 225 + 275 + 297 + 495 + 675 + 825 + 1485 + 2475 = 7455
  7875: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 63 + 75 + 105 + 125 + 175 + 225 + 315 + 375 + 525 + 875 + 1125 + 1575 + 2625 = 8349
  8085: divisor sum: 1 + 3 + 5 + 7 + 11 + 15 + 21 + 33 + 35 + 49 + 55 + 77 + 105 + 147 + 165 + 231 + 245 + 385 + 539 + 735 + 1155 + 1617 + 2695 = 8331
  8415: divisor sum: 1 + 3 + 5 + 9 + 11 + 15 + 17 + 33 + 45 + 51 + 55 + 85 + 99 + 153 + 165 + 187 + 255 + 495 + 561 + 765 + 935 + 1683 + 2805 = 8433
  8505: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 27 + 35 + 45 + 63 + 81 + 105 + 135 + 189 + 243 + 315 + 405 + 567 + 945 + 1215 + 1701 + 2835 = 8967
  8925: divisor sum: 1 + 3 + 5 + 7 + 15 + 17 + 21 + 25 + 35 + 51 + 75 + 85 + 105 + 119 + 175 + 255 + 357 + 425 + 525 + 595 + 1275 + 1785 + 2975 = 8931
  9135: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 29 + 35 + 45 + 63 + 87 + 105 + 145 + 203 + 261 + 315 + 435 + 609 + 1015 + 1305 + 1827 + 3045 = 9585
  9555: divisor sum: 1 + 3 + 5 + 7 + 13 + 15 + 21 + 35 + 39 + 49 + 65 + 91 + 105 + 147 + 195 + 245 + 273 + 455 + 637 + 735 + 1365 + 1911 + 3185 = 9597
  9765: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 31 + 35 + 45 + 63 + 93 + 105 + 155 + 217 + 279 + 315 + 465 + 651 + 1085 + 1395 + 1953 + 3255 = 10203
 10395: divisor sum: 1 + 3 + 5 + 7 + 9 + 11 + 15 + 21 + 27 + 33 + 35 + 45 + 55 + 63 + 77 + 99 + 105 + 135 + 165 + 189 + 231 + 297 + 315 + 385 + 495 + 693 + 945 + 1155 + 1485 + 2079 + 3465 = 12645
 11025: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 49 + 63 + 75 + 105 + 147 + 175 + 225 + 245 + 315 + 441 + 525 + 735 + 1225 + 1575 + 2205 + 3675 = 11946

One thousandth abundant odd number:
492975: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 63 + 75 + 105 + 175 + 225 + 313 + 315 + 525 + 939 + 1565 + 1575 + 2191 + 2817 + 4695 + 6573 + 7825 + 10955 + 14085 + 19719 + 23475 + 32865 + 54775 + 70425 + 98595 + 164325 = 519361

First abundant odd number above one billion:
1000000575: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 49 + 63 + 75 + 105 + 147 + 175 + 225 + 245 + 315 + 441 + 525 + 735 + 1225 + 1575 + 2205 + 3675 + 11025 + 90703 + 272109 + 453515 + 634921 + 816327 + 1360545 + 1904763 + 2267575 + 3174605 + 4081635 + 4444447 + 5714289 + 6802725 + 9523815 + 13333341 + 15873025 + 20408175 + 22222235 + 28571445 + 40000023 + 47619075 + 66666705 + 111111175 + 142857225 + 200000115 + 333333525 = 1083561009
```


[User]
These define three classifications of positive integers based on their   proper divisors.

Let   P(n)   be the sum of the proper divisors of   **n**   where the proper divisors are all positive divisors of   **n**   other than   **n**   itself.

```
   if    P(n) <  n    then  n  is classed as  deficient  (OEIS A005100).
   if    P(n) == n    then  n  is classed as  perfect    (OEIS A000396).
   if    P(n) >  n    then  n  is classed as  abundant   (OEIS A005101).

```

Example

**6**   has proper divisors of   **1**,   **2**,   and   **3**.

**1 + 2 + 3 = 6**,   so   **6**   is classed as a perfect number.

Task

Calculate how many of the integers   **1**   to   **20,000**   (inclusive) are in each of the three classes.

Show the results here.

Related tasks

* Aliquot sequence classifications.   (The whole series from which this task is a subset.)
* Proper divisors
* Amicable pairs

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.12

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

say bag (1..20000).map: { propdivsum($_) <=> $_ }

```

Output:

```
Bag(Less(15043), More(4953), Same(4))
```


[User]
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).

Rules

The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in *small italic text*).

:   Before you submit an example, make sure the function

:   1. Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
       Although these exact function and parameter names need not be used
    2. Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) *(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)*
    3. Generates functions that return the sum of every number ever passed to them, not just the most recent. *(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)*
    4. Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. *(Follow your language's conventions here.)*
    5. Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. *(No global variables or other such things.)*
:   E.g. if after the example, you added the following code (in a made-up language) *where the factory function is called foo*:

    :   ```
        x = foo(1);
        x(5);
        foo(3);
        print x(2.3);
        ```
:   It should print 8.3. *(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)*

Task

Create a function that implements the described rules.

It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.

Where it is not possible to hold exactly to the constraints above, describe the deviations.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

```
sub accum ($n is copy) { sub { $n += $^x } }

#Example use:
my $a = accum 5;
$a(4.5);
say $a(.5);   # Prints "10".

# You can also use the "&" sigil to create a function that behaves syntactically
# like any other function (i.e. no sigil nor parentheses needed to call it):

my &b = accum 5;
say b 3;   # Prints "8".
```


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

An **Achilles number** is a number that is powerful but imperfect. *Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect.*

A positive integer **n** is a powerful number if, for every prime factor **p** of **n**, **p2** is also a divisor.

In other words, every prime factor appears at least squared in the factorization.

All **Achilles numbers** are powerful. However, not all powerful numbers are **Achilles numbers**: only those that cannot be represented as **mk**, where **m** and **k** are positive integers greater than **1**.

A ***strong* Achilles number** is an **Achilles number** whose **Euler totient (𝜑)** is also an **Achilles number**.

E.G.

**108** is a powerful number. Its prime factorization is **22 × 33**, and thus its prime factors are **2** and **3**. Both **22 = 4** and **32 = 9** are divisors of **108**. However, **108** cannot be represented as **mk**, where **m** and **k** are positive integers greater than **1**, so **108** is an **Achilles number**.

**360** is *not* an **Achilles number** because it is not powerful. One of its prime factors is **5** but **360** is not divisible by **52 = 25**.

Finally, **784** is *not* an **Achilles number**. It is a powerful number, because not only are **2** and **7** its only prime factors, but also **22 = 4** and **72 = 49** are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is *not* an **Achilles number**.

**500 = 22 × 53** is a ***strong* Achilles number** as its Euler totient, **𝜑(500)**, is **200 = 23 × 52** which is *also* an **Achilles number**.

Task

* Find and show the first 50 **Achilles numbers**.
* Find and show at least the first 20 ***strong* Achilles numbers**.
* For at least 2 through 5, show the count of **Achilles numbers** with that many digits.

See also

* Wikipedia: Achilles number * OEIS:A052486 - Achilles numbers - powerful but imperfect numbers * OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number * Related task: Powerful numbers * Related task: Totient function

[Assistant]
Timing is going to be system / OS dependent.

```
use Prime::Factor;
use Math::Root;

sub is-square-free (Int \n) {
    constant @p = ^100 .map: { next unless .is-prime; .² };
    for @p -> \p { return False if n %% p }
    True
}

sub powerful (\n, \k = 2) {
    my @p;
    p(1, 2*k - 1);
    sub p (\m, \r) {
        @p.push(m) and return if r < k;
        for 1 .. (n / m).&root(r) -> \v {
            if r > k {
                next unless is-square-free(v);
                next unless m gcd v == 1;
            }
            p(m * v ** r, r - 1)
        }
    }
    @p
}

my $achilles = powerful(10**9).hyper(:500batch).grep( {
    my $f = .&prime-factors.Bag;
    (+$f.keys > 1) && (1 == [gcd] $f.values) && (.sqrt.Int² !== $_)
} ).classify: { .chars }

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

my %as = Set.new: flat $achilles.values».list;

my $strong = lazy (flat $achilles.sort».value».list».sort).grep: { ?%as{𝜑[$_]} };

put "First 50 Achilles numbers:";
put (flat $achilles.sort».value».list».sort)[^50].batch(10)».fmt("%4d").join("\n");

put "\nFirst 30 strong Achilles numbers:";
put   $strong[^30].batch(10)».fmt("%5d").join("\n");

put "\nNumber of Achilles numbers with:";
say "$_ digits: " ~ +$achilles{$_} // 0 for 2..9;

printf "\n%.1f total elapsed seconds\n", now - INIT now;

```

Output:

```
First 50 Achilles numbers:
  72  108  200  288  392  432  500  648  675  800
 864  968  972 1125 1152 1323 1352 1372 1568 1800
1944 2000 2312 2592 2700 2888 3087 3200 3267 3456
3528 3872 3888 4000 4232 4500 4563 4608 5000 5292
5324 5400 5408 5488 6075 6125 6272 6728 6912 7200

First 30 strong Achilles numbers:
  500   864  1944  2000  2592  3456  5000 10125 10368 12348
12500 16875 19652 19773 30375 31104 32000 33275 37044 40500
49392 50000 52488 55296 61731 64827 67500 69984 78608 80000

Number of Achilles numbers with:
2 digits: 1
3 digits: 12
4 digits: 47
5 digits: 192
6 digits: 664
7 digits: 2242
8 digits: 7395
9 digits: 24008

6.1 total elapsed seconds
```

Could go further but slows to a crawl and starts chewing up memory in short order.

```
10 digits: 77330
11 digits: 247449
12 digits: 788855

410.4 total elapsed seconds

```


[User]
The **Ackermann function** is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.

The Ackermann function is usually defined as follows:

:   A
    (
    m
    ,
    n
    )
    =

    {

    n
    +
    1

    if
    m
    =
    0

    A
    (
    m
    −
    1
    ,
    1
    )

    if
    m
    >
    0

     and
    n
    =
    0

    A
    (
    m
    −
    1
    ,
    A
    (
    m
    ,
    n
    −
    1
    )
    )

    if
    m
    >
    0

     and
    n
    >
    0.

    {\displaystyle {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}}

Its arguments are never negative and it always terminates.

Task

Write a function which returns the value of

A
(
m
,
n
)
{\displaystyle {\displaystyle A(m,n)}}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.

See also

* Conway chained arrow notation for the Ackermann function.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

```
sub A(Int $m, Int $n) {
    if    $m == 0 { $n + 1 }
    elsif $n == 0 { A($m - 1, 1) }
    else          { A($m - 1, A($m, $n - 1)) }
}
```

An implementation using multiple dispatch:

```
multi sub A(0,      Int $n) { $n + 1                   }
multi sub A(Int $m, 0     ) { A($m - 1, 1)             }
multi sub A(Int $m, Int $n) { A($m - 1, A($m, $n - 1)) }
```

Note that in either case, Int is defined to be arbitrary precision in Raku.

Here's a caching version of that, written in the sigilless style, with liberal use of Unicode, and the extra optimizing terms to make A(4,2) possible:

```
proto A(Int \𝑚, Int \𝑛) { (state @)[𝑚][𝑛] //= {*} }

multi A(0,      Int \𝑛) { 𝑛 + 1 }
multi A(1,      Int \𝑛) { 𝑛 + 2 }
multi A(2,      Int \𝑛) { 3 + 2 * 𝑛 }
multi A(3,      Int \𝑛) { 5 + 8 * (2 ** 𝑛 - 1) }

multi A(Int \𝑚, 0     ) { A(𝑚 - 1, 1) }
multi A(Int \𝑚, Int \𝑛) { A(𝑚 - 1, A(𝑚, 𝑛 - 1)) }

# Testing:
say A(4,1);
say .chars, " digits starting with ", .substr(0,50), "..." given A(4,2);
```

Output:

```
65533
19729 digits starting with 20035299304068464649790723515602557504478254755697...
```


[User] The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.

[Assistant]
(formerly Perl 6)

Using module LMDB - bindings to the openLDAP library. Requires an LDAP instance.

```
use LMDB;

my %DB := LMDB::DB.open(:path<some-dir>, %connection-parameters);

```

%DB may be accessed, read from and written to like a native hash.


[User] Make sure you Connect to Active Directory

[Assistant]
(formerly Perl 6)

```
# 20190718 Raku programming solution
# https://github.com/perl6/doc/issues/2898
# https://www.facebook.com/groups/perl6/permalink/2379873082279037/

# Reference:
# https://github.com/Altai-man/cro-ldap
# https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/

use v6.d;
use Cro::LDAP::Client;

my $client = await Cro::LDAP::Client.connect('ldap://ldap.forumsys.com');

my $bind = await $client.bind(
   name=>'cn=read-only-admin,dc=example,dc=com',password=>'password'
);
die $bind.error-message if $bind.result-code;

my $resp = $client.search(
   :dn<dc=example,dc=com>, base=>"ou=mathematicians", filter=>'(&(uid=gauss))'
);

react {
   whenever $resp -> $entry {
      for $entry.attributes.kv -> $k, $v {
         my $value-str = $v ~~ Blob ?? $v.decode !! $v.map(*.decode);
         note "$k -> $value-str";
      }
   }
}

```

Output:

```
objectClass -> inetOrgPerson organizationalPerson top person
mail -> gauss@ldap.forumsys.com
uid -> gauss
cn -> Carl Friedrich Gauss
sn -> Gauss

```


[User]
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.

A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.

**The task**

Implement an active integrator object. The object has an input and output. The input can be set using the method *Input*. The input is a function of time. The output can be queried using the method *Output*. The object integrates its input over the time and the result becomes the object's output. So if the input is *K*(*t*) and the output is *S*, the object state *S* is changed to *S* + (*K*(*t*1) + *K*(*t*0)) \* (*t*1 - *t*0) / 2, i.e. it integrates *K* using the trapeze method. Initially *K* is constant 0 and *S* is 0.

In order to test the object:

1. set its input to sin (2π *f t*), where the frequency *f*=0.5Hz. The phase is irrelevant.
2. wait 2s
3. set the input to constant 0
4. wait 0.5s

Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.12

There is some jitter in the timer, but it is typically accurate to within a few thousandths of a second.

```
class Integrator {
    has $.f is rw = sub ($t) { 0 };
    has $.now is rw;
    has $.value is rw = 0;
    has $.integrator is rw;

    method init() {
        self.value = &(self.f)(0);
        self.integrator = Thread.new(
            :code({
                loop {
                    my $t1 = now;
                    self.value += (&(self.f)(self.now) + &(self.f)($t1)) * ($t1 - self.now) / 2;
                    self.now = $t1;
                    sleep .001;
                }
            }),
            :app_lifetime(True)
        ).run
    }

    method Input (&f-of-t) {
        self.f = &f-of-t;
        self.now = now;
        self.init;
    }

    method Output { self.value }
}

my $a = Integrator.new;

$a.Input( sub ($t) { sin(2 * π * .5 * $t) } );

say "Initial value: ", $a.Output;

sleep 2;

say "After 2 seconds: ", $a.Output;

$a.Input( sub ($t) { 0 } );

sleep .5;

say "f(0): ", $a.Output;

```

Typical output:

```
Initial value: 0
After 2 seconds: -0.0005555887464620366
f(0): 0
```


[User]
Demonstrate how to dynamically add variables to an object (a class instance) at runtime.

This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

You can add variables/methods to a class at runtime by composing in a role. The role only affects that instance, though it is inheritable. An object created from an existing object will inherit any roles composed in with values set to those at the time the role was created. If you want to keep changed values in the new object, clone it instead.

```
class Bar { }             # an empty class

my $object = Bar.new;     # new instance

role a_role {             # role to add a variable: foo,
   has $.foo is rw = 2;   # with an initial value of 2
}

$object does a_role;      # compose in the role

say $object.foo;          # prints: 2
$object.foo = 5;          # change the variable
say $object.foo;          # prints: 5

my $ohno = Bar.new;       # new Bar object
#say $ohno.foo;           # runtime error, base Bar class doesn't have the variable foo

my $this = $object.new;   # instantiate a new Bar derived from $object
say $this.foo;            # prints: 2 - original role value

my $that = $object.clone; # instantiate a new Bar derived from $object copying any variables
say $that.foo;            # 5 - value from the cloned object

```

That's what's going on underneath, but often people just mix in an anonymous role directly using the but operator. Here we'll mix an attribute into a normal integer.

```
my $lue = 42 but role { has $.answer = "Life, the Universe, and Everything" }

say $lue;          # 42
say $lue.answer;   # Life, the Universe, and Everything

```

On the other hand, mixins are frowned upon when it is possible to compose roles directly into classes (as with Smalltalk traits), so that you get method collision detection at compile time. If you want to change a class at run time, you can also use monkey patching:

```
use MONKEY-TYPING;
augment class Int {
    method answer { "Life, the Universe, and Everything" }
}
say 42.answer;     # Life, the Universe, and Everything

```

This practice, though allowed, is considered to be Evil Action at a Distance.


[User]
An addition chain of length r for n is a sequence 1 = a(0) < a(1) < a(2) ... < a(r) = n , such as a(k) = a(i) + a(j) ( i < k and j < k , i may be = j) . Each member is the sum of two earlier members, not necessarily distincts.

A Brauer chain for n is an addition chain where a(k) = a(k-1) + a(j) with j < k. Each member uses the previous member as a summand.

We are interested in chains of minimal length L(n).

**Task**

For each n in {7,14,21,29,32,42,64} display the following : L(n), the count of Brauer chains of length L(n), an example of such a Brauer chain, the count of non-brauer chains of length L(n), an example of such a chain. (NB: counts may be 0 ).

Extra-credit: Same task for n in {47, 79, 191, 382 , 379, 12509}

**References**

* OEIS sequences A079301, A079302. [1]
* Richard K. Guy - Unsolved problems in Number Theory - C6 - Addition chains.

**Example**

* minimal chain length l(19) = 6
* brauer-chains(19) : count = 31 Ex: ( 1 2 3 4 8 11 19)
* non-brauer-chains(19) : count = 2 Ex: ( 1 2 3 6 7 12 19)

[Assistant]
(formerly Perl 6)

**Translation of**: Kotlin

```
my @Example = ();

sub check-Sequence($pos, @seq, $n, $minLen --> List)  {
   if ($pos > $minLen or @seq[0] > $n) {
      return $minLen, 0;
   } elsif (@seq[0] == $n) {
      @Example = @seq;
      return $pos, 1;
   } elsif ($pos < $minLen) {
      return try-Permutation 0, $pos, @seq, $n, $minLen;
   } else {
      return $minLen, 0;
   }
}

multi sub try-Permutation($i, $pos, @seq, $n, $minLen --> List) {
   return $minLen, 0 if $i > $pos;
   my @res1 = check-Sequence $pos+1, (@seq[0]+@seq[$i],@seq).flat, $n, $minLen;
   my @res2 = try-Permutation $i+1, $pos, @seq, $n, @res1[0];
   if (@res2[0] < @res1[0]) {
      return @res2[0], @res2[1];
   } elsif (@res2[0] == @res1[0]) {
      return @res2[0], @res1[1]+@res2[1];
   } else {
      note "Error in try-Permutation";
      return 0, 0;
   }
}

multi sub try-Permutation($x, $minLen --> List) {
   return try-Permutation 0, 0, [1], $x, $minLen;
}

sub find-Brauer($num, $minLen, $nbLimit) {
   my ($actualMin, $brauer) = try-Permutation $num, $minLen;
   say "\nN = ", $num;
   say "Minimum length of chains : L($num) = $actualMin";
   say "Number of minimum length Brauer chains : ", $brauer;
   say "Brauer example : ", @Example.reverse if $brauer > 0;
   @Example = ();
   if ($num ≤ $nbLimit) {
      my $nonBrauer = find-Non-Brauer $num, $actualMin+1, $brauer;
      say "Number of minimum length non-Brauer chains : ", $nonBrauer;
      say "Non-Brauer example : ", @Example if $nonBrauer > 0;
      @Example = ();
   } else {
      say "Non-Brauer analysis suppressed";
   }
}

sub is-Addition-Chain(@a --> Bool) {
   for 2 .. @a.end -> $i {
      return False if @a[$i] > @a[$i-1]*2 ;
      my $ok = False;
      for $i-1 … 0 -> $j {
         for $j … 0 -> $k {
            { $ok = True; last } if @a[$j]+@a[$k] == @a[$i];
         }
      }
      return False unless $ok;
   }

   @Example = @a unless @Example or is-Brauer @a;
   return True;
}

sub is-Brauer(@a --> Bool) {
   for 2 .. @a.end -> $i {
      my $ok = False;
      for $i-1 … 0 -> $j {
         { $ok = True; last } if @a[$i-1]+@a[$j] == @a[$i];
      }
      return False unless $ok;
   }
   return True;
}

sub find-Non-Brauer($num, $len, $brauer --> Int) {
   my @seq   = flat 1 .. $len-1, $num;
   my $count = is-Addition-Chain(@seq) ?? 1 !! 0;

   sub next-Chains($index) {
      loop {
         next-Chains $index+1 if $index < $len-1;
         return if @seq[$index]+$len-1-$index ≥ @seq[$len-1];
         @seq[$index]++;
         for $index^..^$len-1 { @seq[$_] = @seq[$_-1] + 1 }
         $count++ if is-Addition-Chain @seq;
      }
   }

   next-Chains 2;
   return $count - $brauer;
}

say "Searching for Brauer chains up to a minimum length of 12:";
find-Brauer $_, 12, 79 for 7, 14, 21, 29, 32, 42, 64 #, 47, 79, 191, 382, 379, 379, 12509 # un-comment for extra-credit

```

Output:

```
Searching for Brauer chains up to a minimum length of 12:

N = 7
Minimum length of chains : L(7) = 4
Number of minimum length Brauer chains : 5
Brauer example : (1 2 3 4 7)
Number of minimum length non-Brauer chains : 0

N = 14
Minimum length of chains : L(14) = 5
Number of minimum length Brauer chains : 14
Brauer example : (1 2 3 4 7 14)
Number of minimum length non-Brauer chains : 0

N = 21
Minimum length of chains : L(21) = 6
Number of minimum length Brauer chains : 26
Brauer example : (1 2 3 4 7 14 21)
Number of minimum length non-Brauer chains : 3
Non-Brauer example : [1 2 4 5 8 13 21]

N = 29
Minimum length of chains : L(29) = 7
Number of minimum length Brauer chains : 114
Brauer example : (1 2 3 4 7 11 18 29)
Number of minimum length non-Brauer chains : 18
Non-Brauer example : [1 2 3 6 9 11 18 29]

N = 32
Minimum length of chains : L(32) = 5
Number of minimum length Brauer chains : 1
Brauer example : (1 2 4 8 16 32)
Number of minimum length non-Brauer chains : 0

N = 42
Minimum length of chains : L(42) = 7
Number of minimum length Brauer chains : 78
Brauer example : (1 2 3 4 7 14 21 42)
Number of minimum length non-Brauer chains : 6
Non-Brauer example : [1 2 4 5 8 13 21 42]

N = 64
Minimum length of chains : L(64) = 6
Number of minimum length Brauer chains : 1
Brauer example : (1 2 4 8 16 32 64)
Number of minimum length non-Brauer chains : 0
```


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

In cases of special objects (such as with matrices) the operation of multiplication can be excessively expensive. In these cases the operation of multiplication should be avoided or reduced to a minimum.

In mathematics and computer science, optimal **addition-chain exponentiation** is a method of exponentiation by positive integer powers that requires a minimal number of multiplications. It works by creating a shortest addition chain that generates the desired exponent. Each exponentiation in the chain can be evaluated by multiplying two of the earlier exponentiation results. More generally, *addition-chain exponentiation* may also refer to exponentiation by non-minimal addition chains constructed by a variety of algorithms (since a shortest addition chain is very difficult to find).

The shortest addition-chain algorithm requires no more multiplications than binary exponentiation and usually less. The first example of where it does better is for

a

15
{\displaystyle {\displaystyle a^{15}}}
, where the binary method needs six multiplies but a shortest addition chain requires only five:

:   a

    15
    =
    a
    ×
    (
    a
    ×
    [
    a
    ×

    a

    2

    ]

    2

    )

    2

    {\displaystyle {\displaystyle a^{15}=a\times (a\times [a\times a^{2}]^{2})^{2}\!}}
     (binary, 6 multiplications)
:   a

    15
    =

    a

    3
    ×
    (
    [

    a

    3

    ]

    2

    )

    2

    {\displaystyle {\displaystyle a^{15}=a^{3}\times ([a^{3}]^{2})^{2}\!}}
     (shortest addition chain, 5 multiplications)

On the other hand, the addition-chain method is much more complicated, since the determination of a shortest addition chain seems quite difficult: no efficient optimal methods are currently known for arbitrary exponents, and the related problem of finding a shortest addition chain for a given set of exponents has been proven NP-complete.

Table demonstrating how to do *Exponentiation* using *Addition Chains*

| Number of Multiplications | Actual Exponentiation | Specific implementation of *Addition Chains* to do Exponentiation |
| --- | --- | --- |
| 0 | a1 | a |
| 1 | a2 | a × a |
| 2 | a3 | a × a × a |
| 2 | a4 | (a × a→b) × b |
| 3 | a5 | (a × a→b) × b × a |
| 3 | a6 | (a × a→b) × b × b |
| 4 | a7 | (a × a→b) × b × b × a |
| 3 | a8 | ((a × a→b) × b→d) × d |
| 4 | a9 | (a × a × a→c) × c × c |
| 4 | a10 | ((a × a→b) × b→d) × d × b |
| 5 | a11 | ((a × a→b) × b→d) × d × b × a |
| 4 | a12 | ((a × a→b) × b→d) × d × d |
| 5 | a13 | ((a × a→b) × b→d) × d × d × a |
| 5 | a14 | ((a × a→b) × b→d) × d × d × b |
| 5 | a15 | ((a × a→b) × b × a→e) × e × e |
| 4 | a16 | (((a × a→b) × b→d) × d→h) × h |

The number of multiplications required follows this sequence:
0, 1, 2, 2, 3, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 4, 5, 5, 6, 5,
6, 6, 6, 5, 6, 6, 6, 6, 7, 6, 7, 5, 6, 6, 7, 6, 7, 7, 7, 6,
7, 7, 7, 7, 7, 7, 8, 6, 7, 7, 7, 7, 8, 7, 8, 7, 8, 8, 8, 7,
8, 8, 8, 6, 7, 7, 8, 7, 8, 8, 9, 7, 8, 8, 8, 8, 8, 8, 9, 7,
8, 8, 8, 8, 8, 8, 9, 8, 9, 8, 9, 8, 9, 9, 9, 7, 8, 8, 8, 8...

This sequence can be found at: http://oeis.org/A003313

**Task requirements:**

Using the following values:

A
=

[

1
2

0

1
2

0

0

0

0

1
2

0

1
2

0

0

0

1
2

0

−

1
2

0

0

−

1
2

0

1
2

0

0

0

0

0

0

0

0

1

0

0

0

0

1

0

]
{\displaystyle {\displaystyle A={\begin{bmatrix}{\sqrt {\frac {1}{2}}}&0&{\sqrt {\frac {1}{2}}}&0&0&0&\\0&{\sqrt {\frac {1}{2}}}&0&{\sqrt {\frac {1}{2}}}&0&0&\\0&{\sqrt {\frac {1}{2}}}&0&-{\sqrt {\frac {1}{2}}}&0&0&\\-{\sqrt {\frac {1}{2}}}&0&{\sqrt {\frac {1}{2}}}&0&0&0&\\0&0&0&0&0&1&\\0&0&0&0&1&0&\\\end{bmatrix}}}}

m
=
31415
{\displaystyle {\displaystyle m=31415}}
 and

n
=
27182
{\displaystyle {\displaystyle n=27182}}

Repeat task Matrix-exponentiation operator, except use **addition-chain exponentiation** to better calculate:

:   A

    m
    {\displaystyle {\displaystyle A^{m}}}
    ,

    A

    n
    {\displaystyle {\displaystyle A^{n}}}
     and

    A

    n
    ×
    m
    {\displaystyle {\displaystyle A^{n\times m}}}
    .

As an easier alternative to doing the matrix manipulation above, generate the *addition-chains* for 12509, 31415 and 27182 and use *addition-chain exponentiation* to calculate these two equations:

* 1.0000220644541631415
* 1.0000255005525127182

Also: Display a count of how many multiplications were done in each case.

Note: There are two ways to approach this task:

* Brute force - try every permutation possible and pick one with the least number of multiplications. If the brute force is a simpler algorithm, then present it as a subtask under the subtitle "Brute force", eg ===Brute Force===.
* Some clever algorithm - the wikipedia page has some hints, subtitle the code with the name of algorithm.

Note: Binary exponentiation does not usually produce the best solution. Provide only optimal solutions.

Kudos (κῦδος) for providing a routine that generate sequence A003313 in the output.

Also, see the Rosetta Code task:   [http://rosettacode.org/wiki/Knuth%27s\_power\_tree
Knuth's power tree].

[Assistant]
**Translation of**: Python

```
# 20230327 Raku programming solution

use Math::Matrix;

class AdditionChains { has ( $.idx, $.pos, @.chains, @.lvl, %.pat ) is rw;

   method add_chain {
      # method 1: add chains depth then breadth first until done
      return gather given self {
         take my $newchain = .chains[.idx].clone.append:
            .chains[.idx][*-1] + .chains[.idx][.pos];
	     .chains.append: $newchain;
         .pos == +.chains[.idx]-1 ?? ( .idx += 1 && .pos = 0 ) !! .pos += 1;
      }
   }

   method find_chain(\nexp where nexp > 0) {
   # method 1 interface: search for chain ending with n, adding more as needed
      return ([1],) if nexp == 1;
      my @chn = self.chains.grep: *.[*-1] == nexp // [];
      unless @chn.Bool {
         repeat { @chn = self.add_chain } until @chn[*-1][*-1] == nexp
      }
      return @chn
   }

   method knuth_path(\ngoal) {
      # method 2: knuth method, uses memoization to search for a shorter chain
      return [] if ngoal < 1;
      until self.pat{ngoal}:exists {
         self.lvl[0] = [ gather for self.lvl[0].Array -> \i {
            for self.knuth_path(i).Array -> \j {
               unless self.pat{i + j}:exists {
                  self.pat{i + j} = i and take i + j
               }
            }
         } ]
      }
      return self.knuth_path(self.pat{ngoal}).append: ngoal
   }

   multi method cpow(\xbase, \chain) {
#  raise xbase by an addition exponentiation chain for what becomes x**chain[-1]
      my ($pows, %products) = 0, 1 => xbase;

      %products{0} = xbase ~~ Math::Matrix
         ?? Math::Matrix.new([ [ 1 xx xbase.size[1] ] xx xbase.size[0] ]) !! 1;

      for chain.Array -> \i {
         %products{i} = %products{$pows} * %products{i - $pows};
         $pows = i
      }
      return %products{ chain[*-1] }
   }
}

my $chn =  AdditionChains.new( idx    =>      0, pos =>      0,
                               chains => ([1],), lvl => ([1],), pat => {1=>0} );

say 'First one hundred addition chain lengths:';
.Str.say for ( (1..100).map: { +$chn.find_chain($_)[0] - 1 } ).rotor: 10;

my %chns = (31415, 27182).map: { $_ => $chn.knuth_path: $_ };

say "\nKnuth chains for addition chains of 31415 and 27182:";
say "Exponent: $_\n  Addition Chain: %chns{$_}[0..*-2]" for %chns.keys;
say '1.00002206445416^31415 = ', $chn.cpow(1.00002206445416, %chns{31415});
say '1.00002550055251^27182 = ', $chn.cpow(1.00002550055251, %chns{27182});
say '(1.000025 + 0.000058i)^27182 = ', $chn.cpow: 1.000025+0.000058i, %chns{27182};
say '(1.000022 + 0.000050i)^31415 = ', $chn.cpow: 1.000022+0.000050i, %chns{31415};

my \sq05 = 0.5.sqrt;
my \mat  = Math::Matrix.new( [[sq05,    0, sq05,     0, 0, 0],
                             [    0, sq05,    0,  sq05, 0, 0],
                             [    0, sq05,    0, -sq05, 0, 0],
                             [-sq05,    0, sq05,     0, 0, 0],
                             [    0,    0,    0,     0, 0, 1],
                             [    0,    0,    0,     0, 1, 0]] );

say 'matrix A ^ 27182 =';
say my $res27182 = $chn.cpow(mat, %chns{27182});
say 'matrix A ^ 31415 =';
say $chn.cpow(mat, %chns{31415});
say '(matrix A ** 27182) ** 31415 =';
say $chn.cpow($res27182, %chns{31415});

```

Output:

```
First one hundred addition chain lengths:
0 1 2 2 3 3 4 3 4 4
5 4 5 5 5 4 5 5 6 5
6 6 6 5 6 6 6 6 7 6
7 5 6 6 7 6 7 7 7 6
7 7 7 7 7 7 8 6 7 7
7 7 8 7 8 7 8 8 8 7
8 8 8 6 7 7 8 7 8 8
9 7 8 8 8 8 8 8 9 7
8 8 8 8 8 8 9 8 9 8
9 8 9 9 9 7 8 8 8 8

Knuth chains for addition chains of 31415 and 27182:
Exponent: 27182
  Addition Chain: 1 2 3 5 7 14 21 35 70 140 143 283 566 849 1698 3396 6792 6799 13591
Exponent: 31415
  Addition Chain: 1 2 3 5 7 14 28 56 61 122 244 488 976 1952 3904 7808 15616 15677 31293
1.00002206445416^31415 = 1.9999999998924638
1.00002550055251^27182 = 1.999999999974053
(1.000025 + 0.000058i)^27182 = -0.01128636963542673+1.9730308496660347i
(1.000022 + 0.000050i)^31415 = 0.00016144681325535107+1.9960329014194498i
matrix A ^ 27182 =
  0  0  0  0  0  0
  0  0  0  0  0  0
  0  0  0  0  0  0
  0  0  0  0  0  0
  0  0  0  0  0  1
  0  0  0  0  1  0
matrix A ^ 31415 =
   0  0  0   0  0  0
   0  0  0   0  0  0
   0  0  0  -0  0  0
  -0  0  0   0  0  0
   0  0  0   0  0  1
   0  0  0   0  1  0
(matrix A ** 27182) ** 31415 =
  0  0  0  0  0  0
  0  0  0  0  0  0
  0  0  0  0  0  0
  0  0  0  0  0  0
  0  0  0  0  0  1
  0  0  0  0  1  0
```


[User]
Definitions

In mathematics, **additive primes** are prime numbers for which the sum of their decimal digits are also primes.

Task

Write a program to determine (and show here) all **additive primes** less than **500**.

Optionally, show the **number** of additive primes.

Also see
:   * the OEIS entry:   A046704 additive primes.
    * the prime-numbers entry:   additive primes.
    * the geeks for geeks entry: additive prime number.
    * the prime-numbers fandom: additive primes.

[Assistant]
```
unit sub MAIN ($limit = 500);
say "{+$_} additive primes < $limit:\n{$_».fmt("%" ~ $limit.chars ~ "d").batch(10).join("\n")}",
    with ^$limit .grep: { .is-prime && .comb.sum.is-prime }

```

Output:

```
54 additive primes < 500:
  2   3   5   7  11  23  29  41  43  47
 61  67  83  89 101 113 131 137 139 151
157 173 179 191 193 197 199 223 227 229
241 263 269 281 283 311 313 317 331 337
353 359 373 379 397 401 409 421 443 449
461 463 467 487
```


[User]
Task

Demonstrate how to get the address of a variable and how to set the address of a variable.

[Assistant]
(formerly Perl 6)

```
my $x;
say $x.WHERE;

my $y := $x;   # alias
say $y.WHERE;  # same address as $x

say "Same variable" if $y =:= $x;
$x = 42;
say $y;  # 42

```

Output:

```
7857931379550584425
```

How you set the address of a variable (or any other object) is outside the purview of Raku, but the language supports pluggable object representations, and any given representation scheme could conceivably allow an existing address to be treated as an object candidate where that makes sense. Memory-mapped structs are not unreasonable and are likely to be supported on VMs that allow it.


[User]
Description

The ADFGVX cipher was a manually applied field cipher used by the German Army during World War I. It was broken in 1918 by the French cryptanalyst Georges Painvin.

The workings of the cipher are described in the Wikipedia article, linked to above, and so will not be repeated here.

Task

Write routines, functions etc. in your language to:

1. Encrypt *suitable* plaintext and decrypt the resulting cipher text using the ADFGVX cipher algorithm given a Polybius square (see 2. below) and a *suitable* key. For this purpose *suitable* means text consisting solely of ASCII upper case letters or digits.

2. Create a 6 x 6 Polybius square using a random combination of the letters A to Z and the digits 0 to 9 and then display it.

3. Given the number of letters (between 7 and 12 say) to use, create a key by selecting a *suitable* word at random from unixdict.txt and then display it. The word selected should be such that none of its characters are repeated.

Use these routines to create a Polybius square and a 9 letter key.

These should then be used to encrypt the plaintext: **ATTACKAT1200AM** and decrypt the resulting cipher text. Display here the results of both operations.

Note

As it's unclear from the Wikipedia article how to handle a final row with fewer elements than the number of characters in the key, either of the methods mentioned in Columnar transposition may be used. In the case of the second method, it is also acceptable to fill any gaps after shuffling by moving elements to the left which makes decipherment harder.

[Assistant]
Slightly different results from every other entry so far. See discussion page for reasons. It is impossible to tell from casual observation which column comes first in the Raku example. In every other (so far), the sub group with 4 characters is the first column.

```
srand 123456; # For repeatability

my @header   = < A D F G V X >;
my $polybius = (flat 'A'..'Z', 0..9).pick(*).join;

my $key-length = 9;
my $key = uc 'unixdict.txt'.IO.words.grep( { (.chars == $key-length) && (+.comb.Set == +.comb) } ).roll;

my %cypher   = (@header X~ @header) Z=> $polybius.comb;

my $message = 'Attack at 1200AM';

use Terminal::Boxer;
say "Key: $key\n";
say "Polybius square:\n", ss-box :7col, :3cw, :indent("\t"), '', |@header, |(@header Z $polybius.comb.batch: 6);
say "Message to encode: $message";
say "\nEncoded: " ~ my $encoded = encode $message;
say "\nDecoded: " ~ decode $encoded;

sub encode ($text is copy) {
    $text = $text.uc.comb(/<[A..Z 0..9]>/).join;
    my @order = $key.comb.pairs.sort( *.value )».key;
    my @encode = %cypher.invert.hash{ $text.comb }.join.comb.batch($key-length).map: { [$_] };
    ((^$key-length).map: { @encode».[@order]».grep( *.defined )».[$_].grep( *.defined ).join }).Str;
}

sub decode ($text is copy) {
    my @text = $text.split(' ')».comb;
    my $chars = @text[0].chars;
    $_ = flat |$_, ' ' if .chars < $chars for @text;
    my @order = $key.comb.pairs.sort( *.value )».key.pairs.sort( *.value )».key;
    %cypher{ ( grep { /\w/ }, flat [Z] @order.map( { |@text.batch($key-length)».[$_] } ) ).batch(2)».join }.join;
}

```

Output:

```
Key: GHOSTLIKE

Polybius square:
	┌───┬───┬───┬───┬───┬───┬───┐
	│   │ A │ D │ F │ G │ V │ X │
	├───┼───┼───┼───┼───┼───┼───┤
	│ A │ H │ O │ S │ 5 │ 7 │ Q │
	├───┼───┼───┼───┼───┼───┼───┤
	│ D │ 0 │ I │ 6 │ J │ C │ V │
	├───┼───┼───┼───┼───┼───┼───┤
	│ F │ 4 │ 8 │ R │ X │ G │ A │
	├───┼───┼───┼───┼───┼───┼───┤
	│ G │ Y │ F │ P │ B │ Z │ 3 │
	├───┼───┼───┼───┼───┼───┼───┤
	│ V │ M │ W │ 9 │ D │ 1 │ N │
	├───┼───┼───┼───┼───┼───┼───┤
	│ X │ 2 │ E │ U │ T │ L │ K │
	└───┴───┴───┴───┴───┴───┴───┘

Message to encode: Attack at 1200AM

Encoded: DVVA FVX XXA FGF XVX GXA XXD GFA XXD

```


[User]
In astronomy **air mass** is a measure of the amount of atmosphere between the observer and the object being observed. It is a function of the *zenith angle* (the angle between the line of sight an vertical) and the altitude of the observer. It is defined as the integral of the atmospheric density along the line of sight and is usually expressed relative to the air mass at zenith. Thus, looking straight up gives an air mass of one (regardless of observer's altitude) and viewing at any zenith angle greater than zero gives higher values.

You will need to integrate

ρ
{\displaystyle {\displaystyle \rho }}
(h(a,z,x)) where

ρ
{\displaystyle {\displaystyle \rho }}
(h) is the atmospheric density for a given height above sea level, and h(a,z,x) is the height above sea level for a point at distance x along the line of sight. Determining this last function requires some trigonometry.

For this task you can assume:

:   * The density of Earth's atmosphere is proportional to exp(-a/8500 metres)
    * The Earth is a perfect sphere of radius 6371 km.

Task
:   * Write a function that calculates the air mass for an observer at a given altitude    ***a***    above sea level and zenith angle    ***z.***
    * Show the air mass for zenith angles **0** to **90** in steps of **5** degrees for an observer at sea level.
    * Do the same for the   NASA SOFIA infrared telescope,   which has a cruising altitude of 13,700 meters   (about 8.3 miles),

    :   it flies in a specially retrofitted Boeing 747 about four flights a week.

[Assistant]
**Translation of**: FreeBASIC

```
constant DEG = pi/180;    # degrees to radians
constant RE  = 6371000;   # Earth radius in meters
constant dd  = 0.001;     # integrate in this fraction of the distance already covered
constant FIN = 10000000;  # integrate only to a height of 10000km, effectively infinity

#| Density of air as a function of height above sea level
sub rho ( \a ) { exp( -a / 8500 ) }

sub height ( \a, \z, \d ) {
    # a = altitude of observer
    # z = zenith angle (in degrees)
    # d = distance along line of sight
    my \AA = RE + a;
    sqrt( AA² + d² - 2*d*AA*cos((180-z)*DEG) ) - AA;
}

#| Integrates density along the line of sight
sub column_density ( \a, \z ) {
    my $sum = 0;
    my $d   = 0;
    while $d < FIN {
        my \delta = max(dd, (dd)*$d);  # Adaptive step size to avoid it taking forever
        $sum += rho(height(a, z, $d + delta/2))*delta;
        $d   += delta;
    }
    $sum;
}

sub airmass ( \a, \z ) {
    column_density( a, z ) /
    column_density( a, 0 )
}

say 'Angle     0 m              13700 m';
say '------------------------------------';
say join "\n", (0, 5 ... 90).hyper(:3batch).map: -> \z {
    sprintf "%2d      %11.8f      %11.8f", z, airmass(    0, z), airmass(13700, z);
}

```

Output:

```
Angle     0 m              13700 m
------------------------------------
 0       1.00000000       1.00000000
 5       1.00380963       1.00380965
10       1.01538466       1.01538475
15       1.03517744       1.03517765
20       1.06399053       1.06399093
25       1.10305937       1.10306005
30       1.15418974       1.15419083
35       1.21998076       1.21998246
40       1.30418931       1.30419190
45       1.41234169       1.41234567
50       1.55280404       1.55281025
55       1.73875921       1.73876915
60       1.99212000       1.99213665
65       2.35199740       2.35202722
70       2.89531368       2.89537287
75       3.79582352       3.79596149
80       5.53885809       5.53928113
85      10.07896219      10.08115981
90      34.32981136      34.36666557
```


[User]
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.

The theorem on which the test is based can be stated as follows:

* a number

  p
  {\displaystyle {\displaystyle p}}
     is prime   if and only if   all the coefficients of the polynomial expansion of

:   :   :   (
            x
            −
            1

            )

            p
            −
            (

            x

            p
            −
            1
            )
            {\displaystyle {\displaystyle (x-1)^{p}-(x^{p}-1)}}

are divisible by

p
{\displaystyle {\displaystyle p}}
.

Example

Using

p
=
3
{\displaystyle {\displaystyle p=3}}
:

```
         (x-1)^3 - (x^3 - 1)
            = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
            = -3x^2 + 3x

```

And all the coefficients are divisible by **3**,   so **3** is prime.

|  |
| --- |
| **Note:** This task is **not** the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. |

Task

1. Create a function/subroutine/method that given

   p
   {\displaystyle {\displaystyle p}}
      generates the coefficients of the expanded polynomial representation of

   (
   x
   −
   1

   )

   p
   {\displaystyle {\displaystyle (x-1)^{p}}}
   .
2. Use the function to show here the polynomial expansions of

   (
   x
   −
   1

   )

   p
   {\displaystyle {\displaystyle (x-1)^{p}}}
      for

   p
   {\displaystyle {\displaystyle p}}
      in the range   **0**   to at least   **7**,   inclusive.
3. Use the previous function in creating another function that when given

   p
   {\displaystyle {\displaystyle p}}
      returns whether

   p
   {\displaystyle {\displaystyle p}}
      is prime using the theorem.
4. Use your test to generate a list of all primes *under*   **35**.
5. **As a stretch goal**,   generate all primes under   **50**   (needs integers larger than 31-bit).

References

* Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
* Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015-12

The expansions are generated similarly to how most FP languages generate sequences that resemble Pascal's triangle, using a zipwith meta-operator (Z) with subtraction, applied between two lists that add a 0 on either end to the prior list. Here we define a constant infinite sequence using the ... sequence operator with a "whatever" endpoint. In fact, the second term [1,-1] could have been generated from the first term, but we put it in there for documentation so the reader can see what direction things are going.

The polyprime function pretty much reads like the original description. Is it "so" that the p'th expansion's coefficients are all divisible by p? The .[1 ..^ \*/2] slice is done simply to weed out divisions by 1 or by factors we've already tested (since the coefficients are symmetrical in terms of divisibility). If we wanted to write polyprime even more idiomatically, we could have made it another infinite constant list that is just a mapping of the first list, but we decided that would just be showing off. :-)

```
constant expansions = [1], [1,-1], -> @prior { [|@prior,0 Z- 0,|@prior] } ... *;

sub polyprime($p where 2..*) { so expansions[$p].[1 ..^ */2].all %% $p }

# Showing the expansions:

say ' p: (x-1)ᵖ';
say '-----------';

sub super ($n) {
    $n.trans: '0123456789'
           => '⁰¹²³⁴⁵⁶⁷⁸⁹';
}

for ^13 -> $d {
    say $d.fmt('%2i: '), (
        expansions[$d].kv.map: -> $i, $n {
            my $p = $d - $i;
            [~] gather {
                take < + - >[$n < 0] ~ ' ' unless $p == $d;
                take $n.abs                unless $p == $d > 0;
                take 'x'                   if $p > 0;
                take super $p - $i         if $p > 1;
            }
        }
    )
}

#  And testing the function:

print "\nPrimes up to 100:\n  { grep &polyprime, 2..100 }\n";

```

Output:

```
 p: (x-1)ᵖ
-----------
 0: 1
 1: x - 1
 2: x² - 2x + 1
 3: x³ - 3x² + 3x - 1
 4: x⁴ - 4x³ + 6x² - 4x + 1
 5: x⁵ - 5x⁴ + 10x³ - 10x² + 5x - 1
 6: x⁶ - 6x⁵ + 15x⁴ - 20x³ + 15x² - 6x + 1
 7: x⁷ - 7x⁶ + 21x⁵ - 35x⁴ + 35x³ - 21x² + 7x - 1
 8: x⁸ - 8x⁷ + 28x⁶ - 56x⁵ + 70x⁴ - 56x³ + 28x² - 8x + 1
 9: x⁹ - 9x⁸ + 36x⁷ - 84x⁶ + 126x⁵ - 126x⁴ + 84x³ - 36x² + 9x - 1
10: x¹⁰ - 10x⁹ + 45x⁸ - 120x⁷ + 210x⁶ - 252x⁵ + 210x⁴ - 120x³ + 45x² - 10x + 1
11: x¹¹ - 11x¹⁰ + 55x⁹ - 165x⁸ + 330x⁷ - 462x⁶ + 462x⁵ - 330x⁴ + 165x³ - 55x² + 11x - 1
12: x¹² - 12x¹¹ + 66x¹⁰ - 220x⁹ + 495x⁸ - 792x⁷ + 924x⁶ - 792x⁵ + 495x⁴ - 220x³ + 66x² - 12x + 1

Primes up to 100:
  2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
```


[User]
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.

Task

As an example, implement insertion in a red-black-tree.

A red-black-tree is a binary tree where each internal node has a color attribute *red* or *black*. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion.

Reference

Red-Black Trees in a Functional Setting

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.11

Raku doesn't have algebraic data types (yet), but it does have pretty good pattern matching in multi signatures.

```
enum RedBlack <R B>;

multi balance(B,[R,[R,$a,$x,$b],$y,$c],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }
multi balance(B,[R,$a,$x,[R,$b,$y,$c]],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }
multi balance(B,$a,$x,[R,[R,$b,$y,$c],$z,$d]) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }
multi balance(B,$a,$x,[R,$b,$y,[R,$c,$z,$d]]) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }

multi balance($col, $a, $x, $b) { [$col, $a, $x, $b] }

multi ins( $x, @s [$col, $a, $y, $b] ) {
    when $x before $y     { balance $col, ins($x, $a), $y, $b }
    when $x after $y      { balance $col, $a, $y, ins($x, $b) }
    default               { @s }
}
multi ins( $x, Any:U ) { [R, Any, $x, Any] }

multi insert( $x, $s ) {
    [B, |ins($x,$s)[1..3]];
}

sub MAIN {
    my $t = Any;
    $t = insert($_, $t) for (1..10).pick(*);
    say $t.gist;
}

```

This code uses generic comparison operators before and after, so it should work on any ordered type.

Output:

```
[B [B [B (Any) 1 [R (Any) 2 (Any)]] 3 [B (Any) 4 [R (Any) 5 (Any)]]] 6 [B [B (Any) 7 (Any)] 8 [B [R (Any) 9 (Any)] 10 (Any)]]]
```


[User]
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.

Use the following text to test your programs:

```
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
```

Note that:

1. The example input texts lines may, or may not, have trailing dollar characters.
2. All columns should share the same alignment.
3. Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
4. Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
5. The minimum space between columns should be computed from the text and not hard-coded.
6. It is *not* a requirement to add separating characters between or around columns.

Other tasks related to string operations:

Metrics

* Array length
* String length
* Copy a string
* Empty string  (assignment)

Counting

* Word frequency
* Letter frequency
* Jewels and stones
* I before E except after C
* Bioinformatics/base count
* Count occurrences of a substring
* Count how many vowels and consonants occur in a string

Remove/replace

* XXXX redacted
* Conjugate a Latin verb
* Remove vowels from a string
* String interpolation (included)
* Strip block comments
* Strip comments from a string
* Strip a set of characters from a string
* Strip whitespace from a string -- top and tail
* Strip control codes and extended characters from a string

Anagrams/Derangements/shuffling

* Word wheel
* ABC problem
* Sattolo cycle
* Knuth shuffle
* Ordered words
* Superpermutation minimisation
* Textonyms (using a phone text pad)
* Anagrams
* Anagrams/Deranged anagrams
* Permutations/Derangements

Find/Search/Determine

* ABC words
* Odd words
* Word ladder
* Semordnilap
* Word search
* Wordiff  (game)
* String matching
* Tea cup rim text
* Alternade words
* Changeable words
* State name puzzle
* String comparison
* Unique characters
* Unique characters in each string
* Extract file extension
* Levenshtein distance
* Palindrome detection
* Common list elements
* Longest common suffix
* Longest common prefix
* Compare a list of strings
* Longest common substring
* Find common directory path
* Words from neighbour ones
* Change e letters to i in words
* Non-continuous subsequences
* Longest common subsequence
* Longest palindromic substrings
* Longest increasing subsequence
* Words containing "the" substring
* Sum of the digits of n is substring of n
* Determine if a string is numeric
* Determine if a string is collapsible
* Determine if a string is squeezable
* Determine if a string has all unique characters
* Determine if a string has all the same characters
* Longest substrings without repeating characters
* Find words which contains all the vowels
* Find words which contain the most consonants
* Find words which contains more than 3 vowels
* Find words whose first and last three letters are equal
* Find words with alternating vowels and consonants

Formatting

* Substring
* Rep-string
* Word wrap
* String case
* Align columns
* Literals/String
* Repeat a string
* Brace expansion
* Brace expansion using ranges
* Reverse a string
* Phrase reversals
* Comma quibbling
* Special characters
* String concatenation
* Substring/Top and tail
* Commatizing numbers
* Reverse words in a string
* Suffixation of decimal numbers
* Long literals, with continuations
* Numerical and alphabetical suffixes
* Abbreviations, easy
* Abbreviations, simple
* Abbreviations, automatic

Song lyrics/poems/Mad Libs/phrases

* Mad Libs
* Magic 8-ball
* 99 bottles of beer
* The Name Game (a song)
* The Old lady swallowed a fly
* The Twelve Days of Christmas

Tokenize

* Text between
* Tokenize a string
* Word break problem
* Tokenize a string with escaping
* Split a character string based on change of character

Sequences

* Show ASCII table
* De Bruijn sequences
* Summarize and say sequence
* Generate lower case ASCII alphabet

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

Call with parameter left (default), center or right.

```
my @lines =
q|Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
|.lines;

my @widths;

for @lines { for .split('$').kv { @widths[$^key] max= $^word.chars; } }
for @lines { say |.split('$').kv.map: { (align @widths[$^key], $^word) ~ " "; } }

sub align($column_width, $word, $aligment = @*ARGS[0]) {
        my $lr = $column_width - $word.chars;
        my $c  = $lr / 2;
        given ($aligment) {
                when "center" { " " x $c.ceiling ~ $word ~ " " x $c.floor }
                when "right"  { " " x $lr        ~ $word                  }
                default       {                    $word ~ " " x $lr      }
        }
}

```

Or a more functional version, called like `./align.p6 left input.txt`, which however only supports left and right alignment (not center):

```
sub MAIN ($alignment where 'left'|'right', $file) {
    my @lines := $file.IO.lines.map(*.split('$').cache).cache;
    my @widths = roundrobin(|@lines).map(*».chars.max);
    my $align  = {left=>'-', right=>''}{$alignment};
    my $format = @widths.map( '%' ~ ++$ ~ '$' ~ $align ~ * ~ 's' ).join(' ') ~ "\n";
    printf $format, |$_ for @lines;
}

```


[User]
An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.

:   * If the terms eventually reach 0 then the series for K is said to **terminate**.

:   There are several classifications for non termination:

    * If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called **perfect**.
    * If the third term *would* be repeating K then the sequence repeats with period 2 and K is called **amicable**.
    * If the Nth term *would* be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called **sociable**.
:   Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...

    * Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence `95, 25, 6, 6, 6, ...` such K are called **aspiring**.
    * K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence `562, 284, 220, 284, 220, ...` such K are called **cyclic**.

:   And finally:

    * Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called **non-terminating**.
      For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating **16** terms or if any term of the sequence is greater than 2\*\*47 = 140,737,488,355,328.

Task

1. Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
2. Use it to display the classification and sequences of the numbers one to ten inclusive.
3. Use it to show the classification and sequences of the following integers, in order:

:   :   11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.

Show all output on this page.

Related tasks

* Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
* Proper divisors
* Amicable pairs

External links

* An amazing thing about 276, Numberphile

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.10

```
sub propdivsum (\x) {
    my @l = x > 1;
    (2 .. x.sqrt.floor).map: -> \d {
        unless x % d { my \y = x div d; y == d ?? @l.push: d !! @l.append: d,y }
    }
    sum @l;
}

multi quality (0,1)  { 'perfect ' }
multi quality (0,2)  { 'amicable' }
multi quality (0,$n) { "sociable-$n" }
multi quality ($,1)  { 'aspiring' }
multi quality ($,$n) { "cyclic-$n" }

sub aliquotidian ($x) {
    my %seen;
    my @seq = $x, &propdivsum ... *;
    for 0..16 -> $to {
        my $this = @seq[$to] or return "$x\tterminating\t[@seq[^$to]]";
        last if $this > 140737488355328;
        if %seen{$this}:exists {
            my $from = %seen{$this};
            return "$x\t&quality($from, $to-$from)\t[@seq[^$to]]";
        }
        %seen{$this} = $to;
    }
    "$x non-terminating\t[{@seq}]";
}

aliquotidian($_).say for flat
    1..10,
    11, 12, 28, 496, 220, 1184, 12496, 1264460,
    790, 909, 562, 1064, 1488,
    15355717786080;

```

Output:

```
1	terminating	[1]
2	terminating	[2 1]
3	terminating	[3 1]
4	terminating	[4 3 1]
5	terminating	[5 1]
6	perfect 	[6]
7	terminating	[7 1]
8	terminating	[8 7 1]
9	terminating	[9 4 3 1]
10	terminating	[10 8 7 1]
11	terminating	[11 1]
12	terminating	[12 16 15 9 4 3 1]
28	perfect 	[28]
496	perfect 	[496]
220	amicable	[220 284]
1184	amicable	[1184 1210]
12496	sociable-5	[12496 14288 15472 14536 14264]
1264460	sociable-4	[1264460 1547860 1727636 1305184]
790	aspiring	[790 650 652 496]
909	aspiring	[909 417 143 25 6]
562	cyclic-2	[562 284 220]
1064	cyclic-2	[1064 1336 1184 1210]
1488 non-terminating	[1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608 ...]
15355717786080 non-terminating	[15355717786080 44534663601120 144940087464480 ...]

```


[User]
The Almkvist-Giullera formula for calculating

1

π

2
{\displaystyle {\displaystyle {\frac {1}{\pi ^{2}}}}}
 is based on the Calabi-Yau
differential equations of order 4 and 5,   which were originally used to describe certain manifolds
in string theory.

The formula is:

:   1

    π

    2
    =
    32

    ∑

    n
    =
    0

    ∞

    (
    6
    n
    )
    !

    3
    ⋅
    n

    !

    6
    (
    532

    n

    2
    +
    126
    n
    +
    9
    )

    1

    10

    6
    n
    +
    3
    {\displaystyle {\displaystyle {\frac {1}{\pi ^{2}}}=32\sum \_{n=0}^{\infty }{\frac {(6n)!}{3\cdot n!^{6}}}(532n^{2}+126n+9){\frac {1}{10^{6n+3}}}}}

This formula can be used to calculate the constant

1

π

2
{\displaystyle {\displaystyle {\frac {1}{\pi ^{2}}}}}
,   and thus to calculate

π
{\displaystyle {\displaystyle \pi }}
.

Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:

:   32
    (
    6
    n
    )
    !

    3
    ⋅
    n

    !

    6
    (
    532

    n

    2
    +
    126
    n
    +
    9
    )
    {\displaystyle {\displaystyle {\frac {32(6n)!}{3\cdot n!^{6}}}(532n^{2}+126n+9)}}

multiplied by a negative integer power of 10:

:   10

    −
    (
    6
    n
    +
    3
    )
    {\displaystyle {\displaystyle 10^{-(6n+3)}}}

Task
:   * Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
    * Use the complete formula to calculate and print

      π
      {\displaystyle {\displaystyle \pi }}
       to 70 decimal digits of precision.

Reference
:   * Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.

[Assistant]
```
# 20201013 Raku programming solution

use BigRoot;
use Rat::Precise;
use experimental :cached;

BigRoot.precision = 75 ;
my $Precision     = 70 ;
my $AGcache       =  0 ;

sub postfix:<!>(Int $n --> Int) is cached { [*] 1 .. $n }

sub Integral(Int $n --> Int) is cached {
   (2⁵*(6*$n)! * (532*$n² + 126*$n + 9)) div (3*($n!)⁶)
}

sub A-G(Int $n --> FatRat) is cached { # Almkvist-Giullera
   Integral($n).FatRat / (10**(6*$n + 3)).FatRat
}

sub Pi(Int $n --> Str) {
   (1/(BigRoot.newton's-sqrt: $AGcache += A-G $n)).precise($Precision)
}

say "First 10 integer portions : ";
say $_, "\t", Integral $_ for ^10;

my $target = Pi my $Nth = 0;

loop { $target eq ( my $next = Pi ++$Nth ) ?? ( last ) !! $target = $next }

say "π to $Precision decimal places is :\n$target"

```

Output:

```
First 10 integer portions :
0       96
1       5122560
2       190722470400
3       7574824857600000
4       312546150372456000000
5       13207874703225491420651520
6       567273919793089083292259942400
7       24650600248172987140112763715584000
8       1080657854354639453670407474439566400000
9       47701779391594966287470570490839978880000000
π to 70 decimal places is :
3.1415926535897932384626433832795028841971693993751058209749445923078164
```


[User]
A   k-Almost-prime   is a natural number

n
{\displaystyle {\displaystyle n}}
   that is the product of

k
{\displaystyle {\displaystyle k}}
   (possibly identical) primes.

Example

1-almost-primes,   where

k
=
1
{\displaystyle {\displaystyle k=1}}
,   are the prime numbers themselves.

2-almost-primes,   where

k
=
2
{\displaystyle {\displaystyle k=2}}
,   are the   semiprimes.

Task

Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for

1
≤
K
≤
5
{\displaystyle {\displaystyle 1\leq K\leq 5}}
.

Related tasks

* Semiprime
* Category:Prime Numbers

[Assistant]
(formerly Perl 6)

**Translation of**: C

**Works with**: Rakudo version 2015.12

```
sub is-k-almost-prime($n is copy, $k) returns Bool {
    loop (my ($p, $f) = 2, 0; $f < $k && $p*$p <= $n; $p++) {
        $n /= $p, $f++ while $n %% $p;
    }
    $f + ($n > 1) == $k;
}

for 1 .. 5 -> $k {
    say ~.[^10]
        given grep { is-k-almost-prime($_, $k) }, 2 .. *
}

```

Output:

```
2 3 5 7 11 13 17 19 23 29
4 6 9 10 14 15 21 22 25 26
8 12 18 20 27 28 30 42 44 45
16 24 36 40 54 56 60 81 84 88
32 48 72 80 108 112 120 162 168 176
```

Here is a solution with identical output based on the factors routine from Count\_in\_factors#Raku (to be included manually until we decide where in the distribution to put it).

```
constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;

multi sub factors(1) { 1 }
multi sub factors(Int $remainder is copy) {
    gather for @primes -> $factor {
        # if remainder < factor², we're done
        if $factor * $factor > $remainder {
            take $remainder if $remainder > 1;
            last;
        }
        # How many times can we divide by this prime?
        while $remainder %% $factor {
            take $factor;
            last if ($remainder div= $factor) === 1;
        }
    }
}

constant @factory = lazy 0..* Z=> flat (0, 0, map { +factors($_) }, 2..*);

sub almost($n) { map *.key, grep *.value == $n, @factory }

put almost($_)[^10] for 1..5;

```


[User]
An alternade is a word whose alternating letters themselves form two words.

Example

The word **lounge** contains the word **lug** (**l**o**u**n**g**e) and the word **one** (l**o**u**n**g**e**).

For a word to be an alternade, all its letters must be used.

The two words that form an alternade don't need to be the same length; for example, the word **board** is an alternade made up of the words **bad** (**b**o**a**r**d**) and **or** (b**o**a**r**d).

Task

Print out every alternade in unixdict.txt whose length is **6** or greater, also showing both the words that make up the alternade.

See also
:   * Wikipedia entry:   Alternade

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]
```
unit sub MAIN ($file = 'unixdict.txt', :$min = 6);

my %words = $file.IO.slurp.words.map: * => 1;

my @alternades;

for %words {
    next if .key.chars < $min;
    my @letters = .key.comb;
    my @alts = @letters[0,2 … *].join, @letters[1,3 … *].join;
    @alternades.push(.key => @alts) if %words{@alts[0]} && %words{@alts[1]};
}

@alternades.=sort;

say "{+@alternades} alternades longer than {$min-1} characters found in $file:";

.say for @alternades > 10
  ?? (flat @alternades.head(5), '...', @alternades.tail(5))
  !! @alternades;

```

Output:

```
58 alternades longer than 5 characters found in unixdict.txt:
accost => [acs cot]
accuse => [acs cue]
afield => [ail fed]
agleam => [ala gem]
alcott => [act lot]
...
triode => [tid roe]
triune => [tin rue]
troupe => [top rue]
truant => [tun rat]
twirly => [til wry]
```