[User]
The   game of Pig   is a multiplayer game played with a single six-sided die.   The
object of the game is to reach   **100**   points or more.
Play is taken in turns.   On each person's turn that person has the option of either:

:   1. **Rolling the dice**:   where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again;   or a roll of   **1**   loses the player's total points   *for that turn*   and their turn finishes with play passing to the next player.
    2. **Holding**:   the player's score for that round is added to their total and becomes safe from the effects of throwing a   **1**   (one).   The player's turn finishes with play passing to the next player.

Task

Create a program to score for, and simulate dice throws for, a two-person game.

Related task

* Pig the dice game/Player

[Assistant]
(formerly Perl 6)

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

```
constant DIE = 1..6;

sub MAIN (Int :$players = 2, Int :$goal = 100) {
    my @safe = 0 xx $players;
    for |^$players xx * -> $player {
	say "\nOK, player #$player is up now.";
	my $safe = @safe[$player];
	my $ante = 0;
	until $safe + $ante >= $goal or
	    prompt("#$player, you have $safe + $ante = {$safe+$ante}. Roll? [Yn] ") ~~ /:i ^n/
	{
	    given DIE.roll {
		say "  You rolled a $_.";
		when 1 {
		    say "  Bust!  You lose $ante but keep your previous $safe.";
		    $ante = 0;
		    last;
		}
		when 2..* {
		    $ante += $_;
		}
	    }
	}
	$safe += $ante;
	if $safe >= $goal {
	    say "\nPlayer #$player wins with a score of $safe!";
	    last;
	}
	@safe[$player] = $safe;
	say "  Sticking with $safe." if $ante;
    }
}

```

The game defaults to the specified task, but we'll play a shorter game with three players for our example:

Output:

```
> pig help
Usage:
  pig [--players=<Int>] [--goal=<Int>]
> pig --players=3 --goal=20

OK, player #0 is up now.
#0, you have 0 + 0 = 0. Roll? [Yn]
  You rolled a 6.
#0, you have 0 + 6 = 6. Roll? [Yn]
  You rolled a 6.
#0, you have 0 + 12 = 12. Roll? [Yn] n
  Sticking with 12.

OK, player #1 is up now.
#1, you have 0 + 0 = 0. Roll? [Yn]
  You rolled a 4.
#1, you have 0 + 4 = 4. Roll? [Yn]
  You rolled a 6.
#1, you have 0 + 10 = 10. Roll? [Yn]
  You rolled a 6.
#1, you have 0 + 16 = 16. Roll? [Yn] n
  Sticking with 16.

OK, player #2 is up now.
#2, you have 0 + 0 = 0. Roll? [Yn]
  You rolled a 5.
#2, you have 0 + 5 = 5. Roll? [Yn]
  You rolled a 1.
  Bust!  You lose 5 but keep your previous 0.

OK, player #0 is up now.
#0, you have 12 + 0 = 12. Roll? [Yn]
  You rolled a 1.
  Bust!  You lose 0 but keep your previous 12.

OK, player #1 is up now.
#1, you have 16 + 0 = 16. Roll? [Yn] n

OK, player #2 is up now.
#2, you have 0 + 0 = 0. Roll? [Yn]
  You rolled a 6.
#2, you have 0 + 6 = 6. Roll? [Yn]
  You rolled a 6.
#2, you have 0 + 12 = 12. Roll? [Yn]
  You rolled a 4.
#2, you have 0 + 16 = 16. Roll? [Yn]
  You rolled a 6.

Player #2 wins with a score of 22!
```


[User]
Task

Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy.

* State here the play strategies involved.
* Show play during a game here.

As a stretch goal:

* Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.

Game Rules

The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either

1. **Rolling the dice**: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points *for that turn* and their turn finishes with play passing to the next player.
2. **Holding**: The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player.

References

* Pig (dice)
* The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.

[Assistant]
(formerly Perl 6)

This implements a pig player class where you can customize the strategy it uses. Pass a strategy code reference in that will evaluate to a Boolean value. The player will roll the die then decide whether to roll again or lock in its winnings based on its strategy. It will continue to roll until it gets a 1 (bust) or the strategy code reference evaluates to True (finished turn).

Set up as many players as you want, then run it. It will play 100 games (by default) then report the score for each game then the win totals for each player. If you want to play a different number of games, pass the number at the command line as a parameter.

Here we have 5 players:

```
 player 0 uses the default strategy, always roll if it can.
 player 1 will roll up to 5 times then lock in whatever it earned.
 player 2 will try to get at least 20 points per turn.
 player 3 randomly picks whether to roll again or not biased so that there is a 90% chance that it will.
 player 4 randomly chooses to roll again but gets more consrvative as its score get closer to the goal.

```

```
my $games = @*ARGS ?? (shift @*ARGS) !! 100;

constant DIE = 1 .. 6;
constant GOAL = 100;

class player {
    has $.score    is rw = 0;
    has $.ante     is rw;
    has $.rolls    is rw;
    has &.strategy is rw = sub { False }; # default, always roll again

    method turn {
        my $done_turn = False;
        $.rolls = 0;
        $.ante  = 0;
        repeat {
            given DIE.roll {
                $.rolls++;
                when 1 {
                    $.ante = 0;
                    $done_turn = True;
                }
                when 2..* {
                    $.ante += $_;
                }
            }
            $done_turn = True if $.score + $.ante >= GOAL or (&.strategy)();
        } until $done_turn;
        $.score += $.ante;
    }
}

my @players;

# default, go-for-broke, always roll again
@players[0] = player.new;

# try to roll 5 times but no more per turn
@players[1] = player.new( strategy => sub { @players[1].rolls >= 5 } );

# try to accumulate at least 20 points per turn
@players[2] = player.new( strategy => sub { @players[2].ante > 20 } );

# random but 90% chance of rolling again
@players[3] = player.new( strategy => sub { 1.rand < .1 } );

# random but more conservative as approaches goal
@players[4] = player.new( strategy => sub { 1.rand < ( GOAL - @players[4].score ) * .6 / GOAL } );

my @wins = 0 xx @players;

for ^ $games {
    my $player = -1;
    repeat {
        $player++;
        @players[$player % @players].turn;
    } until @players[$player % @players].score >= GOAL;

    @wins[$player % @players]++;

    say join "\t", @players>>.score;
    @players[$_].score = 0 for ^@players; # reset scores for next game
}

say "\nSCORES: for $games games";
say join "\t", @wins;

```

**Sample output for 10000 games**

```
0	103	46	5	40
0	100	69	0	48
0	105	22	7	44
0	75	69	19	102
105	21	23	5	17
0	101	85	12	29
0	70	66	103	23
0	0	104	69	20
0	100	44	0	20
0	102	63	75	30
0	56	101	12	40
0	103	71	2	38
0	103	91	21	32
0	18	102	47	28
...
...
...
104	0	69	14	47
0	68	101	13	22
0	99	89	102	31

SCORES: for 10000 games
947	3534	3396	1714	409

```


[User]
Sample image

The task is to demonstrate the creation of a series of vertical pinstripes across **the entire width of the display**.

* in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
* Quarter of the way down the display, we can switch to a wider 2 pixel wide vertical pinstripe pattern, alternating two pixels white, two pixels black.
* Half way down the display, we switch to 3 pixels wide,
* for the lower quarter of the display we use 4 pixels.

c.f. Colour\_pinstripe/Display

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.10

```
my ($x,$y) = 1280,720;
my @colors = 0, 1;

spurt "pinstripes.pgm", qq:to/EOH/ orelse .die;
    P5
    # pinstripes.pgm
    $x $y
    1
    EOH

my $img = open "pinstripes.pgm", :a, :bin orelse .die;

my $vzones = $y div 4;
for 1..4 -> $w {
    my $stripes = ceiling $x / $w / +@colors;
    my $line = Buf.new: (flat((@colors Xxx $w) xx $stripes).Array).splice(0,$x); # DH change 2015-12-20
    $img.write: $line for ^$vzones;
}

$img.close;

```


[User]
The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)

After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).

Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.

Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.01

Note that Raku does not attempt to be a printer driver. This example allows users to specify the dpi and paper size, then generates an image and passes it to the default printer. Defaults to 300 dpi and US letter paper.

```
unit sub MAIN ($dpi = 300, $size = 'letter');

my $filename = './Pinstripe-printer-perl6.png';

my %paper = (
    'letter' => { :width(8.5),    :height(11.0) }
    'A4'     => { :width(8.2677), :height(11.6929)}
);

my ($w, $h) = %paper{$size}<width height> »*» $dpi;

# Black. It's all black
my @color = (0,0,0),;

my $gap = floor $w % ($dpi * 8) / 2;

my $rows = (1, * * 2 … * > 8 * $dpi).elems;

my $height = $dpi * .8;

use Cairo;

my @colors = @color.map: { Cairo::Pattern::Solid.new.create(|$_) };

given Cairo::Image.create(Cairo::FORMAT_ARGB32, $w, $h) -> $image {
    given Cairo::Context.new($image) {
        my Cairo::Pattern::Solid $bg .= create(1,1,1);
        .rectangle(0, 0, $w, $h);
        .pattern($bg);
        .fill;
        $bg.destroy;
        my $y = $gap;
        for ^$rows -> $row {
            my $x = $gap;
            my $width = 8 * $dpi / (2 ** $row);
            for @colors -> $this {
                my $v = 0;
                while $x < ($dpi * 8) {
                    given Cairo::Context.new($image) -> $block {
                        $block.rectangle($x, $y, $width, $height);
                        $block.pattern($this);
                        $block.fill;
                        $block.destroy;
                    }
                    $x += $width * 2;
                }
            }
            $y += $height;
        }
    }
    $image.write_png($filename);
}

# Uncomment next line if you actually want to print it
#run('lp', $filename)

```

See Pinstripe-printer-perl6.png (offsite png image)


[User]
Task

pi(n), the number of primes <= n, where **pi(n) < 22**

Also see
:   * Prime-counting\_function.
    * Tables and hints   by Tomás Oliveira e Silva.
    * the OEIS entry:   A0000720 pi(n), the number of primes <= n. Sometimes called PrimePi(n)....

[Assistant]
```
my @pi = (1..*).map: { state $pi = 0; $pi += .is-prime };

say @pi[^(@pi.first: * >= 22, :k)].batch(10)».fmt('%2d').join: "\n";

```

Output:

```
 0  1  2  2  3  3  4  4  4  4
 5  5  6  6  6  6  7  7  8  8
 8  8  9  9  9  9  9  9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21
```


[User]
The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...

For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.

Prime numbers are straightforward; the Pisano period of a prime number **p** is simply: **pisano(p)**. The Pisano period of a composite number **c** may be found in different ways. It may be calculated directly: **pisano(c)**, which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.

E.G.

Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):

```
   pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where  m  and  n  are coprime

```

A formulae to calculate the pisano period for integer powers   **k**   of prime numbers   **p**   is:

```
   pisano(pk) == p(k-1)pisano(p)

```

The equation is conjectured, no exceptions have been seen.

If a positive integer   **i**   is split into its prime factors,   then the second and first equations above can be applied to generate the pisano period.

Task

Write 2 functions: pisanoPrime(p,k) and pisano(m).

pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.

pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.

Print pisanoPrime(p,2) for every prime lower than 15.

Print pisanoPrime(p,1) for every prime lower than 180.

Print pisano(m) for every integer from 1 to 180.

Related tasks

* Fibonacci sequence
* Prime decomposition
* Least common multiple

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.02

Didn't bother making two differently named routines, just made a multi that will auto dispatch to the correct candidate.

```
use Prime::Factor;

constant @fib := 1,1,*+*…*;

my %cache;

multi pisano-period (Int $p where *.is-prime, Int $k where * > 0 = 1) {
    return %cache{"$p|$k"} if %cache{"$p|$k"};
    my $fibmod = @fib.map: * % $p**$k;
    %cache{"$p|$k"} = (1..*).first: { !$fibmod[$_-1] and ($fibmod[$_] == 1) }
}

multi pisano-period (Int $p where * > 0 ) {
    [lcm] prime-factors($p).Bag.map: { samewith .key, .value }
}

put "Pisano period (p, 2) for primes less than 50";
put (map { pisano-period($_, 2) }, ^50 .grep: *.is-prime )».fmt('%4d');

put "\nPisano period (p, 1) for primes less than 180";
.put for (map { pisano-period($_, 1) }, ^180 .grep: *.is-prime )».fmt('%4d').batch(15);

put "\nPisano period (p, 1) for integers 1 to 180";
.put for (1..180).map( { pisano-period($_) } )».fmt('%4d').batch(15);

```

Output:

```
Pisano period (p, 2) for primes less than 50
   6   24  100  112  110  364  612  342 1104  406  930 2812 1640 3784 1504

Pisano period (p, 1) for primes less than 180
   3    8   20   16   10   28   36   18   48   14   30   76   40   88   32
 108   58   60  136   70  148   78  168   44  196   50  208   72  108   76
 256  130  276   46  148   50  316  328  336  348  178

Pisano period (p, 1) for integers 1 to 180
   1    3    8    6   20   24   16   12   24   60   10   24   28   48   40
  24   36   24   18   60   16   30   48   24  100   84   72   48   14  120
  30   48   40   36   80   24   76   18   56   60   40   48   88   30  120
  48   32   24  112  300   72   84  108   72   20   48   72   42   58  120
  60   30   48   96  140  120  136   36   48  240   70   24  148  228  200
  18   80  168   78  120  216  120  168   48  180  264   56   60   44  120
 112   48  120   96  180   48  196  336  120  300   50   72  208   84   80
 108   72   72  108   60  152   48   76   72  240   42  168  174  144  120
 110   60   40   30  500   48  256  192   88  420  130  120  144  408  360
  36  276   48   46  240   32  210  140   24  140  444  112  228  148  600
  50   36   72  240   60  168  316   78  216  240   48  216  328  120   40
 168  336   48  364  180   72  264  348  168  400  120  232  132  178  120
```


[User]
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.

Task

Create a plasma effect.

See also

* Computer Graphics Tutorial (lodev.org)
* Plasma (bidouille.org)

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.09

```
use Image::PNG::Portable;

my ($w, $h) = 400, 400;
my $out = Image::PNG::Portable.new: :width($w), :height($h);

plasma($out);

$out.write: 'Plasma-perl6.png';

sub plasma ($png) {
    (^$w).race.map: -> $x {
        for ^$h -> $y {
            my $hue = 4 + sin($x / 19) + sin($y / 9) + sin(($x + $y) / 25) + sin(sqrt($x² + $y²) / 8);
            $png.set: $x, $y, |hsv2rgb($hue/8, 1, 1);
        }
    }
}

sub hsv2rgb ( $h, $s, $v ){
    my $c = $v * $s;
    my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );
    my $m = $v - $c;
    (do given $h {
        when   0..^1/6 { $c, $x, 0 }
        when 1/6..^1/3 { $x, $c, 0 }
        when 1/3..^1/2 { 0, $c, $x }
        when 1/2..^2/3 { 0, $x, $c }
        when 2/3..^5/6 { $x, 0, $c }
        when 5/6..1    { $c, 0, $x }
    } ).map: ((*+$m) * 255).Int
}

```


[User]
Task

Implement a Playfair cipher for encryption and decryption.

The user must be able to choose   **J**  =  **I**     or   no   **Q**   in the alphabet.

The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.

Output example

```
                HI DE TH EG OL DI NT HE TR EX ES TU MP

```

[Assistant]
(formerly Perl 6)

```
# Instantiate a specific encoder/decoder.

sub playfair( $key,
              $from = 'J',
	      $to = $from eq 'J' ?? 'I' !! ''
) {

    sub canon($str) { $str.subst(/<-alpha>/,'', :g).uc.subst(/$from/,$to,:g) }

    # Build 5x5 matrix.
    my @m = canon($key ~ ('A'..'Z').join).comb.unique.map:
     -> $a,$b,$c,$d,$e { [$a,$b,$c,$d,$e] }

    # Pregenerate all forward translations.
    my %ENC = gather {
	# Map pairs in same row.
	for @m -> @r {
	    for ^@r X ^@r -> (\i,\j) {
		next if i == j;
		take @r[i] ~ @r[j] => @r[(i+1)%5] ~ @r[(j+1)%5];
	    }
	}

	# Map pairs in same column.
	for ^5 -> $c {
	    my @c = @m.map: *.[$c];
	    for ^@c X ^@c -> (\i,\j) {
		next if i == j;
		take @c[i] ~ @c[j] => @c[(i+1)%5] ~ @c[(j+1)%5];
	    }
	}

	# Map pairs with cross-connections.
	for ^5 X ^5 X ^5 X ^5 -> (\i1,\j1,\i2,\j2) {
	    next if i1 == i2 or j1 == j2;
	    take @m[i1][j1] ~ @m[i2][j2] => @m[i1][j2] ~ @m[i2][j1];
	}
    }

    # Generate reverse translations.
    my %DEC = %ENC.invert;

    return
        sub enc($red) {
	    my @list = canon($red).comb(/(.) (.?) <?{ $1 ne $0 }>/);
	    ~@list.map: { .chars == 1 ?? %ENC{$_~'X'} !! %ENC{$_} }
	},
	sub dec($black) {
	    my @list = canon($black).comb(/../);
	    ~@list.map: { %DEC{$_} }
	}
}

my (&encode,&decode) = playfair 'Playfair example';

my $orig = "Hide the gold in...the TREESTUMP!!!";
say " orig:\t$orig";

my $black = encode $orig;
say "black:\t$black";

my $red = decode $black;
say "  red:\t$red";

```

Output:

```
 orig:	Hide the gold in...the TREESTUMP!!!
black:	BM OD ZB XD NA BE KU DM UI XM MO UV IF
  red:	HI DE TH EG OL DI NT HE TR EX ES TU MP
```


[User]
Task

Create a data structure and the associated methods to define and manipulate a deck of   playing cards.

The deck should contain 52 unique cards.

The methods must include the ability to:

:   :   :   * make a new deck
            * shuffle (randomize) the deck
            * deal from the deck
            * print the current contents of a deck

Each card must have a pip value and a suit value which constitute the unique value of the card.

Related tasks:

* Card shuffles
* Deal cards\_for\_FreeCell
* War Card\_Game
* Poker hand\_analyser
* Go Fish

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.08

```
enum Pip <A 2 3 4 5 6 7 8 9 10 J Q K>;
enum Suit <♦ ♣ ♥ ♠>;

class Card {
    has Pip $.pip;
    has Suit $.suit;

    method Str { $!pip ~ $!suit }
}

class Deck {
    has Card @.cards = pick *,
            map { Card.new(:$^pip, :$^suit) }, flat (Pip.pick(*) X Suit.pick(*));

    method shuffle { @!cards .= pick: * }

    method deal { shift @!cards }

    method Str  { ~@!cards }
    method gist { ~@!cards }
}

my Deck $d = Deck.new;
say "Deck: $d";

my $top = $d.deal;
say "Top card: $top";

$d.shuffle;
say "Deck, re-shuffled: ", $d;

```

Output:

```
Deck: 3♦ J♦ 4♥ 7♠ 7♣ 7♥ 9♣ K♥ 6♠ 2♦ 3♠ Q♥ 8♥ 2♥ J♥ 5♥ 8♦ 8♣ 6♦ 7♦ 5♦ 2♣ 4♦ 8♠ 9♥ 4♣ 3♥ K♠ 2♠ 5♣ Q♣ Q♦ K♦ 4♠ 9♦ Q♠ 5♠ 6♥ J♣ J♠ K♣ 9♠ 3♣ 6♣
Top card: 3♦
Deck, re-shuffled: K♦ 4♣ J♠ 2♥ J♥ K♣ 6♣ 5♠ 3♥ 6♦ 5♦ 4♠ J♣ 4♦ 6♥ K♥ 7♥ 7♦ 2♦ 4♥ 6♠ 7♣ 9♦ 3♣ 3♠ 2♣ 2♠ 8♦ 5♣ 9♠ 5♥ J♦ 9♥ Q♦ Q♣ Q♥ Q♠ 8♥ 8♠ K♠ 9♣ 8♣ 7♠
```


[User]
Task

Plot a function represented as     x,  y     numerical arrays.

Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):

```
      x = {0,   1,    2,    3,    4,    5,     6,     7,     8,     9};
      y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};

```

This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

Generate an SVG image file.

```
use SVG;
use SVG::Plot;

my @x = 0..9;
my @y = (2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0);

say SVG.serialize: SVG::Plot.new(
    width       => 512,
    height      => 512,
    x           => @x,
    x-tick-step => { 1 },
    min-y-axis  => 0,
    values      => [@y,],
    title  => 'Coordinate Pairs',
).plot(:lines);

```


[User] In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.

[Assistant]
(formerly Perl 6)
In Raku all non-native values are boxed and accessed via implicit references. (This is like Java or Python, but unlike C or Perl 5, which use explicit referencing and dereferencing.) Variables are references to containers that can contain references to other values. Basic binding (aliasing) of references to names is supported via the := operator, while assignment to mutable containers implies a dereference from the name to the container, followed by copying of values rather than by duplicating pointers. (Assignment of a bare object reference copies the reference as if it were a value, but the receiving container automatically dereferences as necessary, so to all appearances you are putting the object itself into the destination rather than its reference, and we just think the object can be in more than one place at the same time.)

```
my $foo = 42;    # place a reference to 42 in $foo's item container
$foo++;          # deref $foo name, then increment the container's contents to 43
$foo.say;        # deref $foo name, then $foo's container, and call a method on 43.

$foo := 42;      # bind a direct ref to 42
$foo++;          # ERROR, cannot modify immutable value

my @bar = 1,2,3; # deref @bar name to array container, then set its values
@bar»++;         # deref @bar name to array container, then increment each value with a hyper
@bar.say;        # deref @bar name to array container, then call say on that, giving 2 3 4

@bar := (1,2,3); # bind name directly to a List
@bar»++;         # ERROR, parcels are not mutable
```

References to hashes and functions work more like arrays, insofar as a method call acts directly on the container, not on what the container contains. That is, they don't do the extra dereference implied by calling a method on a scalar variable.

To the first approximation, Raku programmers do not think about references much; since everything is a reference, and value semantics are emulated by assign and other mutating operators, the ubiquitous references are largely transparent to the Raku programmer most of the time.


[User]
Task

Create a program to parse a single five card poker hand and rank it according to this list of poker hands.

A poker hand is specified as a space separated list of five playing cards.

Each input card has two characters indicating face and suit.

Example
:   :   :   :   **2d**       (two of diamonds).

Faces are:    **a**, **2**, **3**, **4**, **5**, **6**, **7**, **8**, **9**, **10**, **j**, **q**, **k**

Suits are:    **h** (hearts),   **d** (diamonds),   **c** (clubs),   and   **s** (spades),   or

alternatively,   the unicode card-suit characters:     ♥ ♦ ♣ ♠

Duplicate cards are illegal.

The program should analyze a single hand and produce one of the following outputs:

```
 straight-flush
 four-of-a-kind
 full-house
 flush
 straight
 three-of-a-kind
 two-pair
 one-pair
 high-card
 invalid

```

Examples

```
   2♥ 2♦ 2♣ k♣ q♦:   three-of-a-kind
   2♥ 5♥ 7♦ 8♣ 9♠:   high-card
   a♥ 2♦ 3♣ 4♣ 5♦:   straight
   2♥ 3♥ 2♦ 3♣ 3♦:   full-house
   2♥ 7♥ 2♦ 3♣ 3♦:   two-pair
   2♥ 7♥ 7♦ 7♣ 7♠:   four-of-a-kind
   10♥ j♥ q♥ k♥ a♥:  straight-flush
   4♥ 4♠ k♠ 5♦ 10♠:  one-pair
   q♣ 10♣ 7♣ 6♣ q♣:  invalid

```

The programs output for the above examples should be displayed here on this page.

Extra credit

1. use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
2. allow two jokers

:   :   * use the symbol   **joker**
        * duplicates would be allowed (for jokers only)
        * five-of-a-kind would then be the highest hand

More extra credit examples

```
   joker  2♦  2♠  k♠  q♦:     three-of-a-kind
   joker  5♥  7♦  8♠  9♦:     straight
   joker  2♦  3♠  4♠  5♠:     straight
   joker  3♥  2♦  3♠  3♦:     four-of-a-kind
   joker  7♥  2♦  3♠  3♦:     three-of-a-kind
   joker  7♥  7♦  7♠  7♣:     five-of-a-kind
   joker  j♥  q♥  k♥  A♥:     straight-flush
   joker  4♣  k♣  5♦ 10♠:     one-pair
   joker  k♣  7♣  6♣  4♣:     flush
   joker  2♦  joker  4♠  5♠:  straight
   joker  Q♦  joker  A♠ 10♠:  straight
   joker  Q♦  joker  A♦ 10♦:  straight-flush
   joker  2♦  2♠  joker  q♦:  four-of-a-kind

```

Related tasks

* Playing cards
* Card shuffles
* Deal cards\_for\_FreeCell
* War Card\_Game
* Go Fish

[Assistant]
(formerly Perl 6)
This solution handles jokers. It has been written to use a Raku grammar.

```
use v6;

grammar PokerHand {

    # Raku Grammar to parse and rank 5-card poker hands
    # E.g. PokerHand.parse("2♥ 3♥ 2♦ 3♣ 3♦");
    # 2013-12-21: handle 'joker' wildcards; maximum of two

    rule TOP {
         :my %*PLAYED;
         { %*PLAYED = () }
         [ <face-card> | <joker> ]**5
    }

    token face-card {<face><suit> <?{
            my $card = ~$/.lc;
            # disallow duplicates
            ++%*PLAYED{$card} <= 1;
       }>
    }

    token joker {:i 'joker' <?{
            my $card = ~$/.lc;
            # allow two jokers in a hand
            ++%*PLAYED{$card} <= 2;
        }>
    }

    token face {:i <[2..9 jqka]> | 10 }
    token suit {<[♥ ♦ ♣ ♠]>}
}

class PokerHand::Actions {
    method TOP($/) {
        my UInt @n    = n-of-a-kind($/);
        my $flush     = 'flush' if flush($/);
        my $straight  = 'straight' if straight($/);
        make rank(@n[0], @n[1], $flush, $straight);
    }
    multi sub rank(5,*@)                    { 'five-of-a-kind' }
    multi sub rank($,$,'flush','straight')  { 'straight-flush' }
    multi sub rank(4,*@)                    { 'four-of-a-kind' }
    multi sub rank($,$,'flush',$)           { 'flush' }
    multi sub rank($,$,$,'straight')        { 'straight' }
    multi sub rank(3,2,*@)                  { 'full-house' }
    multi sub rank(3,*@)                    { 'three-of-a-kind' }
    multi sub rank(2,2,*@)                  { 'two-pair' }
    multi sub rank(2,*@)                    { 'one-pair' }
    multi sub rank(*@)                      { 'high-card' }

    sub n-of-a-kind($/) {
        my %faces := bag @<face-card>.map: -> $/ {~$<face>.lc};
        my @counts = %faces.values.sort.reverse;
        @counts[0] += @<joker>;
        return @counts;
    }

    sub flush($/) {
        my @suits = unique @<face-card>.map: -> $/ {~$<suit>};
        return +@suits == 1;
    }

    sub straight($/) {
        # allow both ace-low and ace-high straights
        constant @Faces = [ "a 2 3 4 5 6 7 8 9 10 j q k a".split: ' ' ];
        constant @Possible-Straights = [ (4 ..^ @Faces).map: { set @Faces[$_-4 .. $_] } ];

        my $faces = set @<face-card>.map: -> $/ {~$<face>.lc};
        my $jokers = +@<joker>;

        return ?( @Possible-Straights.first: { +($faces ∩ $_) + $jokers == 5 } );
    }
}

my PokerHand::Actions $actions .= new;

for ("2♥ 2♦ 2♣ k♣ q♦",   # three-of-a-kind
     "2♥ 5♥ 7♦ 8♣ 9♠",   # high-card
     "a♥ 2♦ 3♣ 4♣ 5♦",   # straight
     "2♥ 3♥ 2♦ 3♣ 3♦",   # full-house
     "2♥ 7♥ 2♦ 3♣ 3♦",   # two-pair
     "2♥ 7♥ 7♦ 7♣ 7♠",   # four-of-a-kind
     "10♥ j♥ q♥ k♥ a♥",  # straight-flush
     "4♥ 4♠ k♠ 5♦ 10♠",  # one-pair
     "q♣ 10♣ 7♣ 6♣ 4♣",  # flush
     "a♥ a♥ 3♣ 4♣ 5♦",   # invalid
     ## EXTRA CREDIT ##
     "joker  2♦  2♠  k♠  q♦",  # three-of-a-kind
     "joker  5♥  7♦  8♠  9♦",  # straight
     "joker  2♦  3♠  4♠  5♠",  # straight
     "joker  3♥  2♦  3♠  3♦",  # four-of-a-kind
     "joker  7♥  2♦  3♠  3♦",  # three-of-a-kind
     "joker  7♥  7♦  7♠  7♣",  # five-of-a-kind
     "joker  j♥  q♥  k♥  A♥",  # straight-flush
     "joker  4♣  k♣  5♦ 10♠",  # one-pair
     "joker  k♣  7♣  6♣  4♣",  # flush
     "joker  2♦ joker  4♠  5♠",  # straight
     "joker  Q♦ joker  A♠ 10♠",  # straight
     "joker  Q♦ joker  A♦ 10♦",  # straight-flush
     "joker  2♦ 2♠  joker  q♦",  # four of a kind
    ) {
    my $rank = do with PokerHand.parse($_, :$actions) {
        .ast;
    }
    else {
        'invalid';
    }
    say "$_: $rank";
}

```

Output:

```
2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind
2♥ 5♠ 7♦ 8♣ 9♠: high-card
a♠ 2♦ 3♣ 4♣ 5♦: straight
2♥ 3♠ 2♦ 3♣ 3♦: full-house
2♥ 7♠ 2♦ 3♣ 3♦: two-pair
2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind
10♠ j♠ q♠ k♠ a♠: straight-flush
4♥ 4♠ k♠ 5♦ 10♠: one-pair
q♣ 10♣ 7♣ 6♣ 4♣: flush
a♥ a♥ 3♣ 4♣ 5♦: invalid
joker  2♦  2♠  k♠  q♦: three-of-a-kind
joker  5♠  7♦  8♠  9♦: straight
joker  2♦  3♠  4♠  5♠: straight
joker  3♥  2♦  3♠  3♦: four-of-a-kind
joker  7♥  2♦  3♠  3♦: three-of-a-kind
joker  7♥  7♦  7♠  7♣: five-of-a-kind
joker  j♠  q♠  k♠  A♠: straight-flush
joker  4♣  k♣  5♦ 10♠: one-pair
joker  k♣  7♣  6♣  4♣: flush
joker  2♦ joker  4♠  5♠: straight
joker  Q♦ joker  A♠ 10♠: straight
joker  Q♦ joker  A♦ 10♦: straight-flush
joker  2♦ 2♠  joker  q♦: four-of-a-kind
```


[User]
In the area of number decomposition algorithms, **Pollard's rho algorithm** is a fast, yet fairly simple method to find factors of a number, using a pseudorandom number generator modulo the number.

Except for trivial factors like 2, 3, 5 etc., it is much faster than trial division, finding a factor quite often, but may terminate without a factor. Thus it cannot prove that a number is prime. If it is known that a number is not prime, the algorithm can be re-iterated with changed parameters to finally find a factor (not necessarily a prime factor) with quite high probability.

Task

Write a function to demonstrate the algorithm (see pseudocode in Wikipedia). The intent is to show the principle as clear as possible in the respective language, but avoid an endless loop. Enhanced versions may be presented as extra examples.

Warning

The variables 'x' and 'y' may be equal during an iteration, calling 'gcd()' with first argument 0,
while the GCD is only defined for postitive numbers, so a library gdc() function might fail. If in this case, the other argument is returned, the algorithm reports failure, which is acceptable.
The gcd() functions supplied for AWK and C have this property.

Example numbers, if supported:

* 4294967213 = 75167 \* 57139 (32 bits)
* 9759463979 = 98779 \* 98801 (34 bits)
* 34225158206557151 = 130051349 \* 263166499 (55 bits)
* 763218146048580636353 = 25998278833 \* 29356487441 (70 bits)

Related tasks

* prime decomposition
* AKS test for primes
* factors of an integer
* factors of a Mersenne number
* trial factoring of a Mersenne number
* partition an integer X into N primes
* sequence of primes by Trial Division

References

* Wikipedia: Pollard's rho algorithm

[Assistant]
Copied verbatim (with different test values) from the Prime decomposition page. This finds all prime factors of an integer of any size. Very large integers, especially those with two or more factors larger than 40 bit may take a while, but it will find them eventually.

Raku handles big integers seamlessly and transparently. No special handling required.

```
sub prime-factors ( Int $n where * > 0 ) {
    return $n if $n.is-prime;
    return () if $n == 1;
    my $factor = find-factor( $n );
    sort flat ( $factor, $n div $factor ).map: &prime-factors;
}

sub find-factor ( Int $n, $constant = 1 ) {
    return 2 unless $n +& 1;
    if (my $gcd = $n gcd 6541380665835015) > 1 { # magic number: [*] primes 3 .. 43
        return $gcd if $gcd != $n
    }
    my $x      = 2;
    my $rho    = 1;
    my $factor = 1;
    while $factor == 1 {
        $rho = $rho +< 1;
        my $fixed = $x;
        my int $i = 0;
        while $i < $rho {
            $x = ( $x * $x + $constant ) % $n;
            $factor = ( $x - $fixed ) gcd $n;
            last if 1 < $factor;
            $i = $i + 1;
        }
    }
    $factor = find-factor( $n, $constant + 1 ) if $n == $factor;
    $factor;
}

.put for (125, 217, 4294967213, 9759463979, 34225158206557151, 763218146048580636353,
5465610891074107968111136514192945634873647594456118359804135903459867604844945580205745718497)\
.hyper(:1batch).map: -> $n {
    my $start = now;
   "factors of $n: ({1+$n.msb} bits) ",
    prime-factors($n).join(' × '), " \t in ", (now - $start).fmt("%0.3f"), " sec."
}

```

Output:

```
factors of 125: (7 bits)  5 × 5 × 5  	 in  0.002  sec.
factors of 217: (8 bits)  7 × 31  	 in  0.001  sec.
factors of 4294967213: (32 bits)  57139 × 75167  	 in  0.001  sec.
factors of 9759463979: (34 bits)  98779 × 98801  	 in  0.001  sec.
factors of 34225158206557151: (55 bits)  130051349 × 263166499  	 in  0.021  sec.
factors of 763218146048580636353: (70 bits)  25998278833 × 29356487441  	 in  0.303  sec.
factors of 5465610891074107968111136514192945634873647594456118359804135903459867604844945580205745718497: (312 bits)  165901 × 10424087 × 18830281 × 53204737 × 56402249 × 59663291 × 91931221 × 95174413 × 305293727939 × 444161842339 × 790130065009  	 in  5.524  sec.
```


[User]
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called *class*.

It is trivial to copy an object if its type is known:

```
int x;
int y = x;

```

Here x is not polymorphic, so y is declared of same type (*int*) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.

The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.08.1

```
my Cool $x = 22/7 but role Fink { method brag { say "I'm a cool {self.WHAT.raku}!" }}
my Cool $y = $x.clone;
$y.brag;

```

Output:

```
I'm a cool Rat+{Fink}!
```


[User]
Task

Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.08.1

All appropriate constructors, initializers, accessors, and destructors are provided by default, but may be explicitly declared for flexibility.
To create only readonly accessors for better encapsulation, leave out all the "is rw" traits.
Here we demonstrate that accessors can behave like variables and may be assigned.

```
class Point {
    has Real $.x is rw = 0;
    has Real $.y is rw = 0;
    method Str { $ }
}

class Circle {
    has Point $.p is rw = Point.new;
    has Real $.r is rw = 0;
    method Str { $ }
}

my $c = Circle.new(p => Point.new(x => 1, y => 2), r => 3);
say $c;
$c.p.x = (-10..10).pick;
$c.p.y = (-10..10).pick;
$c.r   = (0..10).pick;
say $c;

```

In this case we define the Str coercion method polymorphically, which is used by say or print to format the contents of the object.
We could also have defined print methods directly.
We could have factored this method out to a common role and composed it into each class.
We could also have defined multi subs outside of the class, like this:

```
multi print (Point $p) { $p.perl.print }
multi print (Circle $c) { $c.perl.print }

```


[User]
Given a polynomial, represented by an ordered list of its coefficients by increasing degree (e.g. [-1, 6, 5] represents 5x2+6x-1), calculate the polynomial representing the derivative. For example, the derivative of the aforementioned polynomial is 10x+6, represented by [6, 10]. Test cases: 5, -3x+4, 5x2+6x-1, x3-2x2+3x-4, -x4-x3+x+1

Related task
:   * Polynomial long division

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

sub pretty (@poly) {
    join( '+', (^@poly).reverse.map: { @poly[$_] ~ "x{.&super}" } )\
    .subst(/['+'|'-']'0x'<[⁰¹²³⁴⁵⁶⁷⁸⁹]>*/, '', :g).subst(/'x¹'<?before <-[⁰¹²³⁴⁵⁶⁷⁸⁹]>>/, 'x')\
    .subst(/'x⁰'$/, '').subst(/'+-'/, '-', :g).subst(/(['+'|'-'|^])'1x'/, {"$0x"}, :g) || 0
}

for [5], [4,-3], [-1,3,-2,1], [-1,6,5], [1,1,0,-1,-1] -> $test {
   say "Polynomial: " ~ "[{$test.join: ','}] ➡ " ~ pretty $test;
   my @poly = |$test;
   (^@poly).map: { @poly[$_] *= $_ };
   shift @poly;
   say "Derivative: " ~ "[{@poly.join: ','}] ➡ " ~ pretty @poly;
   say '';
}

```

Output:

```
Polynomial: [5] ➡ 5
Derivative: [] ➡ 0

Polynomial: [4,-3] ➡ -3x+4
Derivative: [-3] ➡ -3

Polynomial: [-1,3,-2,1] ➡ x³-2x²+3x-1
Derivative: [3,-4,3] ➡ 3x²-4x+3

Polynomial: [-1,6,5] ➡ 5x²+6x-1
Derivative: [6,10] ➡ 10x+6

Polynomial: [1,1,0,-1,-1] ➡ -x⁴-x³+x+1
Derivative: [1,0,-3,-4] ➡ -4x³-3x²+1
```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Polynomial long division. 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 algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.

Let us suppose a polynomial is represented by a vector,

x
{\displaystyle {\displaystyle x}}
 (i.e., an ordered collection of coefficients) so that the

i
{\displaystyle {\displaystyle i}}
th element keeps the coefficient of

x

i
{\displaystyle {\displaystyle x^{i}}}
, and the multiplication by a monomial is a *shift* of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.

Then a pseudocode for the polynomial long division using the conventions described above could be:

```
degree(P):
  return the index of the last non-zero element of P;
         if all elements are 0, return -∞

polynomial_long_division(N, D) returns (q, r):
  // N, D, q, r are vectors
  if degree(D) < 0 then error
  q ← 0
  while degree(N) ≥ degree(D)
    d ← D shifted right by (degree(N) - degree(D))
    q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
    // by construction, degree(d) = degree(N) of course
    d ← d * q(degree(N) - degree(D))
    N ← N - d
  endwhile
  r ← N
  return (q, r)

```

**Note**: `vector * scalar` multiplies each element of the vector by the scalar; `vectorA - vectorB` subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.

* Error handling (for allocations or for wrong inputs) is not mandatory.
* Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.

**Example for clarification**

This example is from Wikipedia, but changed to show how the given pseudocode works.

```
      0    1    2    3
   ----------------------
N:  -42    0  -12    1        degree = 3
D:   -3    1    0    0        degree = 1

   d(N) - d(D) = 2, so let's shift D towards right by 2:

N:  -42    0  -12    1
d:    0    0   -3    1

   N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
   is like multiplying by x2, and the final multiplication
   (here by 1) is the coefficient of this monomial. Let's store this
   into q:
                               0     1     2
                              ---------------
                          q:   0     0     1

   now compute N - d, and let it be the "new" N, and let's loop

N:  -42    0   -9    0        degree = 2
D:   -3    1    0    0        degree = 1

   d(N) - d(D) = 1, right shift D by 1 and let it be d

N:  -42    0   -9    0
d:    0   -3    1    0        * -9/1 = -9

                          q:   0    -9     1

d:    0   27   -9    0

   N ← N - d

N:  -42  -27    0    0        degree = 1
D:   -3    1    0    0        degree = 1

   looping again... d(N)-d(D)=0, so no shift is needed; we
   multiply D by -27 (= -27/1) storing the result in d, then

                          q:  -27   -9     1

   and

N:  -42  -27    0    0        -
d:   81  -27    0    0        =
N: -123    0    0    0        (last N)

    d(N) < d(D), so now r ← N, and the result is:

       0   1  2
   -------------
q:   -27  -9  1   →  x2 - 9x - 27
r:  -123   0  0   →          -123

```

Related task
:   * Polynomial derivative

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.10

**Translation of**: Perl

for the core algorithm; original code for LaTeX pretty-printing.

```
sub poly_long_div ( @n is copy, @d ) {
    return [0], |@n if +@n < +@d;

    my @q = gather while +@n >= +@d {
        @n = @n Z- flat ( ( @d X* take ( @n[0] / @d[0] ) ), 0 xx * );
        @n.shift;
    }

    return @q, @n;
}

sub xP ( $power ) { $power>1 ?? "x^$power" !! $power==1 ?? 'x' !! '' }
sub poly_print ( @c ) { join ' + ', @c.kv.map: { $^v ~ xP( @c.end - $^k ) } }

my @polys = [ [     1, -12, 0, -42 ], [    1, -3 ] ],
            [ [     1, -12, 0, -42 ], [ 1, 1, -3 ] ],
            [ [          1, 3,   2 ], [    1,  1 ] ],
            [ [ 1, -4,   6, 5,   3 ], [ 1, 2,  1 ] ];

say '<math>\begin{array}{rr}';
for @polys -> [ @a, @b ] {
    printf Q"%s , & %s \\\\\n", poly_long_div( @a, @b ).map: { poly_print($_) };
}
say '\end{array}</math>';

```

Output:

1

x

2
+
−
9
x
+
−
27
,

−
123

1
x
+
−
13
,

16
x
+
−
81

1
x
+
2
,

0

1

x

2
+
−
6
x
+
17
,

−
23
x
+
−
14
{\displaystyle {\displaystyle {\begin{array}{rr}1x^{2}+-9x+-27,&-123\\1x+-13,&16x+-81\\1x+2,&0\\1x^{2}+-6x+17,&-23x+-14\\\end{array}}}}


[User]
Find an approximating polynomial of known degree for a given data.

Example:
For input data:

```
x = {0,  1,  2,  3,  4,  5,  6,   7,   8,   9,   10};
y = {1,  6,  17, 34, 57, 86, 121, 162, 209, 262, 321};

```

The approximating polynomial is:

```
3 x2 + 2 x + 1

```

Here, the polynomial's coefficients are (3, 2, 1).

This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.

[Assistant]
(formerly Perl 6)
We'll use a Clifford algebra library. Very slow.

Rationale (in French for some reason):

Le système d'équations peut s'écrire :

(

a
+
b

x

i
+
c

x

i

2
=

y

i
)

i
=
1
…
N
{\displaystyle {\displaystyle \left(a+bx\_{i}+cx\_{i}^{2}=y\_{i}\right)\_{i=1\ldots N}}}
, où on cherche

(
a
,
b
,
c
)
∈

R

3
{\displaystyle {\displaystyle (a,b,c)\in \mathbb {R} ^{3}}}
. On considère

R

N
{\displaystyle {\displaystyle \mathbb {R} ^{N}}}
 et on répartit chaque équation sur chaque dimension:

(
a
+
b

x

i
+
c

x

i

2
)

e

i
=

y

i

e

i
{\displaystyle {\displaystyle (a+bx\_{i}+cx\_{i}^{2})\mathbf {e} \_{i}=y\_{i}\mathbf {e} \_{i}}}

Posons alors :

x

0
=

∑

i
=
1

N

e

i
,

x

1
=

∑

i
=
1

N

x

i

e

i
,

x

2
=

∑

i
=
1

N

x

i

2

e

i
,

y
=

∑

i
=
1

N

y

i

e

i
{\displaystyle {\displaystyle \mathbf {x} \_{0}=\sum \_{i=1}^{N}\mathbf {e} \_{i},\,\mathbf {x} \_{1}=\sum \_{i=1}^{N}x\_{i}\mathbf {e} \_{i},\,\mathbf {x} \_{2}=\sum \_{i=1}^{N}x\_{i}^{2}\mathbf {e} \_{i},\,\mathbf {y} =\sum \_{i=1}^{N}y\_{i}\mathbf {e} \_{i}}}

Le système d'équations devient :

a

x

0
+
b

x

1
+
c

x

2
=

y
{\displaystyle {\displaystyle a\mathbf {x} \_{0}+b\mathbf {x} \_{1}+c\mathbf {x} \_{2}=\mathbf {y} }}
.

D'où :

a
=

y
∧

x

1
∧

x

2

/
(

x

0
∧

x

1
∧

x

2
)

b
=

y
∧

x

2
∧

x

0

/
(

x

1
∧

x

2
∧

x

0
)

c
=

y
∧

x

0
∧

x

1

/
(

x

2
∧

x

0
∧

x

1
)
{\displaystyle {\displaystyle {\begin{aligned}a=\mathbf {y} \land \mathbf {x} \_{1}\land \mathbf {x} \_{2}/(\mathbf {x} \_{0}\land \mathbf {x\_{1}} \land \mathbf {x\_{2}} )\\b=\mathbf {y} \land \mathbf {x} \_{2}\land \mathbf {x} \_{0}/(\mathbf {x} \_{1}\land \mathbf {x\_{2}} \land \mathbf {x\_{0}} )\\c=\mathbf {y} \land \mathbf {x} \_{0}\land \mathbf {x} \_{1}/(\mathbf {x} \_{2}\land \mathbf {x\_{0}} \land \mathbf {x\_{1}} )\\\end{aligned}}}}

```
use MultiVector;

constant @x1 = <0 1 2 3 4 5 6 7 8 9 10>;
constant @y = <1 6 17 34 57 86 121 162 209 262 321>;

constant $x0 = [+] @e[^@x1];
constant $x1 = [+] @x1 Z* @e;
constant $x2 = [+] @x1 »**» 2  Z* @e;

constant $y  = [+] @y Z* @e;

.say for
  $y∧$x1∧$x2/($x0∧$x1∧$x2),
  $y∧$x2∧$x0/($x1∧$x2∧$x0),
  $y∧$x0∧$x1/($x2∧$x0∧$x1);

```

Output:

```
1
2
3

```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Synthetic division. 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 algebra, polynomial synthetic division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree in an efficient way using a trick involving clever manipulations of coefficients, which results in a lower time complexity than polynomial long division.

[Assistant]
(formerly Perl 6)

**Translation of**: Python

**Works with**: Rakudo version 2018.09

```
sub synthetic-division ( @numerator, @denominator ) {
    my @result = @numerator;
    my $end    = @denominator.end;

    for ^(@numerator-$end) -> $i {
        @result[$i]    /= @denominator[0];
        @result[$i+$_] -= @denominator[$_] * @result[$i] for 1..$end;
    }

    'quotient' => @result[0 ..^ *-$end],
    'remainder' => @result[*-$end .. *];
}

my @tests =
[1, -12, 0, -42], [1, -3],
[1, 0, 0, 0, -2], [1, 1, 1, 1];

for @tests -> @n, @d {
    my %result = synthetic-division( @n, @d );
    say "[{@n}] / [{@d}] = [%result<quotient>], remainder [%result<remainder>]";
}

```

Output:

```
[1 -12 0 -42] / [1 -3] = [1 -9 -27], remainder [-123]
[1 0 0 0 -2] / [1 1 1 1] = [1 -1], remainder [0 0 -1]

```


[User]
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.

Task

Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.

If animation is not practical in your programming environment, you may show a single frame instead.

Pseudo code

```
    set incr to 0.0

    // animation loop
    WHILE true

        incr = (incr + 0.05) MOD 360
        x = width / 2
        y = height / 2
        length = 5
        angle = incr

        // spiral loop
        FOR 1 TO 150
            drawline
            change direction by angle
            length = length + 3
            angle = (angle + incr) MOD 360
        ENDFOR

```

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.09

### SVG "pseudo-animation"

Sort of an ersatz animation. Write updates to a svg file, most modern viewers will update as the content changes.

```
use SVG;
my $w = 600;
my $h = 600;

for 3..33  -> $a {
    my $angle = $a/τ;
    my $x1 = $w/2;
    my $y1 = $h/2;
    my @lines;

    for 1..144 {
        my $length = 3 * $_;
        my ($x2, $y2) = ($x1, $y1) «+« |cis($angle * $_).reals».round(.01) »*» $length ;
        @lines.push: 'line' => [:x1($x1.clone), :y1($y1.clone), :x2($x2.clone), :y2($y2.clone),
                                :style("stroke:rgb({hsv2rgb(($_*5 % 360)/360,1,1).join: ','})")];
        ($x1, $y1) = $x2, $y2;
    }

    my $fname = "./polyspiral-perl6.svg".IO.open(:w);
    $fname.say( SVG.serialize(
        svg => [
            width => $w, height => $h, style => 'stroke:rgb(0,0,0)',
            :rect[:width<100%>, :height<100%>, :fill<black>],
            |@lines,
        ],)
    );
    $fname.close;
    sleep .15;
}

sub hsv2rgb ( $h, $s, $v ){ # inputs normalized 0-1
    my $c = $v * $s;
    my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );
    my $m = $v - $c;
    my ($r, $g, $b) = do given $h {
        when   0..^(1/6) { $c, $x, 0 }
        when 1/6..^(1/3) { $x, $c, 0 }
        when 1/3..^(1/2) { 0, $c, $x }
        when 1/2..^(2/3) { 0, $x, $c }
        when 2/3..^(5/6) { $x, 0, $c }
        when 5/6..1      { $c, 0, $x }
    }
    ( $r, $g, $b ).map: ((*+$m) * 255).Int
}

```

Output:

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

### SDL full animation

Uses the same basic algorithm but fully animated. Use the up / down arrow keys to speed up / slow down the update speed. Use PgUp / PgDn keys to increment / decrement animation speed by large amounts. Use left / right arrow keys to reverse the "direction" of angle change. Press Space bar to toggle animation / reset to minimum speed. Left Control key to toggle stationary / rotating center. Use + / - keys to add remove line segments.

```
use SDL2::Raw;

my $width  = 900;
my $height = 900;

SDL_Init(VIDEO);

my $window = SDL_CreateWindow(
    'Polyspiral',
    SDL_WINDOWPOS_CENTERED_MASK,
    SDL_WINDOWPOS_CENTERED_MASK,
    $width, $height,
    RESIZABLE
);

my $render = SDL_CreateRenderer($window, -1, ACCELERATED +| PRESENTVSYNC);

my $event = SDL_Event.new;

enum KEY_CODES (
    K_UP     => 82,
    K_DOWN   => 81,
    K_LEFT   => 80,
    K_RIGHT  => 79,
    K_SPACE  => 44,
    K_PGUP   => 75,
    K_PGDN   => 78,
    K_LCTRL  => 224,
    K_PLUS   => 87,
    K_MINUS  => 86,
    K_SPLUS  => 46,
    K_SMINUS => 45,
);

my $angle = 0;
my $lines = 240;
my @rgb = palette($lines);
my ($x1, $y1);
my $dir = 1;
my $rot = 0;
my $incr = .0001/π;
my $step = $incr*70;

main: loop {
    while SDL_PollEvent($event) {
        my $casted_event = SDL_CastEvent($event);
        given $casted_event {
            when *.type == QUIT { last main }
            when *.type == KEYDOWN {
                if KEY_CODES(.scancode) -> $comm {
                    given $comm {
                        when 'K_LEFT'   { $dir = $rot ??  1 !! -1 }
                        when 'K_RIGHT'  { $dir = $rot ?? -1 !!  1 }
                        when 'K_UP'     { $step += $incr }
                        when 'K_DOWN'   { $step -= $incr if $step > $incr }
                        when 'K_PGUP'   { $step += $incr*50 }
                        when 'K_PGDN'   { $step -= $incr*50; $step = $step < $incr ?? $incr !! $step }
                        when 'K_SPACE'  { $step = $step ?? 0 !! $incr }
                        when 'K_LCTRL'  { $rot  = $rot  ?? 0 !! -1; $dir *= -1 }
                        when 'K_PLUS'   { $lines = ($lines + 5) min 360; @rgb = palette($lines) }
                        when 'K_SPLUS'  { $lines = ($lines + 5) min 360; @rgb = palette($lines) }
                        when 'K_MINUS'  { $lines = ($lines - 5) max 60;  @rgb = palette($lines) }
                        when 'K_SMINUS' { $lines = ($lines - 5) max 60;  @rgb = palette($lines) }
                    }
                }
                #say .scancode; # unknown key pressed
            }
            when *.type == WINDOWEVENT {
                if .event == 5 {
                    $width  = .data1;
                    $height = .data2;
                }
            }
        }
    }

    $angle = ($angle + $dir * $step) % τ;
    ($x1, $y1) = $width div 2, $height div 2;
    my $dim = $width min $height;
    my $scale = (2 + .33 * abs(π - $angle)) * $dim / $lines;
    $scale *= ($angle > π) ?? (1 - $angle/τ) !! $angle/τ;
    $scale max= $dim/$lines/$lines;
    for ^$lines {
        my $length = $scale + $scale * $_;
        my ($x2, $y2) = ($x1, $y1) «+« cis(($angle * $rot * $lines) + $angle * $_).reals »*» $length;
        SDL_SetRenderDrawColor($render, |@rgb[$_], 255);
        SDL_RenderDrawLine($render, |($x1, $y1, $x2, $y2)».round(1));
        ($x1, $y1) = $x2, $y2;
    }
    @rgb.=rotate($lines/60);
    SDL_RenderPresent($render);
    SDL_SetRenderDrawColor($render, 0, 0, 0, 0);
    SDL_RenderClear($render);
}

SDL_Quit();

sub palette ($l) { (^$l).map: { hsv2rgb(($_ * 360/$l % 360)/360, 1, 1).list } };

sub hsv2rgb ( $h, $s, $v ){ # inputs normalized 0-1
    my $c = $v * $s;
    my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );
    my $m = $v - $c;
    my ($r, $g, $b) = do given $h {
        when   0..^(1/6) { $c, $x, 0 }
        when 1/6..^(1/3) { $x, $c, 0 }
        when 1/3..^(1/2) { 0, $c, $x }
        when 1/2..^(2/3) { 0, $x, $c }
        when 2/3..^(5/6) { $x, 0, $c }
        when 5/6..1      { $c, 0, $x }
    }
    ( $r, $g, $b ).map: ((*+$m) * 255).Int
}

```


[User]
The   *population count*   is the number of   **1**s   (ones)   in the binary representation of a non-negative integer.

*Population count*   is also known as:

:   :   :   :   * *pop count*
                * *popcount*
                * *sideways sum*
                * *bit summation*
                * *Hamming weight*

For example,   **5**   (which is   **101**   in binary)   has a population count of   **2**.

*Evil numbers*   are non-negative integers that have an   *even*   population count.

*Odious numbers*     are  positive integers that have an    *odd*   population count.

Task

* write a function (or routine) to return the population count of a non-negative integer.
* all computation of the lists below should start with   **0**   (zero indexed).

:   * display the   *pop count*   of the   1st   thirty powers of   **3**       (**30**,   **31**,   **32**,   **33**,   **34**,   **∙∙∙**   **329**).
    * display the   1st   thirty     *evil*     numbers.
    * display the   1st   thirty   *odious*   numbers.

* display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified.

See also

* The On-Line Encyclopedia of Integer Sequences:   A000120 population count.
* The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers.
* The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.

[Assistant]
(formerly Perl 6)

```
sub population-count(Int $n where * >= 0) { [+] $n.base(2).comb }

say map &population-count, 3 «**« ^30;
say "Evil: ", (grep { population-count($_) %% 2 }, 0 .. *)[^30];
say "Odious: ", (grep { population-count($_)  % 2 }, 0 .. *)[^30];

```

Output:

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

That's the convenient way to write it, but the following avoids string processing and is therefore about twice as fast:

```
sub population-count(Int $n is copy where * >= 0) {
    loop (my $c = 0; $n; $n +>= 1) {
        $c += $n +& 1;
    }
    $c;
}

```


[User]
**Posit** is a quantization of the real projective line proposed by John Gustafson in 2015. It is claimed to be an improvement over IEEE 754.

The purpose of this task is to write a program capable of decoding a posit number. You will use the example provided by Gustafson in his paper : 0b0000110111011101, representing a 16-bit long real number with three bits for the exponent. Once decoded, you should obtain either the fraction 477/134217728 or the floating point value 3.55393E−6.

Jeff Johnson from Facebook research, described posit numbers as such:

:   A more efficient representation for tapered floating points is the recent *posit* format by Gustafson. It has no explicit size field; the exponent is encoded using a Golomb-Rice prefix-free code, with the exponent

    e
    {\displaystyle {\displaystyle e}}
     encoded as a Golomb-Rice quotient and remainder

    (
    q
    ,
    r
    )
    {\displaystyle {\displaystyle (q,r)}}
     with

    q
    {\displaystyle {\displaystyle q}}
     in unary and

    r
    {\displaystyle {\displaystyle r}}
     in binary (in posit terminology,

    q
    {\displaystyle {\displaystyle q}}
     is the *regime*). Remainder encoding size is defined by the *exponent scale*

    s
    {\displaystyle {\displaystyle s}}
    , where

    2

    s
    {\displaystyle {\displaystyle 2^{s}}}
     is the Golomb-Rice divisor. Any space not used by the exponent encoding is used by the significand, which unlike IEEE 754 always has a leading 1; gradual underflow (and overflow) is handled by tapering. A posit number system is characterized by

    (
    N
    ,
    s
    )
    {\displaystyle {\displaystyle (N,s)}}
    , where

    N
    {\displaystyle {\displaystyle N}}
     is the word length in bits and

    s
    {\displaystyle {\displaystyle s}}
     is the exponent scale. The minimum and maximum positive finite numbers in

    (
    N
    ,
    s
    )
    {\displaystyle {\displaystyle (N,s)}}
     are **Failed to parse (syntax error): {\displaystyle f\_\mathrm{min} = 2^{−(N−2)2^s}}**
    and **Failed to parse (syntax error): {\displaystyle f\_\mathrm{max} = 2^{(N−2)2^s}}**
    . The number line is represented much as the projective reals, with a single point at

    ±
    ∞
    {\displaystyle {\displaystyle \pm \infty }}
     bounding **Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest\_v1/":): {\displaystyle −f\_\mathrm{max}}**
    and

    f

    m
    a
    x
    {\displaystyle {\displaystyle f\_{\mathrm {max} }}}
    .

    ±
    ∞
    {\displaystyle {\displaystyle \pm \infty }}
     and 0 have special encodings; there is no NaN. The number system allows any choice of

    N
    ≥
    3
    {\displaystyle {\displaystyle N\geq 3}}
     and **Failed to parse (syntax error): {\displaystyle 0\le s\le N − 3}**
    .
:   s
    {\displaystyle {\displaystyle s}}
     controls the dynamic range achievable; e.g., 8-bit (8, 5)-posit

    f

    m
    a
    x
    =

    2

    192
    {\displaystyle {\displaystyle f\_{\mathrm {max} }=2^{192}}}
     is larger than

    f

    m
    a
    x
    {\displaystyle {\displaystyle f\_{\mathrm {max} }}}
     in float32. (8, 0) and (8, 1) are more reasonable values to choose for 8-bit floating point representations, with

    f

    m
    a
    x
    {\displaystyle {\displaystyle f\_{\mathrm {max} }}}
     of 64 and 4096 accordingly. Precision is maximized in the range **Failed to parse (syntax error): {\displaystyle \pm\left[2^{−(s+1)}, 2^{s+1}\right)}**
    with **Failed to parse (syntax error): {\displaystyle N − 3 − s}**
    significand fraction bits, tapering to no fraction bits at

    ±

    f

    m
    a
    x
    {\displaystyle {\displaystyle \pm f\_{\mathrm {max} }}}
    .
:   — Jeff Johnson, *Rethinking floating point for deep learning*, Facebook research.

[Assistant]
**Translation of**: Mathematica

```
=begin LICENSE
Copyright © 2017 John L. Gustafson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

This copyright and permission notice shall be included in all copies or substantial portions of the software.

THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY,
WHETHER IN AN ACTION OR CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=end LICENSE

constant nbits = 16;
constant es    = 3;
constant npat  = 2**nbits;
constant useed = 2**2**es;
constant minpos = useed**(-nbits + 2);
constant maxpos = useed**(+nbits - 2);
constant qsize  = 2**((nbits-2)*2**(es+2)+5).log2.ceiling;
constant qextra = qsize - (nbits - 2)*2**(es+2);

constant posit-range = 0..^2**nbits;

sub twoscomp($sign, $p) { ($sign > 0 ?? $p !! npat - $p) mod npat }

sub sign-bit(UInt $p where posit-range) { +$p.polymod(2 xx nbits - 1).tail }
sub regime-bits(UInt $p where posit-range) {
  my $q = twoscomp(1 - sign-bit($p), $p);
  my @bits = $q.polymod(2 xx nbits - 1).reverse;
  my $bit2 = @bits[1];
  my @temp-bits = flat @bits[1..*], 1 - $bit2;
  my $npower = @temp-bits.first(1 - $bit2, :k) - 1;
  @bits[1..($npower+1)];
}
sub regime-value(@bits) { @bits.head ?? @bits.elems - 1 !! -@bits; }
sub exponent-bits(UInt $p where posit-range) {
  my $q = twoscomp(1 - sign-bit($p), $p);
  my $startbit = regime-bits($q).elems + 3;
  my @bits = $q.polymod(2 xx nbits - 1).reverse;
  @bits[$startbit-1 .. $startbit-1 + es - 1]
}
sub fraction-bits(UInt $p where posit-range) {
  my $q = twoscomp(1 - sign-bit($p), $p);
  my $startbit = regime-bits($q).elems + 3 + es;
  my @bits = $q.polymod(2 xx nbits - 1).reverse;
  @bits[$startbit-1 .. *];
}

sub p2x(UInt $p where posit-range) {
  my $s = (-1)**sign-bit($p);
  my $k = regime-value regime-bits $p;
  my @e = exponent-bits $p;
  my @f = fraction-bits $p;
  @e.push: 0 until @e == es;
  my $e = @e.reduce: 2 * * + *;
  my $f = @f == 0 ?? 1 !! 1.FatRat + @f.reduce(2 * * + *)/2**@f;
  given $p {
    when 0          { 0   }
    when npat div 2 { Inf }
    default         { $s * useed**$k * 2**$e * $f }
  }
}

dd p2x 0b0000110111011101;

```

Output:

```
FatRat.new(477, 134217728)
```

You may Attempt This Online!


[User]
Encode pi as a 8-bit posit with a 2-bit exponent.

As an unsigned integer, the result should be 77.

[Assistant]
**Translation of**: Mathematica

```
=begin LICENSE
Copyright © 2017 John L . Gustafson

Permission is hereby granted, free of charge to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction including without limitation the rights to use copy, modify, merge, publish, distribute, sub - license, and/or sell copies of the Software and to permit persons to whom the Software is furnished to do so, subject to the following conditions :

This copyright and permission notice shall be included in all copies or substantial portions of the software .

THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OR CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE .
=end LICENSE

# L<https://posithub.org/docs/Posits4.pdf>
constant nbits = 8;
constant es    = 2;
constant npat  = 2**nbits;
constant useed = 2**2**es;
constant minpos = useed**(-nbits + 2);
constant maxpos = useed**(+nbits - 2);
constant qsize  = 2**((nbits-2)*2**(es+2)+5).log2.ceiling;
constant qextra = qsize - (nbits - 2)*2**(es+2);

constant posit-range = ^npat;
subset posit of UInt where posit-range;

sub x2p(Real $x --> posit) {

  # first, take care of the two exceptional values
  return 0 if $x == 0;
  return npat div 2 if $x == Inf;

  # working variables
  my ($i, $p, $e, $y) = $, $, 2**(es - 1), $x.abs;

  if $y ≥ 1 { # north-east quadrant
    ($p, $i) = 1, 2;
    # Shift in 1s from the right and scale down.
    ($p, $y, $i) = 2*$p+1, $y/useed, $i+1 while $y ≥ useed && $i ≤ nbits;
    $p *= 2; $i++;
  } else { # south-east quadrant
    ($p, $i) = 0, 1;
    # Shift in 0 s from the right and scale up.
    ($y, $i) = $y*useed, $i+1 while $y < 1 && $i ≤ nbits;
    if $i ≥ nbits {
      $p = 2; $i = nbits + 1;
    } else { $p = 1; $i++; }
  }
  # Extract exponent bits:
  while $e > 1/2 and $i ≤ nbits {
    $p *= 2;
    if $y ≥ 2**$e { $y /= 2**$e; $p++ }
    $e /= 2;
    $i++;
  }
  $y--;
  # Fraction bits; substract the hidden bit
  while $y > 0 and $i ≤ nbits {
    $y *= 2;
    $p = 2*$p + $y.floor;
    $y -= $y.floor;
    $i++
  }
  $p *= 2**(nbits+1-$i);
  $i++;

  # Round to nearest; tie goes to even
  $i = $p +& 1;
  $p = ($p/2).floor;
  $p = $i == 0 ?? $p !!
       $y == 0|1 ?? $p + $p+&1 !!
       $p + 1;

  # Simulate 2's complement
  ($x < 0 ?? npat - $p !! $p) mod npat;

}

say x2p pi;

```

Output:

```
77
```

You may Attempt This Online!


[User]
Task

Find positive decimal integers   **n**   in which the digit   **1**   occurs exactly twice,   where   **n   <   1,000**.

[Assistant]
```
say display 10, '%3d', ^1000 .grep: { .comb.Bag{'1'} == 2 };

sub display {
    cache $^c;
    "{+$c} matching:\n" ~ $c.batch($^a)».fmt($^b).join: "\n"
}

```

Yields:

```
27 matching:
 11 101 110 112 113 114 115 116 117 118
119 121 131 141 151 161 171 181 191 211
311 411 511 611 711 811 911
```


[User]
A   set   is a collection (container) of certain values,
without any particular order, and no repeated values.

It corresponds with a finite set in mathematics.

A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.

Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.

Task

By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.

For example, the power set of     {1,2,3,4}     is

:   :   :   {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.

For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.

The power set of the empty set is the set which contains itself (20 = 1):

:   :   :   P
            {\displaystyle {\displaystyle {\mathcal {P}}}}
            (

            ∅
            {\displaystyle {\displaystyle \varnothing }}
            ) = {

            ∅
            {\displaystyle {\displaystyle \varnothing }}
             }

And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):

:   :   :   P
            {\displaystyle {\displaystyle {\mathcal {P}}}}
            ({

            ∅
            {\displaystyle {\displaystyle \varnothing }}
            }) = {

            ∅
            {\displaystyle {\displaystyle \varnothing }}
            , {

            ∅
            {\displaystyle {\displaystyle \varnothing }}
             } }

**Extra credit:**  Demonstrate that your language supports these last two powersets.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2014-02-25

```
sub powerset(Set $s) { $s.combinations.map(*.Set).Set }
say powerset set <a b c d>;
```

Output:

```
set(set(), set(a), set(b), set(c), set(d), set(a, b), set(a, c), set(a, d), set(b, c), set(b, d), set(c, d), set(a, b, c), set(a, b, d), set(a, c, d), set(b, c, d), set(a, b, c, d))
```

If you don't care about the actual Set type, the .combinations method by itself may be good enough for you:

```
.say for <a b c d>.combinations
```

Output:

```

a
b
c
d
a b
a c
a d
b c
b d
c d
a b c
a b d
a c d
b c d
a b c d
```


[User]
A **k**-powerful (or **k**-full) number is a positive integer **n** such that for every prime number **p** dividing **n**, **p^k** also divides **n**.

These are numbers of the form:

```
  2-powerful = a^2 * b^3,             for a,b >= 1
  3-powerful = a^3 * b^4 * c^5,       for a,b,c >= 1
  4-powerful = a^4 * b^5 * c^6 * d^7, for a,b,c,d >= 1
  ...
  k-powerful = a^k * b^(k+1) * c^(k+2) *...* ω^(2*k-1), for a,b,c,...,ω >= 1

```

Task

Write a function that generates all the **k**-powerful numbers less than or equal to **n**.

* For **k = 2..10**, generate the set of **k**-powerful numbers **<= 10^k** and show the first **5** and the last **5** terms, along with the length of the set.

Write a function that counts the number of **k**-powerful numbers less than or equal to **n**. (optional)

* For **k = 2..10**, show the number of **k**-powerful numbers less than or equal to **10^j**, for **0 <= j < k+10**.

See also

* Wikipedia, Powerful number

* OEIS A001694: 2-powerful numbers

* OEIS A036966: 3-powerful numbers

* OEIS A036967: 4-powerful numbers

* OEIS A069492: 5-powerful numbers

* OEIS A069493: 6-powerful numbers

* OEIS A062762: number of powerful numbers <= 2^n

* OEIS A118896: number of powerful numbers <= 10^n

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.01

**Translation of**: Perl

Raku has no handy pre-made nth integer root routine so has the same problem as Go with needing a slight "fudge factor" in the nth root calculation.

```
sub super (\x) { x.trans([<0123456789>.comb] => [<⁰¹²³⁴⁵⁶⁷⁸⁹>.comb]) }

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

sub powerfuls (\n, \k, \enumerate = False) {
    my @powerful;
    p(1, 2*k - 1);
    sub p (\m, \r) {
        if r < k {
            enumerate ?? @powerful.push(m) !! ++@powerful[m - 1  ?? (m - 1).chars !! 0];
            return
        }
        for 1 .. ((n / m) ** (1/r) + .0001).Int -> \v {
            if r > k {
                next unless is-square-free(v);
                next unless m gcd v == 1;
            }
            p(m * v ** r, r - 1)
        }
    }
    @powerful;
}

put "Count and first and last five enumerated n-powerful numbers in 10ⁿ:";
for 2..10 -> \k {
    my @powerful = sort powerfuls(10**k, k, True);
    printf "%2d %2s-powerful numbers <= 10%-2s: %s ... %s\n", +@powerful, k, super(k),
           @powerful.head(5).join(", "), @powerful.tail(5).join(", ");
}

put "\nCounts in each order of magnitude:";
my $top = 9;
for 2..10 -> \k {
    printf "%2s-powerful numbers <= 10ⁿ (where 0 <= n <= %d): ", k, $top+k;
    quietly say join ', ', [\+] powerfuls(10**($top + k), k);
}

```

Output:

```
Count and first and last five enumerated n-powerful numbers in 10ⁿ:
14  2-powerful numbers <= 10² : 1, 4, 8, 9, 16 ... 49, 64, 72, 81, 100
20  3-powerful numbers <= 10³ : 1, 8, 16, 27, 32 ... 625, 648, 729, 864, 1000
25  4-powerful numbers <= 10⁴ : 1, 16, 32, 64, 81 ... 5184, 6561, 7776, 8192, 10000
32  5-powerful numbers <= 10⁵ : 1, 32, 64, 128, 243 ... 65536, 69984, 78125, 93312, 100000
38  6-powerful numbers <= 10⁶ : 1, 64, 128, 256, 512 ... 559872, 746496, 823543, 839808, 1000000
46  7-powerful numbers <= 10⁷ : 1, 128, 256, 512, 1024 ... 7558272, 8388608, 8957952, 9765625, 10000000
52  8-powerful numbers <= 10⁸ : 1, 256, 512, 1024, 2048 ... 60466176, 67108864, 80621568, 90699264, 100000000
59  9-powerful numbers <= 10⁹ : 1, 512, 1024, 2048, 4096 ... 644972544, 725594112, 816293376, 967458816, 1000000000
68 10-powerful numbers <= 10¹⁰: 1, 1024, 2048, 4096, 8192 ... 7739670528, 8589934592, 8707129344, 9795520512, 10000000000

Counts in each order of magnitude:
 2-powerful numbers <= 10ⁿ (where 0 <= n <= 11): 1, 4, 14, 54, 185, 619, 2027, 6553, 21044, 67231, 214122, 680330
 3-powerful numbers <= 10ⁿ (where 0 <= n <= 12): 1, 2, 7, 20, 51, 129, 307, 713, 1645, 3721, 8348, 18589, 41136
 4-powerful numbers <= 10ⁿ (where 0 <= n <= 13): 1, 1, 5, 11, 25, 57, 117, 235, 464, 906, 1741, 3312, 6236, 11654
 5-powerful numbers <= 10ⁿ (where 0 <= n <= 14): 1, 1, 3, 8, 16, 32, 63, 117, 211, 375, 659, 1153, 2000, 3402, 5770
 6-powerful numbers <= 10ⁿ (where 0 <= n <= 15): 1, 1, 2, 6, 12, 21, 38, 70, 121, 206, 335, 551, 900, 1451, 2326, 3706
 7-powerful numbers <= 10ⁿ (where 0 <= n <= 16): 1, 1, 1, 4, 10, 16, 26, 46, 77, 129, 204, 318, 495, 761, 1172, 1799, 2740
 8-powerful numbers <= 10ⁿ (where 0 <= n <= 17): 1, 1, 1, 3, 8, 13, 19, 32, 52, 85, 135, 211, 315, 467, 689, 1016, 1496, 2191
 9-powerful numbers <= 10ⁿ (where 0 <= n <= 18): 1, 1, 1, 2, 6, 11, 16, 24, 38, 59, 94, 145, 217, 317, 453, 644, 919, 1308, 1868
10-powerful numbers <= 10ⁿ (where 0 <= n <= 19): 1, 1, 1, 1, 5, 9, 14, 21, 28, 43, 68, 104, 155, 227, 322, 447, 621, 858, 1192, 1651
```


[User]
A Practical number P has some selection of its proper divisors, (other than
itself), that can be selected to sum to every integer less than itself.

Compute all the proper divisors/factors of an input number X, then, using all selections from
the factors compute all possible sums of factors and see if all numbers from 1
to X-1 can be created from it.

Task

Write a function that given X returns a boolean value of whether X *is* a
Practical number, (using the above method).

* Show how many Practical numbers there are in the range 1..333, inclusive.
* Show that the Practical numbers in the above range start and end in:

:   1, 2, 4, 6, 8, 12, 16, 18, 20, 24 ... 288, 294, 300, 304, 306, 308, 312, 320, 324, 330

Stretch Goal

* Show if 666 is a Practical number

[Assistant]
```
use Prime::Factor:ver<0.3.0+>;

sub is-practical ($n) {
   return True  if $n == 1;
   return False if $n % 2;
   my @proper = $n.&proper-divisors :sort;
   return True if all( @proper.rotor(2 => -1).map: { .[0] / .[1] >= .5 } );
   my @proper-sums = @proper.combinations».sum.unique.sort;
   +@proper-sums < $n-1 ?? False !! @proper-sums[^$n] eqv (^$n).list ?? True !! False
}

say "{+$_} matching numbers:\n{.batch(10)».fmt('%3d').join: "\n"}\n"
    given [ (1..333).hyper(:32batch).grep: { is-practical($_) } ];

printf "%5s is practical? %s\n", $_, .&is-practical for 666, 6666, 66666, 672, 720;

```

Output:

```
77 matching numbers:
  1   2   4   6   8  12  16  18  20  24
 28  30  32  36  40  42  48  54  56  60
 64  66  72  78  80  84  88  90  96 100
104 108 112 120 126 128 132 140 144 150
156 160 162 168 176 180 192 196 198 200
204 208 210 216 220 224 228 234 240 252
256 260 264 270 272 276 280 288 294 300
304 306 308 312 320 324 330

  666 is practical? True
 6666 is practical? True
66666 is practical? False
  672 is practical? True
  720 is practical? True
```


[User]
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules).

Task

List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.

[Assistant]
(formerly Perl 6)

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

The Perl 6 pragma mechanism is nearly identical to Perl 5's, piggybacking on the notation for importing modules (pragmas are distinguished by case from normal modules, which are generally of mixed case). By convention pragmas are lowercase, unless they are indicating the use of an unsafe feature, in which case they are in all caps.

```
use MONKEY-TYPING;
augment class Int {
    method times (&what) { what() xx self }  # pretend like we're Ruby
}

```

Unlike Perl 5, there is no use strict; pragma, however, since Perl 6 is strict by default. Importation of a pragma is lexically scoped as in Perl 5, but note that unlike in Perl 5, *all* importation is lexical in Perl 6, so pragmas are not special that way.


[User]
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department.

Task

Given a floating point value between   0.00   and   1.00,   rescale according to the following table:

```
>=  0.00  <  0.06  :=  0.10
>=  0.06  <  0.11  :=  0.18
>=  0.11  <  0.16  :=  0.26
>=  0.16  <  0.21  :=  0.32
>=  0.21  <  0.26  :=  0.38
>=  0.26  <  0.31  :=  0.44
>=  0.31  <  0.36  :=  0.50
>=  0.36  <  0.41  :=  0.54
>=  0.41  <  0.46  :=  0.58
>=  0.46  <  0.51  :=  0.62
>=  0.51  <  0.56  :=  0.66
>=  0.56  <  0.61  :=  0.70
>=  0.61  <  0.66  :=  0.74
>=  0.66  <  0.71  :=  0.78
>=  0.71  <  0.76  :=  0.82
>=  0.76  <  0.81  :=  0.86
>=  0.81  <  0.86  :=  0.90
>=  0.86  <  0.91  :=  0.94
>=  0.91  <  0.96  :=  0.98
>=  0.96  <  1.01  :=  1.00

```

[Assistant]
(formerly Perl 6)

Simple solution, doing a linear search.
Note that in Raku we don't have to worry about floating-point misrepresentations of decimals, because decimal fractions are stored as rationals.

**Works with**: rakudo version 2016.07

```
sub price-fraction ($n where 0..1) {
    when $n < 0.06 { 0.10 }
    when $n < 0.11 { 0.18 }
    when $n < 0.16 { 0.26 }
    when $n < 0.21 { 0.32 }
    when $n < 0.26 { 0.38 }
    when $n < 0.31 { 0.44 }
    when $n < 0.36 { 0.50 }
    when $n < 0.41 { 0.54 }
    when $n < 0.46 { 0.58 }
    when $n < 0.51 { 0.62 }
    when $n < 0.56 { 0.66 }
    when $n < 0.61 { 0.70 }
    when $n < 0.66 { 0.74 }
    when $n < 0.71 { 0.78 }
    when $n < 0.76 { 0.82 }
    when $n < 0.81 { 0.86 }
    when $n < 0.86 { 0.90 }
    when $n < 0.91 { 0.94 }
    when $n < 0.96 { 0.98 }
    default        { 1.00 }
}

while prompt("value: ") -> $value {
    say price-fraction(+$value);
}

```

If we expect to rescale many prices, a better approach would be to build a look-up array of 101 entries.
Memory is cheap, and array indexing is blazing fast.

```
my @price = map *.value, flat
    ( 0 ..^ 6  X=> 0.10),
    ( 6 ..^ 11 X=> 0.18),
    (11 ..^ 16 X=> 0.26),
    (16 ..^ 21 X=> 0.32),
    (21 ..^ 26 X=> 0.38),
    (26 ..^ 31 X=> 0.44),
    (31 ..^ 36 X=> 0.50),
    (36 ..^ 41 X=> 0.54),
    (41 ..^ 46 X=> 0.58),
    (46 ..^ 51 X=> 0.62),
    (51 ..^ 56 X=> 0.66),
    (56 ..^ 61 X=> 0.70),
    (61 ..^ 66 X=> 0.74),
    (66 ..^ 71 X=> 0.78),
    (71 ..^ 76 X=> 0.82),
    (76 ..^ 81 X=> 0.86),
    (81 ..^ 86 X=> 0.90),
    (86 ..^ 91 X=> 0.94),
    (91 ..^ 96 X=> 0.98),
    (96 ..^101 X=> 1.00),
;

while prompt("value: ") -> $value {
    say @price[$value * 100] // "Out of range";
}

```

We can also build this same look-up array by parsing the table as formatted in the task description:

**Works with**: rakudo version 2016.07

```
my $table = q:to/END/;
>=  0.00  <  0.06  :=  0.10
>=  0.06  <  0.11  :=  0.18
>=  0.11  <  0.16  :=  0.26
>=  0.16  <  0.21  :=  0.32
>=  0.21  <  0.26  :=  0.38
>=  0.26  <  0.31  :=  0.44
>=  0.31  <  0.36  :=  0.50
>=  0.36  <  0.41  :=  0.54
>=  0.41  <  0.46  :=  0.58
>=  0.46  <  0.51  :=  0.62
>=  0.51  <  0.56  :=  0.66
>=  0.56  <  0.61  :=  0.70
>=  0.61  <  0.66  :=  0.74
>=  0.66  <  0.71  :=  0.78
>=  0.71  <  0.76  :=  0.82
>=  0.76  <  0.81  :=  0.86
>=  0.81  <  0.86  :=  0.90
>=  0.86  <  0.91  :=  0.94
>=  0.91  <  0.96  :=  0.98
>=  0.96  <  1.01  :=  1.00
END

my @price;

for $table.lines {
    /:s '>='  (\S+)  '<'  (\S+)  ':='  (\S+)/;
    @price[$0*100 ..^ $1*100] »=» +$2;
}

while prompt("value: ") -> $value {
    say @price[$value * 100] // "Out of range";
}

```


[User]
There is a list of around 100\_000 prices in the range £0 to £100\_000, expressed
in whole £, (no pence); and prices *may* be duplicated.
The API allows access to the maximum item price via
function `get_max_price()`; and the number of items equal-to and between two
given price points via function `get_prange_count(pricemin, pricemax)`.
Assume that for the purposes of testing, you have access to the actual number of priced items to split.

Task

1. Write functions to randomly generate around 100K prices and provide the `get_prange_count` and `get_max_price` API calls.
2. Write functions to provide non-overlapping min and max price ranges that provide product counts where most are close to, but no more than, 5\_000.
3. Ensure that all priced items are covered by all the ranges of prices shown
4. Show ascending price ranges and the number of items covered by each range.
5. Show output from a sample run here.

[Assistant]
**Translation of**: Go

```
# 20210208 Raku programming solution

my \minDelta = 1;

sub getMaxPrice { @_.max }

sub getPRangeCount(@prices,\min,\max) { +@prices.grep: min ≤ * ≤ max }

sub get5000(@prices, $min, $max is copy, \n) {
   my $count = getPRangeCount(@prices, $min, $max);
   my $delta = ($max - $min) / 2;
   while $count != n && $delta ≥ minDelta/2 {
      $count > n ?? ($max -= $delta) !! ($max += $delta);
      $count = getPRangeCount(@prices, $min, $max);
      $delta /= 2;
   }
   $max, $count
}

sub getAll5000(@prices, \min, \max, \n) {
   my ( $pmax, $pcount ) = get5000(@prices, min, max, n);
   my @res = [ min, $pmax, $pcount ] , ;
   while $pmax < max {
      my $pmin = $pmax + 1;
      ( $pmax, $pcount ) = get5000(@prices, $pmin, max, n);
      $pcount == 0 and note "Price list from $pmin has too many duplicates.";
      @res.push: [ $pmin, $pmax, $pcount ];
   }
   @res
}

my $numPrices = (99000..101001).roll;
my \maxPrice  = 1e5;
my @prices    = (1..$numPrices+1).roll xx $numPrices ;

my $actualMax = getMaxPrice(@prices);
say "Using $numPrices items with prices from 0 to $actualMax:";

my @res = getAll5000(@prices, 0, $actualMax, 5000);
say "Split into ", +@res, " bins of approx 5000 elements:";

for @res -> @row {
   my ($min,$max,$subtotal) = @row;
   $max = $actualMax if $max > $actualMax ;
   printf "  From %6d to %6d with %4d items\n", $min, $max, $subtotal
}

```

Output:

```
Using 99506 items with prices from 0 to 99507:
Split into 20 bins of approx 5000 elements:
  From      0 to   4983 with 5000 items
  From   4984 to  10034 with 5003 items
  From  10035 to  15043 with 4998 items
  From  15044 to  20043 with 5001 items
  From  20044 to  24987 with 5001 items
  From  24988 to  30000 with 4998 items
  From  30001 to  34954 with 5000 items
  From  34955 to  40018 with 5000 items
  From  40019 to  45016 with 5000 items
  From  45017 to  49950 with 5000 items
  From  49951 to  54877 with 4999 items
  From  54878 to  59880 with 5002 items
  From  59881 to  64807 with 5001 items
  From  64808 to  69800 with 5000 items
  From  69801 to  74897 with 5000 items
  From  74898 to  79956 with 5002 items
  From  79957 to  85037 with 5000 items
  From  85038 to  90118 with 5001 items
  From  90119 to  95169 with 5001 items
  From  95170 to  99507 with 4470 items

```


[User]
Task

Write a boolean function that tells whether a given integer is prime.

Remember that   **1**   and all non-positive numbers are not prime.

Use trial division.

Even numbers greater than   **2**   may be eliminated right away.

A loop from   **3**   to   **√ n** will suffice,   but other loops are allowed.

Related tasks

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

[Assistant]
(formerly Perl 6)
Here we use a "none" junction which will autothread through the %% "is divisible by" operator to assert that $i is not divisible by 2 or any of the numbers up to its square root. Read it just as you would English: "Integer $i is prime if it is greater than one and is divisible by none of 2, 3, up to the square root of $i."

```
sub prime (Int $i --> Bool) {
    $i > 1 and so $i %% none 2..$i.sqrt;
}
```

This can easily be improved in two ways. First, we generate the primes so we only divide by those, instead of all odd numbers. Second, we memoize the result using the //= idiom of Perl, which does the right-hand calculation and assigns it only if the left side is undefined. We avoid recalculating the square root each time. Note the mutual recursion that depends on the implicit laziness of list evaluation:

```
my @primes = 2, 3, 5, -> $p { ($p+2, $p+4 ... &prime)[*-1] } ... *;
my @isprime = False,False;   # 0 and 1 are not prime by definition
sub prime($i) {
    my \limit = $i.sqrt.floor;
    @isprime[$i] //= so ($i %% none @primes ...^ { $_ > limit })
}

say "$_ is{ "n't" x !prime($_) } prime." for 1 .. 100;
```


[User]
Task

Write a boolean function that tells whether a given integer is prime using Wilson's theorem.

By Wilson's theorem, a number **p** is prime if and only if **p** divides `(p - 1)! + 1`.

Remember that **1** and all non-positive integers are not prime.

See also

* Cut-the-knot: Wilson's theorem.
* Wikipedia: Wilson's theorem

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

Not a particularly recommended way to test for primality, especially for larger numbers. It *works*, but is slow and memory intensive.

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

sub is-wilson-prime (Int $p where * > 1) { (($p - 1)! + 1) %% $p }

# Pre initialize factorial routine (not thread safe)
9000!;

# Testing
put '   p  prime?';
printf("%4d  %s\n", $_, .&is-wilson-prime) for 2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659;

my $wilsons = (2,3,*+2…*).hyper.grep: &is-wilson-prime;

put "\nFirst 120 primes:";
put $wilsons[^120].rotor(20)».fmt('%3d').join: "\n";

put "\n1000th through 1015th primes:";
put $wilsons[999..1014];

```

Output:

```
   p  prime?
   2  True
   3  True
   9  False
  15  False
  29  True
  37  True
  47  True
  57  False
  67  True
  77  False
  87  False
  97  True
 237  False
 409  True
 659  True

First 120 primes:
  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 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659

1000th through 1015th primes:
7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081
```


[User]
A recent discovery, quoted from   Quantamagazine   (March 13, 2016):

```
     Two mathematicians have uncovered a simple, previously unnoticed property of
     prime numbers — those numbers that are divisible only by 1 and themselves.
     Prime numbers, it seems, have decided preferences about the final digits of
     the primes that immediately follow them.

```

and

```
     This conspiracy among prime numbers seems, at first glance, to violate a
     longstanding assumption in number theory:  that prime numbers behave much
     like random numbers.

                            ─── (original authors from Stanford University):
                            ─── Kannan Soundararajan  and  Robert Lemke Oliver

```

The task is to check this assertion, modulo 10.

Lets call   `i -> j`    a transition if   `i`    is the last decimal digit of a prime, and   `j`    the last decimal digit of the following prime.

Task

Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions   `i -> j`    and print them along with their relative frequency, sorted by   `i` .

You can see that, for a given   `i` ,   frequencies are not evenly distributed.

Observation

(Modulo 10),   primes whose last digit is   **9**   "prefer"   the digit   **1**   to the digit   **9**,   as its following prime.

Extra credit

Do the same for one hundred million primes.

Example for 10,000 primes

```
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count:        365 frequency: 3.65 %
1 → 3 count:        833 frequency: 8.33 %
1 → 7 count:        889 frequency: 8.89 %
1 → 9 count:        397 frequency: 3.97 %
2 → 3 count:          1 frequency: 0.01 %
3 → 1 count:        529 frequency: 5.29 %
3 → 3 count:        324 frequency: 3.24 %
3 → 5 count:          1 frequency: 0.01 %
3 → 7 count:        754 frequency: 7.54 %
3 → 9 count:        907 frequency: 9.07 %
5 → 7 count:          1 frequency: 0.01 %
7 → 1 count:        655 frequency: 6.55 %
7 → 3 count:        722 frequency: 7.22 %
7 → 7 count:        323 frequency: 3.23 %
7 → 9 count:        808 frequency: 8.08 %
9 → 1 count:        935 frequency: 9.35 %
9 → 3 count:        635 frequency: 6.35 %
9 → 7 count:        541 frequency: 5.41 %
9 → 9 count:        379 frequency: 3.79 %

```

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.9

Using module `Math::Primesieve` to generate primes, as much faster than the built-in (but extra credit still very slow).

```
use Math::Primesieve;

my %conspiracy;
my $upto = 1_000_000;
my $sieve = Math::Primesieve.new;
my @primes = $sieve.n-primes($upto+1);

@primes[^($upto+1)].reduce: -> $a, $b {
    my $d = $b % 10;
    %conspiracy{"$a → $d count:"}++;
    $d;
}

say "$_ \tfrequency: {($_.value/$upto*100).round(.01)} %" for %conspiracy.sort;

```

Output:

```
1 → 1 count:	42853 	frequency: 4.29 %
1 → 3 count:	77475 	frequency: 7.75 %
1 → 7 count:	79453 	frequency: 7.95 %
1 → 9 count:	50153 	frequency: 5.02 %
2 → 3 count:	1 	frequency: 0 %
3 → 1 count:	58255 	frequency: 5.83 %
3 → 3 count:	39668 	frequency: 3.97 %
3 → 5 count:	1 	frequency: 0 %
3 → 7 count:	72828 	frequency: 7.28 %
3 → 9 count:	79358 	frequency: 7.94 %
5 → 7 count:	1 	frequency: 0 %
7 → 1 count:	64230 	frequency: 6.42 %
7 → 3 count:	68595 	frequency: 6.86 %
7 → 7 count:	39603 	frequency: 3.96 %
7 → 9 count:	77586 	frequency: 7.76 %
9 → 1 count:	84596 	frequency: 8.46 %
9 → 3 count:	64371 	frequency: 6.44 %
9 → 7 count:	58130 	frequency: 5.81 %
9 → 9 count:	42843 	frequency: 4.28 %
```


[User]
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.

Example

```
 12 = 2 × 2 × 3,  so its prime decomposition is  {2, 2, 3}

```

Task

Write a function which returns an array or collection which contains the prime decomposition of a given number

n
{\displaystyle {\displaystyle n}}
   greater than   **1**.

If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).

If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.

Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).

Related tasks

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

[Assistant]
(formerly Perl 6)

### Pure Raku

This is a pure Raku version that uses no outside libraries. It uses a variant of Pollard's rho factoring algorithm and is fairly performent when factoring numbers < 2⁸⁰; typically taking well under a second on an i7. It starts to slow down with larger numbers, but really bogs down factoring numbers that have more than 1 factor larger than about 2⁴⁰.

```
sub prime-factors ( Int $n where * > 0 ) {
    return $n if $n.is-prime;
    return () if $n == 1;
    my $factor = find-factor( $n );
    sort flat ( $factor, $n div $factor ).map: &prime-factors;
}

sub find-factor ( Int $n, $constant = 1 ) {
    return 2 unless $n +& 1;
    if (my $gcd = $n gcd 6541380665835015) > 1 { # magic number: [*] primes 3 .. 43
        return $gcd if $gcd != $n
    }
    my $x      = 2;
    my $rho    = 1;
    my $factor = 1;
    while $factor == 1 {
        $rho = $rho +< 1;
        my $fixed = $x;
        my int $i = 0;
        while $i < $rho {
            $x = ( $x * $x + $constant ) % $n;
            $factor = ( $x - $fixed ) gcd $n;
            last if 1 < $factor;
            $i = $i + 1;
        }
    }
    $factor = find-factor( $n, $constant + 1 ) if $n == $factor;
    $factor;
}

.put for (2²⁹-1, 2⁴¹-1, 2⁵⁹-1, 2⁷¹-1, 2⁷⁹-1, 2⁹⁷-1, 2¹¹⁷-1, 2²⁴¹-1,
5465610891074107968111136514192945634873647594456118359804135903459867604844945580205745718497)\
.hyper(:1batch).map: -> $n {
    my $start = now;
   "factors of $n: ",
    prime-factors($n).join(' × '), " \t in ", (now - $start).fmt("%0.3f"), " sec."
}
```

Output:

```
factors of 536870911:  233 × 1103 × 2089    in  0.004  sec.
factors of 2199023255551:  13367 × 164511353     in  0.011  sec.
factors of 576460752303423487:  179951 × 3203431780337       in  0.023  sec.
factors of 2361183241434822606847:  228479 × 48544121 × 212885833    in  0.190  sec.
factors of 604462909807314587353087:  2687 × 202029703 × 1113491139767       in  0.294  sec.
factors of 158456325028528675187087900671:  11447 × 13842607235828485645766393       in  0.005  sec.
factors of 166153499473114484112975882535043071:  7 × 73 × 79 × 937 × 6553 × 8191 × 86113 × 121369 × 7830118297      in  0.022  sec.
factors of 3533694129556768659166595001485837031654967793751237916243212402585239551:  22000409 × 160619474372352289412737508720216839225805656328990879953332340439     in  0.085  sec.
factors of 5465610891074107968111136514192945634873647594456118359804135903459867604844945580205745718497:  165901 × 10424087 × 18830281 × 53204737 × 56402249 × 59663291 × 91931221 × 95174413 × 305293727939 × 444161842339 × 790130065009     in  28.427  sec.
```

There is a Raku module available: Prime::Factor, that uses essentially this algorithm with some minor performance tweaks.

### External library

If you really need a speed boost, load the highly optimized Perl 5 ntheory module. It needs a little extra plumbing to deal with the lack of built-in big integer support, but for large number factoring the interface overhead is worth it.

```
use Inline::Perl5;
my $p5 = Inline::Perl5.new();
$p5.use( 'ntheory' );

sub prime-factors ($i) {
    my &primes = $p5.run('sub { map { ntheory::todigitstring $_ } sort {$a <=> $b} ntheory::factor $_[0] }');
    primes("$i");
}

for 2²⁹-1, 2⁴¹-1, 2⁵⁹-1, 2⁷¹-1, 2⁷⁹-1, 2⁹⁷-1, 2¹¹⁷-1,
5465610891074107968111136514192945634873647594456118359804135903459867604844945580205745718497
 ->  $n {
    my $start = now;
    say "factors of $n: ",
    prime-factors($n).join(' × '), " \t in ", (now - $start).fmt("%0.3f"), " sec."
}
```

Output:

```
factors of 536870911: 233 × 1103 × 2089     in 0.001 sec.
factors of 2199023255551: 13367 × 164511353      in 0.001 sec.
factors of 576460752303423487: 179951 × 3203431780337    in 0.001 sec.
factors of 2361183241434822606847: 228479 × 48544121 × 212885833     in 0.012 sec.
factors of 604462909807314587353087: 2687 × 202029703 × 1113491139767    in 0.003 sec.
factors of 158456325028528675187087900671: 11447 × 13842607235828485645766393    in 0.001 sec.
factors of 166153499473114484112975882535043071: 7 × 73 × 79 × 937 × 6553 × 8191 × 86113 × 121369 × 7830118297   in 0.001 sec.
factors of 5465610891074107968111136514192945634873647594456118359804135903459867604844945580205745718497: 165901 × 10424087 × 18830281 × 53204737 × 56402249 × 59663291 × 91931221 × 95174413 × 305293727939 × 444161842339 × 790130065009      in 0.064 sec.

```