title: My god, it's full of spaces!

text:
# Question
Title: My god, it's full of spaces!
Some people insist on using spaces for tabulation and indentation.

For tabulation, that's indisputably wrong. By definition, tabulators must be used for tabulation.

Even for indentation, tabulators are objectively superior:

* There's clear consensus in the Stack Exchange community.
* Using a single space for indentation is visually unpleasant; using more than one is wasteful.

As all cod~~e golf~~ers know, programs should be as short as possible. Not only does it save hard disk space, compilation times are also reduced if less bytes have to be processed.
* By adjusting the tab width1, the same file looks different on each computer, so everybody can use his favorite indent width without modifying the actual file.
* All good text editors use tabulators by default (and definition).
* I say so and I'm always right!

Sadly, not everybody listens to reason. Somebody has sent you a file that is doing it wrongTM and you have to fix it. You could just do it manually, but there will be others.

It's bad enough that spacers are wasting your precious time, so you decide to write the shortest possible program to take care of the problem.

### Task

Write a program or a function that does the following:

1. Read a single string either from STDIN or as a command-line or function argument.
2. Identify all locations where spaces have been used for tabulation or indentation.

A run of spaces is **indentation** if it occurs at the beginning of a line.

A run of *two or more* spaces is **tabulation** if it isn't indentation.

A *single* space that is not indentation may or may not have been used for tabulation. As expected when you use the same character for different purposes, there's no easy way to tell. Therefore, we'll say that the space has been used for **confusion**.
3. Determine the longest possible tab width1 for which all spaces used for tabulation or indentation can be replaced with tabulators, without altering the appearance of the file.

If the input contains neither tabulation, nor indentation, it is impossible to determine the tab width. In this case, skip the next step.
4. Using the previously determined tab width, replace all spaces used for tabulation or indentation with tabulators.

Also, whenever possible without altering the appearance of the file, replace all spaces used for confusion with tabulators. (If in doubt, get rid of spaces.)
5. Return the modified string from your function or print it to STDOUT.

### Examples

* All spaces of

```
a    bc   def  ghij

```

are tabulation.

Each run of spaces pads the preceding string of non-space characters to a width of 5, so the correct tab width is 5 and the correct output2 is

```
a--->bc-->def->ghij

```
* The first two spaces of

```
ab  cde f
ghi jk lm

```

are tabulation, the others confusion.

The correct tab width is 4, so the correct output2 is

```
ab->cde>f
ghi>jk lm

```

The last space remains untouched, since it would be rendered as *two* spaces if replaced by a tabulator:

```
ab->cde>f
ghi>jk->lm

```
* All but one spaces of

```
int
    main( )
    {
        puts("TABS!");
    }

```

are indentation, the other is confusion.

The indentation levels are 0, 4 and 8 spaces, so the correct tab width is 4 and the correct output2 is

```
int
--->main( )
--->{
--->--->puts("TABS!");
--->}

```

The space in `( )` would be rendered as three spaces if replaced by a tabulator, so it remains untouched.
* The first two spaces of

```
  x yz w

```

are indentation, the others confusion.

The proper tab width is 2 and the correct output2 is

```
->x>yz w

```

The last space would be rendered as two spaces if replaced by a tabulator, so it remains untouched.
* The first two spaces of

```
  xy   zw

```

are indentation, the other three are tabulation.

Only a tab width of 1 permits to eliminate all spaces, so the correct output2 is

```
>>xy>>>zw

```
* All spaces of

```
a b c d

```

are confusion.

There is no longest possible tab width, so the correct output2 is

```
a b c d

```

### Additional rules

* The input will consist entirely of printable ASCII characters and linefeeds.
* You may assume that there are at most 100 lines of text and at most 100 characters per line.
* If you choose STDOUT for output, you may print a single trailing linefeed.
* Standard rules apply.

---

1 The tab width is defined as the distance in characters between two consecutive tab stops, using a monospaced font.
2 The ASCII art arrows represent the tabulators Stack Exchange refuses to render properly, for which I have submitted a bug report. The actual output has to contain actual tabulators.

# Answer
> 5 votes
# Pyth, ~~102~~ 103 bytes

```
=T|u?<1hHiGeHGsKmtu++J+hHhGlhtH+tG]+HJ.b,YN-dk<1u+G?H1+1.)Gd]0]0cR\ .zZ8VKVNp?%eNT*hNd*/+tThNTC9p@N1)pb

```

Try it Online

Interesting idea, but since tabs in the input break the concept, not very usable.

Edit: Fixed bug. many thanks @aditsu

# Answer
> 5 votes
# PowerShell, ~~414~~ 409 bytes

```
function g($a){if($a.length-gt2){g $a[0],(g $a[1..100])}else{if(!$a[1]){$a[0]}else{g $a[1],($a[0]%$a[1])}}}{$a[0]}else{g $a[1],($a[0]%$a[1])}}}
$b={($n|sls '^ +|(?<!^)  +' -a).Matches}
$n=$input-split"`n"
$s=g(&$b|%{$_.Index+$_.Length})
($n|%{$n=$_
$w=@(&$b)
$c=($n|sls '(?<!^| ) (?! )'-a).Matches
$w+$c|sort index -d|%{$x=$_.Index
$l=$_.Length
if($s-and!(($x+$l)%$s)){$n=$n-replace"(?<=^.{$x}) {$l}",("`t"*(($l/$s),1-ge1)[0])}}
$n})-join"`n"

```

I went ahead and used newlines instead of `;` where possible to make display easier. I'm using unix line endings so it shouldn't affect the byte count.

## How To Execute

Copy code into `SpaceMadness.ps1` file, then pipe the input into the script. I will assume the file that needs converting is called `taboo.txt`:

From PowerShell:

```
cat .\taboo.txt | .\SpaceMadness.ps1

```

From command prompt:

```
type .\taboo.txt | powershell.exe -File .\SpaceMadness.txt

```

I tested it with PowerShell 5, but it should work on 3 or higher.

## Testing

Here's a quick PowerShell scrip that's useful for testing the above:

```
[CmdletBinding()]
param(
    [Parameter(
        Mandatory=$true,
        ValueFromPipeline=$true
    )]
    [System.IO.FileInfo[]]
    $File
)

Begin {
    $spaces = Join-Path $PSScriptRoot SpaceMadness.ps1
}

Process {
     $File | ForEach-Object {
        $ex = Join-Path $PSScriptRoot $_.Name
        Write-Host $ex -ForegroundColor Green
        Write-Host ('='*40) -ForegroundColor Green
        (gc $ex -Raw | & $spaces)-split'\r?\n'|%{[regex]::Escape($_)} | Write-Host -ForegroundColor White -BackgroundColor Black
        Write-Host "`n"
    }
}

```

Put this in the same directory as `SpaceMadness.ps1`, I call this one `tester.ps1`, call it like so:

```
"C:\Source\SomeFileWithSpaces.cpp" | .\tester.ps1
.\tester.ps1 C:\file1.txt,C:\file2.txt
dir C:\Source\*.rb -Recurse | .\tester.ps1

```

You get the idea. It spits out the contents of each file after conversion, run through `[RegEx]::Escape()` which happens to escape both spaces and tabs so it's really convenient to see what's actually been changed.

The output looks like this (but with colors):

```
C:\Scripts\Powershell\Golf\ex3.txt
========================================
int
\tmain\(\ \)
\t\{
\t\tputs\("TABS!"\);
\t}

```

# Explanation

The very first line defines a greatest common factor/divisor function `g` as succinctly as I could manage, that takes an array (arbitrary number of numbers) and calculates GCD recursively using the Euclidean algorithm.

The purpose of this was to figure out the "longest possible tab width" by taking the index + length of every **indentation** and **tabulation** as defined in the question, then feeding it to this function to get the GCD which I think is the best we can do for tab width. A confusion's length will always be 1 so it contributes nothing to this calculation.

`$b` defines a scriptblock because annoyingly I need to call that piece of code twice, so I save some bytes that way. This block takes the string (or array of strings) `$n` and runs a regex on it (`sls` or `Select-String`), returning match objects. I'm actually getting both indentations and tabulations in one here, which really saved me extra processing by capturing them separately.

`$n` is used for different things inside and outside the main loop (really bad, but necessary here so that I can embed it in `$b`'s scriptblock and use that both inside and outside the loop without a lengthy `param()` declaration and passing arguments.

`$s` gets assigned the tab width, by calling the `$b` block on the array of lines in the input file, then summing the index and length of each match, returning the array of the sums as an argument into the GCD function. So `$s` has the size of our tab stops now.

Then the loop starts. We iterate over each line in the array of input lines `$n`. The first thing I do in the loop is assign `$n` (local scope) the value of the current line for the above reason.

`$w` gets the value of the scriptblock call for the current line only (the indentations and tabulations for the current line).

`$c` gets a similar value, but instead we find all the **confusions**.

I add up `$w` and `$c` which are arrays, giving me one array with all of the space matches I need, `sort` it in descending order by index, and begin iterating over each match for the current line.

The sort is important. Early on I found out the hard way that replacing parts of a string based on index values is a bad idea when the replacement string is smaller and changes the length of the string! The other indexes get invalidated. So by starting with the highest indexes on each line, I make sure I only make the string shorter from the end, and move backwards so the indexes always work.

Into this loop, `$x` is in the index of the current match and `$l` is the length of the current match. `$s` can in fact be `0` and that causes a pesky divide by zero error so I'm checking for its validity then doing the math.

The `!(($x+$l)%$s)` bit there is the single point where I check to see if a **confusion** should be replaced with a tab or not. If the index plus the length divided by the tab width has no remainder, then we're good to go in replacing this match with a tab (that math will always work on the **indentations** and **tabulations**, because their size is what determined the tab width to begin with).

For the replace, each iteration of the match loop works on the current line of the input, so it's a cumulative set of replaces. The regex just looks for `$l` spaces that are preceded by `$x` of any character. We replace it with `$l/$s` tab characters (or 1 if that number is below zero).

This part `(($l/$s),1-ge1)[0]` is a fancy convoluted way of saying `if (($l/$s) -lt 0) { 1 } else { $l/$s }` or alternatively `[Math]::Max(1,($l/$s))`. It makes an array of `$l/$s` and `1`, then uses `-ge 1` to return an array containing only the elements that are greater than or equal to one, then takes the first element. It comes in a few bytes shorter than the `[Math]::Max` version.

So once all of the replaces are done, the current line is returned from the `ForEach-Object` (`%`) iteration, and when all of them are returned (an array of fixed lines), it's `-join`ed with newlines (since we split on newlines in the beginning).

I feel like there's room for improvement here that I'm too burnt out to catch right now, but maybe I'll see something later.

> Tabs 4 lyfe

# Answer
> 4 votes
## PHP - ~~278~~ 210 bytes

The function works by testing each tab width, starting with a value of 100, the maximal length of a line and therefore the maximal tab width.

For each tab width, we split each line into "blocks" of that length. For each of this blocks:

* If, by concatenating the last character of the previous block with this block, we find two consecutive spaces before a character, we have an indentation or a tabulation that can't be transformed to space without altering the appearance; we try the next tab width.
* Otherwise, if the last character is a space, we strip spaces at end of the block, add a tabulator and memorise the whole thing.
* Otherwise, we just memorise the block.

Once each blocks of a line have been analysed, we memorise a linefeed. If all the blocks of all the lines were analysed with success, we return the string we've memorised. Otherwise, if each strictly positive tab width have been tried, there was neither tabulation, nor indentation, and we return the original string.

```
function($s){for($t=101;--$t;){$c='';foreach(split('
',$s)as$l){$e='';foreach(str_split($l,$t)as$b){if(ereg('  [^ ]',$e.$b))continue 3;$c.=($e=substr($b,-1))==' '?rtrim($b).'   ':$b;}$c.='
';}return$c;}return$s;}

```

Here is the ungolfed version:

```
function convertSpacesToTabs($string)
{
    for ($tabWidth = 100; $tabWidth > 0; --$tabWidth)
    {
        $convertedString = '';
        foreach (explode("\n", $string) as $line)
        {
            $lastCharacter = '';
            foreach (str_split($line, $tabWidth) as $block)
            {
                if (preg_match('#  [^ ]#', $lastCharacter.$block))
                {
                    continue 3;
                }

                $lastCharacter = substr($block, -1);
                if ($lastCharacter == ' ')
                {
                    $convertedString .= rtrim($block) ."\t";
                }
                else
                {
                    $convertedString .= $block;
                }
            }

            $convertedString .= "\n";
        }

        return $convertedString;
    }

    return $string;
}

```

Special thanks to DankMemes for saving 2 bytes.

# Answer
> 4 votes
# CJam, 112

```
qN/_' ff=:e`{0:X;{_0=X+:X+}%}%_:+{~;\(*},2f=0\+{{_@\%}h;}*:T;\.f{\~\{@;1$({;(T/)9c*}{\;T{T%}&S9c?}?}{1$-@><}?}N*

```

Try it online

I had to answer this challenge, because I must do my part to help rid the world of this abomination. Tabs are obviously superior, but sadly, some people just can't be reasoned with.

**Explanation:**

```
qN/          read input and split into lines
_            duplicate the array (saving one copy for later)
' ff=        replace each character in each line with 0/1 for non-space/space
:e`          RLE-encode each line (obtaining chunks of spaces/non-spaces)
{…}%         transform each line
  0:X;       set X=0
  {…}%       transform each chunk, which is a [length, 0/1] array
    _0=      copy the first element (the length)
    X+:X     increment X by it
    +        and append to the array; this is the end position for the chunk
_            duplicate the array (saving one copy for later)
:+           join the lines (putting all the chunks together in one array)
{…},         filter the array using the block to test each chunk
  ~          dump the chunk (length, 0/1, end) on the stack
  ;          discard the end position
  \(         bring the length to the top and decrement it
  *          multiply the 2 values (0/1 for non-space/space, and length-1)
              the result is non-zero (true) iff it's a chunk of at least 2 spaces
2f=          get all the end positions of the multiple-space chunks
0\+          prepend a 0 to deal with the empty array case
{…}*         fold the array using the block
  {_@\%}h;   calculate gcd of 2 numbers
:T;          save the resulting value (gcd of all numbers) in variable T
\            swap the 2 arrays we saved earlier (input lines and chunks)
.f{…}        for each chunk and its corresponding line
  \~         bring the chunk to the top and dump it on the stack
              (length, 0/1, end position)
  \          swap the end position with the 0/1 space indicator
  {…}        if 1 (space)
    @;       discard the line text
    1$(      copy the chunk length and decrement it
    {…}      if non-zero (multiple spaces)
      ;      discard the end position
      (T/)   divide the length by T, rounding up
      9c*    repeat a tab character that many times
    {…}      else (single space)
      \;     discard the length
      T{…}&  if T != 0
        T%   calculate the end position mod T
      S9c?   if non-zero, use a space, else use a tab
    ?        end if
  {…}        else (non-space)
    1$-      copy the length and subtract it from the end position
              to get the start position of the chunk
    @>       slice the line text beginning at the start position
    <        slice the result ending at the chunk length
              (this is the original chunk text)
  ?          end if
N*           join the processed lines using a newline separator

```

# Answer
> 1 votes
# PowerShell, ~~165~~ ~~160~~ ~~153~~ ~~152~~ ~~142~~ ~~138~~ 137 bytes

```
param($s)@((0..99|%{$s-split"(
|..{0,$_})"-ne''-replace(' '*!$_*($s[0]-ne32)+' +$'),"`t"-join''})-notmatch'(?m)^ |\t '|sort{$_|% Le*})[0]

```

Try it online!

Less golfed:

```
param($spacedString)

$tabed = 0..99|%{
    $spacedString `
        -split "(\n|..{0,$_})" -ne '' `
        -replace (' '*!$_*($spacedString[0]-ne32)+' +$'),"`t" `
        -join ''
}

$validated = $tabed -notmatch '(?m)^ |\t '

$sorted = $validated|sort{$_|% Length}    # sort by a Length property

@($sorted)[0]  # $shortestProgram is an element with minimal length

```

---
Tags: code-golf, string, conversion, whitespace
---


title: ASCII Maze Compression

text:
# Question
Title: ASCII Maze Compression
# Challenge

Design a compression algorithm specialized for compressing ASCII mazes. You will need to create both a compression algorithm and a decompression algorithm. Your score will be based on the size of your compressed mazes.

# Mazes

These mazes are made primarily of the characters  (floors), `+`, `-`, `|`, and `#` (walls), and *exactly one* each of `^` (start) and `$` (end). They may also contain ASCII letters, which count as floor tiles. For the purposes of this challenge, mazes do not have to be solvable and the actual meaning of maze contents is irrelevant.

* `+` will be used for wall cells where there is at least one horizontally adjacent wall cell and at least one vertically adjacent wall cell.
* `|` will be used for wall cells where there is at least one vertically adjacent wall cell, but no horizontally adjacent wall cells.
* `-` will be used for wall cells where there is at least one horizontally adjacent wall cell, but no vertically adjacent wall cells
* `#` will only be used for wall cells that are not orthogonally adjacent to other wall cells.

All mazes are rectangular, but do not necessarily have a regular grid/wall alignment.

# Mazes To Compress

Maze 1

```
+----+----
|  o |    |
| -- | o--+
|    | |  $
 --^-+-+---

```

Maze 2

```
+-----+---+
|  a  |   |
^ +-+-+ # |
| | |  B  |
| | | --+ |
|   c   | $
+-------+--

```

Maze 3

```
----------+-+-+-----+-+
^         | | |     | |
+-- --+R #  | |p| | | |
|     | |       | |   |
+---+ +-+-+-- +-+ | | |
|  m| | | |   |   | | |
| +-+ | | | | | --+ | |
| | |    h  | |   | | |
| | | | | |  #  --+-+ |
|     | | | | |  S|   $
+-----+-+-+-+-+---+----

```

Maze 4

```
+-----+---+-+---+-------^-----+
|     |x  | |   |     tsrq    |
+-+-- +-- | +--  #  --+---- --+
| |   |           |   |       |
| | | | | +-+-+---+ | +-- | +-+
| | | u | | | |     | |   | | |
| +-+ | | | | +---- +-+---+ | |
| |   | |   |    y  |       w |
| | --+ | --+ +-- | +---- | | |
|     | |   | |   | |     | | |
+-- --+ +-+ | | | | +-- | +-+-+
|     | | |   | | | |   |     |
$ | --+-+ | --+-+ | +-+-+-- --+
| |   |      z|   |   |    v  |
+-+---+-------+---+---+-------+

```

Maze 5

```
++ -----------+
++-       Beep|
$  ----+---+--+
+-+boop|   |  |
| +--- | | | ++
|      | |  +++
+------+-+--+ ^

```

Maze 6

```
+-$---------------+-+--
|                 | |j
| |l ---- # ---+ |  |
| | |       m  | +--+ |
| | | +-+---- #       |
| | | | |      +----+ |
|o| | | | +----+    | |
|       | |    | -- | |
| | | | | | -+ |    | |
| | | | |  | | +--- | |
| | | | +- | | |   | ++
+-+ |n| |  | ++ +--+ |
    | |   -+- | |  | +-
+---+ +---    |  | |  ^
|    |     --+ --+ | |
| -- | |  k  |     | ++
|    | |      +--- | ++
|    |      | |    |  |
+-- -+----  | +----+--+

```

Maze 7

```
+---+-+-------------+-+^+-----+-------+---+-+---+-+---+-+---+
|   |c|             | | |  c  |       |   | |   | |   |c|   |
+-- | | +-- +-- # | | | +-- --+ +---- +-- | +-+ | | +-+ | --+
|       |   |     | |           |         |   | |c| |       |
| | +-- | +-+-- +-+ +-- # +- # -+-- +-- | | --+ | | | | --+C|
|c| |   | | c   |         |         |c  |             |   | |
+-+-+---+-+-----+---------+---------+---+-------------+---+$|

```

Maze 8

```
------+-+-+---+-+---+-----------+---+-----+---------------+-+
^     | | |   | |   |           |   |     |      r        | |
+-- | | | t | | +-- +----- # ---+-- +-- --+-- ----+-+ --+ | |
|   |   | | |   |   |         r |   |             | |   |   |
| | | | | +-+ --+ --+-- --------+-- | ----+ --+ | | | --+ | |
| |r| |            rotation               |   | |   |   | | $
+-+-+-+-----------------------------------+---+-+---+---+-+--

```

Maze 9

```
|$|^--+-+---+-----+-+---+-+-+---+---+-+---+-----+
| |   | |   |     | |   | | | f |   | |   |     |
| +-+ | | # +-+ --+ +-+ | | | # | +-+ +-- | ----+
|   |       | |    f| |           | | |   |   f |
| |F+-+ | | | | +---+ | | | ----+-+ | | --+ --+-+
| |   | | |     |     | | |   f |   |         | |
| | | | +-+-+---+-- | | | +-+-+-+ +-+ +--- # -+ |
| | | |     |   |   |   | | | |   | | |         |
+-+-+ | +---+ --+ | +---+-+ | | --+ f | | | | --+
|     | |         |                 | | | | |   |
| --+f| | | +-- --+--f--+ --+ | ----+ | +-+ +---+
|   |     | |     |     |   | |           |     |
+---+-----+-+-----+-----+---+-+-----------+-----+

```

Maze 10

```
+-----+-+-----------+
|  q  | |         q |
|Q+-+ | +-+-+-+---- |
$ | |     | | |  q  |
+-+ | | | | | +-- +-+
| |   | |     |   | |
| +-- +-+ |q| +-+ | |
|    q|   | |   |   |
| | | +-- | +-+ | --+
| | | |   | | |     |
+-+-+-+ +-+-+ +-- | |
|       |         | |
+--- # -+ | | +-- | |
|  q      | | |   | ^
+-+ +-- | | +-+ | +-+
| | |   | |q|   |   |
| +-+-+ | +-+-- | | |
|     | | |     | | |
| | | +-+-+-- +-+ +-+
| | |         | q   |
+-+-+---------+-----+

```

# Rules, Assumptions, Scoring

* Standard loopholes are banned
    + Write a general program, not one that only works for the ten test cases. It must be able to handle any arbitrary maze.
* You may assume there will be exactly one entrance and one exit. Entrances and exits will always be on the border of the maze.
* You may assume that all inputs use walls that follow the rules enumerated above. Your compression algorithm does not have to work for mazes containing walls that violate those rules.
* Input mazes may or may not be solvable.
* You may assume the maze will be no larger than 100 characters in either direction.
* You may assume that letters will not appear on the edge of the maze. (since this is the case for the examples provided)
* Your score is the total size, in bytes (octets), of all of the compressed mazes.
    + You may use hex, base64, binary strings, or any similar format as a representation for your compressed maze if you find that more convenient. You should still count the result in whole octets, rounded up for each maze (e.g. 4 base64 digits is 3 bytes, 2 hex digits is 1 byte, 8 binary digits is 1 byte, etc...)
    + Lowest score wins!

# Answer
> 5 votes
# JavaScript (Node.js), score =  ~~586 541 503 492~~  479 bytes

The walls are stored as a Huffman-encoded stream of bits describing whether a prediction function is returning the correct guess or not.

The special characters are stored as \\$(d, c)\\$, where \\$d\\$ is the distance from the previous special character and \\$c\\$ is the ASCII code.

Try it online!

### Common

```
const HUFFMAN = [
  '00',       // 0000
  '010',      // 0001
  '1001',     // 0010
  '11100',    // 0011
  '011',      // 0100
  '101',      // 0101
  '11110',    // 0110
  '100010',   // 0111
  '110',      // 1000
  '11101',    // 1001
  '1111100',  // 1010
  '1111101',  // 1011
  '10000',    // 1100
  '1111110',  // 1101
  '100011',   // 1110
  '1111111'   // 1111
];

let bin = (n, w) => n.toString(2).padStart(w, '0');

let wallShape = (row, x, y) => {
  let vWall = (row[y - 1] || [])[x] | (row[y + 1] || [])[x],
      hWall = row[y][x - 1] | row[y][x + 1];

  return ' -|+'[row[y][x] ? vWall * 2 | hWall : 0];
}

let predictWall = (row, x, y, w, h) => {
  let prvRow = row[y - 1] || [];
  return !x | !y | x == w - 1 | y == h - 1 | (prvRow[x] | row[y][x - 1]) & !prvRow[x - 1];
}

```

### Compression

```
let pack = str => {
  let row = str.split('\n').map(r => [...r]),
      w = row[0].length,
      h = row.length;

  let wall = row.map((r, y) => r.map((c, x) => +/[-+|]/.test(c)));

  if(row.some((r, y) => r.some((c, x) => wall[y][x] && wallShape(wall, x, y) != c))) {
    throw "invalid maze";
  }

  row = wall.map((r, y) => r.map((v, x) => predictWall(wall, x, y, w, h) ^ v));
  row = row.map(r => r.join('')).join('');
  row = row.replace(/.{1,4}/g, s => HUFFMAN[parseInt(s.padEnd(4, '0'), 2)]);

  str =
    str.replace(/[\n|+-]/g, '').replace(/ *(\S)/g, (s, c) => {
      let n = c.charCodeAt(),
          i = '^$#'.indexOf(c);

      return (
        bin(s.length > 63 ? 0xFC000 | s.length - 1 : s.length - 1, 6) +
        bin(~i ? i : n < 91 ? (n > 80 ? 0x1F0 : 0x1E0) | ~-n & 15 : n - 94, 5)
      );
    }).trim();

  return (
    Buffer.from(
      (bin(w, 7) + bin(h, 7) + row + str)
      .match(/.{1,8}/g).map(s => parseInt(s.padEnd(8, '0'), 2))
    ).toString('binary')
  );
}

```

### Decompression

```
let unpack = str => {
  str = [...str].map(c => bin(c.charCodeAt(), 8)).join('');

  let x, y, n, i, s,
      ptr = 0,
      read = n => parseInt(str.slice(ptr, ptr += n), 2),
      w = read(7),
      h = read(7),
      row = [];

  for(x = s = ''; s.length < w * h;) {
    ~(i = HUFFMAN.indexOf(x += read(1))) && (s += bin(i, 4), x = '');
  }
  for(i = y = 0; y < h; y++) {
    for(row[y] = [], x = 0; x < w; x++) {
      row[y][x] = predictWall(row, x, y, w, h) ^ s[i++];
    }
  }

  row = row.map((r, y) => r.map((c, x) => wallShape(row, x, y)));

  for(i = 0; str[ptr + 10];) {
    for(
      n = (n = read(6)) == 0x3F ? read(14) + 1 : n + 1;
      n -= row[i / w | 0][i % w] == ' ';
      i++
    ) {}

    row[i / w | 0][i % w] = String.fromCharCode(
      (n = read(5)) >= 0x1E ? read(4) + (n == 0x1F ? 81 : 65) : [94, 36, 35][n] || n + 94
    );
  }
  return row.map(r => r.join('')).join('\n');
}

```

## How?

A maze is encoded as a bit stream which is eventually converted to a string.

### Header

The header consists of:

* the width \\$w\\$ on 7 bits
* the height \\$h\\$ on 7 bits

### Wall data

We walk through the entire maze and attempt to predict if the next cell is a wall or not, based on the previously encountered cells. We emit a \\$0\\$ if we are correct, or a \\$1\\$ if we are wrong.

This results in a sequence of correction bits with (hopefully) significantly more \\$0\\$'s than \\$1\\$'s. This sequence is split into nibbles and stored using hard-coded Huffman codes:

* `00``0000`
* `010``0001`
* `1001``0010`
* `11100``0011`
* `011``0100`
* etc.

To decode the wall \\$W\_n\\$, the decompression routine computes the same prediction \\$P\_n\\$ and toggles the result if needed, using the correction bit \\$C\_n\\$:

$$W\_n=P\_n\oplus C\_n$$

The final wall shapes are deduced in a way that is similar to Nick Kennedy's answer.

### Special characters

Each special characters is encoded as:

* The distance minus \\$1\\$ from the last special character (ignoring the walls):

+ on 6 bits if it's less than \\$63\\$
    + or as \\$111111\\$ \+ 14 bits otherwise (never used in the test cases, but required in theory)
* The code of the character:

+ on 5 bits if it's `^`, `$`, `#` or `[a-z]`
    + or \\$11110\\$ \+ 4 bits for `[A-O]`
    + or \\$11111\\$ \+ 4 bits for `[P-Z]`

# Answer
> 4 votes
# R, score 668 bytes

This takes advantage of the fact that the wall character is determined by its surroundings. As such, wall characters can be encoded as bits. The remaining info that needs to be stored are the dimensions of the maze, the positions of the start and finish and the positions of any other non-wall characters. Since the non-wall characters are ASCII, I've used the most significant bit of each byte to indicate whether there is another character that follows so that some of the words in the mazes don't have to have the location of each character stored separately. Note also that for mazes less than or equal to 256 characters (e.g. up to 16x16 or equivalent rectangular mazes), the positions can be stored in one byte, whereas for larger mazes the positions need two bytes.

### Utility functions

```
r <- as.raw

int_as_raw <- function(int, bytes = 2) {
  if (bytes == 1) {
    r(int)
  } else {
    do.call(c, lapply(int, function(.x) r(c(.x %/% 256, .x %% 256))))
  }
}

raw_as_int <- function(raw, bytes = 2) {
  if (bytes == 1) {
    as.integer(raw)
  } else {
    sapply(
      seq(1, length(raw) - 1, 2),
      function(.x) as.integer(as.integer(raw[.x + 0:1]) %*% c(256, 1))
    )
  }
}

```

### Compression algorithm

```
compress_maze <- function(maze) {
  maze_array <- do.call(rbind, strsplit(maze, ""))
  simple_maze <- r(maze_array %in% c("+", "#", "-", "|"))
  simple_maze <- packBits(c(simple_maze, rep(r(0), (8 - length(simple_maze)) %% 8)))
  maze_dim <- int_as_raw(dim(maze_array), 1)
  bytes_needed <- 1 + (length(maze_array) > 256)
  start_finish <- int_as_raw(sapply(c("^", "$"), function(.x) which(maze_array == .x)) - 1, bytes = bytes_needed)
  other_ascii_locs_rle <- rle(!(maze_array %in% c(" ", "+", "#", "-", "|", "$", "^")))
  other_ascii_locs <- cumsum(
    c(1, other_ascii_locs_rle$lengths[-length(other_ascii_locs_rle$lengths)])
  )[other_ascii_locs_rle$values]
  other_ascii_locs_length <- other_ascii_locs_rle$lengths[other_ascii_locs_rle$values]

  encode_ascii <- function(loc, len) {
    text <- charToRaw(paste(maze_array[loc:(loc + len - 1)], collapse = ""))
    if (len > 1) {
      text[1:(len - 1)] <- text[1:(len - 1)] | r(128)
    }
    c(int_as_raw(loc - 1, bytes = bytes_needed), text)
  }

  other_ascii_encoded <- Map(encode_ascii,
    other_ascii_locs,
    other_ascii_locs_length
    )
  other_ascii_encoded <- do.call(c, other_ascii_encoded)
  c(maze_dim, simple_maze, start_finish, other_ascii_encoded)
}

```

### Decompression algorithm

```
decompress_maze <- function(c_maze) {
  dim_maze <- as.integer(c_maze[1:2])
  len_maze <- prod(dim_maze)
  len_maze_b <- ceiling(len_maze / 8)
  bit_maze <- rawToBits(c_maze[-(1:2)])[1:len_maze]
  dim(bit_maze) <- dim_maze
  bit_maze[-1, ] <- bit_maze[-1, ] | rawShift(bit_maze[-nrow(bit_maze), ] & r(1), 1)
  bit_maze[-nrow(bit_maze), ] <- bit_maze[-nrow(bit_maze), ] | rawShift(bit_maze[-1, ] & r(1), 1)
  bit_maze[, -1] <- bit_maze[, -1] | rawShift(bit_maze[, -ncol(bit_maze)] & r(1), 2)
  bit_maze[, -ncol(bit_maze)] <- bit_maze[, -ncol(bit_maze)] | rawShift(bit_maze[, -1] & r(1), 2)
  bit_maze[(bit_maze & r(1)) == r(0)] <- r(0)
  array_maze <- c(" ", "#", "|", "-", "+")[(as.integer(bit_maze) + 1) %/% 2 + 1]
  dim(array_maze) <- dim_maze
  bytes_needed <- 1 + (len_maze > 256)
  start_finish <- raw_as_int(c_maze[2 + len_maze_b + 1:(bytes_needed * 2)], bytes_needed) + 1
  array_maze[start_finish] <- c("^", "$")
  i <- 3 + len_maze_b + 2 * bytes_needed
  while (i < length(c_maze)) {
    loc <- raw_as_int(c_maze[i + 1:bytes_needed - 1], bytes_needed) + 1
    i <- i + bytes_needed
    text <- character(0)
    while (c_maze[i] & r(128)) {
      text <- c(text, rawToChar(c_maze[i] & r(127)))
      i <- i + 1
    }
    text <- c(text, rawToChar(c_maze[i]))
    array_maze[loc:(loc + length(text) - 1)] <- text
    i <- i + 1
  }
  apply(array_maze, 1, paste, collapse = "")
}

```

Try it online!

---
Tags: ascii-art, code-challenge, compression, maze
---


# Question
Title: Which were the latest 13 consecutive years with the most friday 13. in total?
Shortest program wins, of course.

# Answer
> 1 votes
# Wolfram Language 171 bytes

Any modern 13-year interval will have between 20 and 24 Friday the 13ths.

```
SortBy[{{#[[1,1]],#[[-1,1]]},Total[#[[2]]&/@#]}&/@Partition[Table[{y,Length@Cases[DateObject@{y,m,13}~Table~{m,12},x_/;DayName@x==Friday]},{y,1900,2019}],13,1],Last][[-1]]

* {{2007, 2019}, 24} *)

```

The above generates all the Friday the 13ths for each year between 1900 and 2019, partitions the results into intervals of 13 years, and finds the total for each such interval. The interval of 2007-2019 has 24, the maximum number of Friday the 13ths.

If 2019 cannot be used, the correct answer will be the interval of 200-2018, which also contains 24 Friday the 13ths.

---
Tags: code-golf, date
---


title: Answer-Chaining Fibonacci

text:
# Question
Title: Answer-Chaining Fibonacci
*(Inspired by ASCII's 95 Characters...95 Movie Quotes)*

## The Challenge

Given input `n`, output the `nth` Fibonacci number. You can use either `0` or `1` indexing, please state which in your submission. Simple, yeah? The catch is you must take the character set of the immediate previous answer, remove two characters from it, and add a separate character. The separate character must

* *not* be from the immediate previous answer's character set
* be from the set of (printable ASCII, space, newline, horizontal tab)

and thus your total character set size will be *exactly* one smaller than the immediate previous answer's set.

## The initial answer

The first submission must contain a subset of (all printable ASCII, space, newline, and horizontal tab) with two characters removed. Every submission thereafter must restrict their answers to this original ASCII-only format (meaning you can't add a Unicode or extended-ASCII character ... sorry Jelly, APL, et al.).

## Examples and Clarifications

* Suppose the first answer is in C and contains (almost all printable ASCII, newline, and horizontal tab), and omits the `%` and `^` from its character set. The second submission, then, must remove two characters from the previous (almost all printable ASCII, newline, and horizontal tab) character set and add in either the `%` or `^`. Perhaps it's a one-liner PowerShell answer that omits the newline. And so on.
* If the previous answer had `print(){}!*+` as its character set (12 characters), your submission could have `print(){}!` (10 characters) and one additional character, `print(){!+` (10 characters) and one additional character, etc.
* If the previous answer had `print(){}!*+` as its character set (12 characters), your submission could *not* have `print()` and `&` (8 characters) as its character set, since `12 - 8 > 1`.
* If the previous answer had `print(){}!*+` as its character set (12 characters), your submission could *not* have `print(){}!` (10 characters) plus additional character `*` as its character set, since even though that's 11 characters, the `*` is included in the previous set.
* Not every character in your character set must do something useful for your submission. For example, if the previous answer had `print(){}!*+` as its character set, and your language has a built-in `!` that calculates the Fibonacci sequence and `#` that starts a comment, your submission could be `!#print(){}` and still be valid.
* You can use the same character from your character set multiple times. For example, suppose your character set was `!*#_`, your answer could be `!!!**#**#_!!` and would be acceptable.
* In addition to your code (and an explanation is nice, too!) please also explicitly list your character set, to make it easier for future submissions.

## Winning

The winner of the challenge will be the person who posted the *second* most-recent submission (i.e., not the person who posted last, since they broke the chain).

### Final Rules

Usual rules apply:

* The same person can't post twice in a row
* If an answer is deemed invalid (for example, it used a forbidden character, or doesn't calculate correctly), it needs to be deleted (and any subsequent answers that chain off of it also)
* Two users who post "at the same time" will have to let the earlier submission stand
* The same language cannot be posted twice in a row. For the purposes of this rule, languages of the same family (e.g., Python 2 and Python 3) count as "the same language."

---

Final things:

* This post works best if you sort by "Oldest" so that the answers are in proper order.
* Kyle Gullion constructed a code checker in Python here to verify if you're missing or using wrong characters.

# Answer
# 1. C

Contains no `{` or `}`.

```
#if 1
#define Q !"$&'",./=@[]^_\`|*
int WERTYUIOPASDFGHJKLZXCVBNM34567890(qwrtyuopasghjklzxcvbm)<%
	return qwrtyuopasghjklzxcvbm<2?1:WERTYUIOPASDFGHJKLZXCVBNM34567890(~-qwrtyuopasghjklzxcvbm)+WERTYUIOPASDFGHJKLZXCVBNM34567890(qwrtyuopasghjklzxcvbm-2);
%>
#endif

```

Try it online!

I hope I did this right.
> 6 votes

# Answer
# 8. Octave

Added `U` and removed `+` and `-`. Solution contains no `+-`01AEI` or tab character.

```
% !"#$&\'*./256789:<>?BCDFGHJKLMNOPQRSTUVWXYZ\\_abceghijklnpqrstuvwyz{|}~
f=@(x)([mod(4,3) mod(4,3);mod(4,3) mod(4,4)]^x)(3)

```

Based on the Fibonacci Matrix.
> 6 votes

# Answer
## 33, MATL

Added `-`, removed `()`. Solution doesn't contain `!&'()/\01?AEIKLMNPSTWZ`dmwz{}|~`, tab, space, or newline.

```
5X^Hq+G^Hq5X^-G^-HG^5X^*Hqqq^*Yo%"#$,.2346789:;<=>@BCDFJOQRUV[]_abcefghijklnprstuvxy

```

Try it at MATL Online

Fixed mistake: `0`, `1`, and `\` were accidentally left in the comment (after the `%`) at the end. Their removal does not break the functionality. Moved this answer from 32 to 33 in an attempt to keep it valid. If it needs to be deleted, please let me know and I'll do just that.
> 6 votes

# Answer
# 2. Mathematica

Contains no `}`, `Z`, or horizontal tab. (Reincluded `{`.)

```
(* !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY
[\]^_`\abcdefghijklmnopqrstuvwxyz{|~ *)
Fibonacci

```

The two first lines are just a comment; the last line is the builtin function, using the Only True Super Cosmically Ordained Indexing where inputs 0 and 1 yield outputs 0 and 1 respectively (I have no idea whether to call this 0-indexed or 1-indexed).
> 5 votes

# Answer
# 36. Java

Added `\`. Removed `qx`. Doesn't use `!&'()/1?AEIKLMNPSTWZ`dmnqtwxz{}|~[]`, tab, or space.

```
\u002f\u002f"#$%*:>@BCGHJOQRUVXY^_jk
class
Fibo\u006eacci\u007b
i\u006e\u0074
fib\u0028i\u006e\u0074
\u006e\u0029\u007b
i\u006e\u0074
lo\u0077=0,high=3-2,\u0074e\u006Dp;
for\u0028i\u006e\u0074
i=3-2;i<\u006e;i++\u0029\u007b
\u0074e\u006Dp=lo\u0077;
lo\u0077=high;
high=high+\u0074e\u006Dp;
\u007D
re\u0074ur\u006e
lo\u0077;
\u007D
public
s\u0074a\u0074ic
voi\u0064
\u006Dai\u006e\u0028\u0053\u0074ri\u006eg\u005b\u005Db\u0029\u007b
Fibo\u006eacci
a=\u006ee\u0077
Fibo\u006eacci\u0028\u0029;
for\u0028i\u006e\u0074
i=3-2;i<=20;i++\u0029\u007b
\u0053ys\u0074e\u006D.ou\u0074.pri\u006e\u0074l\u006e\u0028a.fib\u0028i\u0029\u0029;
\u007D
\u007D
\u007D

```

I know I probably could have waited longer but I wanted to make sure to get this out before it was too late. Not only does this class define a function which takes an integer `n` and return that Fibonacci number, but it also prints the first 20 for you just for fun. I tried to do my due diligence by writing this in plain old java with no sneaky golfing and then I removed illegal characters 1 by 1 until we got to the creature you see before you now.

Try it online!
> 5 votes

# Answer
# 37. Python 2

Readded `x`. Doesn't use `!&'()/1?AEIMNPSTWZdmnqtwz{}|~[]`, space, tab or \`. Removed K and L.

```
f=u"\u0074"
b=u"\u006D"
i=u"\u0028"
j=u"\u0029"
h=u"\u006e"
r=2.2360679775
s=u"\u002F"
exec"p="+i+"3-2+r"+j+s+"2"
exec"g=i"+h+"pu"+f+i+j
exec"pri"+h+f+i+"i"+h+f+i+i+"p**g-"+i+"-p"+j+"**-g"+j+s+"r"+j+j
#$%´:;<=>@BCGHJOQRUVXY^agklopvy

```

With comments:

```
f=u"\u0074" #t
b=u"\u006D" #m
i=u"\u0028" #(
j=u"\u0029" #)
h=u"\u006e" #n
r=2.2360679775 #sqrt(5)
s=u"\u002F" #/
exec"p="+i+"3-2+r"+j+s+"2" #p=(3-2+r)/2 = (1+sqrt(5))/2 = phi
exec"g=i"+h+"pu"+f+i+j #g=input()
exec"pri"+h+f+i+"i"+h+f+i+i+"p**g-"+i+"-p"+j+"**-g"+j+s+"r"+j+j #print(int((p**g-(-p)**-g)/r))

```

This approach uses the fibonacci series' general term.
> 5 votes

# Answer
# 3. Brain-Flak

Contains no `Z`, `~`, `A`, or horizontal tab. (Re-included `}`)

```
({}<(())>){({}<(({})<>)<>({}{}<<>({}<>)>)>[()])}{}{}
# !"$%&'*+,-./0123456789:;=?@BCDEFGHIJKLMNOPQRSTUVWXY\^_`abcdefghijklmnopqrstuvwxyz|

```

Try it online!
> 4 votes

# Answer
# 5, Haskell

Removed `AEIOU` and tab, added `Z`

```
-- #!"$%&'*./23456789;:<>?@BCDFGHJKLMNPQRSTVWXYZ[\]^`abcdeghijklmopqrstuvwxyz{|}~,_
f 0 = 1
f 1 = 1
f n = f (n-1) + f (n-2)

```

Try it online!
> 4 votes

# Answer
# 6. Brain-Flak

```
({}<(())>){({}<(({})<>)<>({}{}<<>({}<>)>)>[()])}{}{}
# !"$%&'*+,-./0123456789:;=?@BCDFGHJKLMNOPQRSTVWXY\^bcdfghjklmnopqrstvwxyz|

```

Try it online! Doesn't use `*tab*AEIU`_`, and added back `O`
> 3 votes

# Answer
## 12. Python 3

added `:` removed `{;` doesn't contain `{};`01AEIPQx` or tab character.

```
#!"#$%&\',./23456789?@BCDFGHJKLMNORSTUVWXYZ[\]^_abcdgjkmopqrvwyz|~:
def fib(n,a=3-2,b=3-2):
 if n==2-2:
  return a
 a, b = b, a + b
 return fib(n-1,a,b)
```
> 3 votes

# Answer
# 26. Prolog (SWI)

Added `%`. Removed `NK`. Doesn't use `&*01AEIKLMNPSTWZ`dmrwz{}]`, tab or newline.

```
a(X,B):-X<3,B is 4-3;C is X-4-(-3),D is X-2,a(C,G),a(D,F),B is G-(-F).%!"#$'/56789=>?@HJOQRUVY[\^_bcefghjklnopqtuvxy|~

```

Try it online!
> 3 votes

# Answer
# 34. brainfuck

Added newline, removed `n` and `t`. Doesn't use `!&'()/\01?AEIKLMNPSTWZ`dmntwz{}|~`, tab, or space. (maybe we can get some 2D languages now)

0-indexed. Input/output is by byte values.

```
,[->]+>+<<[->>[->+<]<[->+<]>>[-<+<+>>]<<<]>>.
"#$%*23456789:;=@BCDFGHJOQRUVXY^_abcefghijklopqrsuvxy

```

Try it online!
> 3 votes

# Answer
# 4, Python 2

Removed `AEIZ`, tab added `~`

```
# !"$%&'*-./23456789;<>?@BCDFGHJKLMNOPQRSTUVWXY[\]^`chjklmpqsvwxyz{|}

def f(x):
 a=0
 b=1
 for _ in range(x):
  a,b = a+b,a
 return a

```

Try it online!
> 2 votes

# Answer
# 9. Python 2

Added `-`, removed `m` and `x`. Contains no `+`01AEImx` or tab character.

```
# --!"$%&'*./29;:<>?@[\]^345678BCDFGHJKLMNOPQRSTUVWXYZabcdeghijklopqrstuvwyz{|}~,_

def fibonacci(n):
    elif n==(2/2):
        return 2-2
    elif n==2:
        return 2/2
    else:
        return fibonacci(n-2/2)-(-(fibonacci(n-2)))

```

Recursive Python function! Adds all Fibonacci numbers *backwards* until `n` is 1.
> 2 votes

# Answer
# 10. C

Added `m`, removed `PQ`. Doesn't contain `+`01AEIPQx` or tab character.

Compiler flag: `-lm`

```
//!"#$%&'*346789:<=>?@BCDFGHJKLMNORSTUVWXYZ[\]^_acfghkmvyz|.

double fib(i){
    double j = -(-~-2-sqrt(5))/2;
    return floor((pow(j,i)-pow(-j,-i))/sqrt(5));
}

```

Try it online!
> 2 votes

# Answer
## 11. Standard ML (mosml)

Added `+`. Removed `:}`. Doesn't contain `:}0`1AEIPQx` or tab character.

```
(* !"#$%&\',./23456789;<>?@BCDFGHJKLMNORSTUVWXYZ[\]^_abcdgjkmopqrvwyz{|~ *)
fun f s = if s = 2-2 then 2-2 else if s = 3-2 then 3-2 else f (s-4+2) + f (s-3+2)

```

SML isn't on TIO, and I used the moscow ml variety, but there's an online SMLNJ interpreter here.
> 2 votes

# Answer
# 18. Octave

Added `;` and removed `f` and space. Solution contains no `{}:`*%01AEIPQfrd`, no tab, no newline, and no space characters.

```
g=@(x)([4-3,4-3;4-3,4-4]^x)(3)#!"$&'+./256789<>?BCDFGHJKLMNORSTUVWXYZ\_abcehijklmnopqstuvwyz|~

```

Identical to answer 8, just with more SML hate :P
> 2 votes

# Answer
# 23. Standard ML (mosml)

There we go again. Added `Q`, removed `}` and `]`. Doesn't use `%&*+01:AEILMPZ`dmrzM{}]`, tab, or linefeed

```
fun f x = #2("!#$\\',.23456789<>?@BCDFGHJKNOQRSTUVWXY[/;^_abcgjkopqvwxy|~", if x = 2-2 then 2-2 else if x = 3-2 then 3-2 else f (~(~(x-4)-2)) + f (x-(~3-2)))

```
> 2 votes

# Answer
# 25. CJam

Added `+` back, removed `S` and `T`. Doesn't use `%&*01AEILMPSTZ`dmrz{}]Ww`, tab, or linefeed.

Basically a port of my older answer, but this one uses some eval trickery to circumvent the lack of braces.

```
q~"XX"a:~'|("_(j\((j+"'|)'j+++~e# !$,-./23456789;<=>?@BCDFGHJKNOQRUVY[^bcfghiklnopstuvxy

```

0-indexed.

Try it online!
> 2 votes

# Answer
# 27. JavaScript

Added `*`, removed `"` and `'`. Doesn't use `"&'01AEIKLMNPSTZ`dmrz{}]Ww`, tab, or linefeed.

```
f=a=>a<2?3-2:f(a-3+2)+f(a-4+2)/* !#$,.56789;%@BCDFGHJOQRUVXY[\^_bceghijklnopqstuvxy|~*/

```
> 2 votes

# Answer
# 28. Haskell

```
f=length"":scanl(+)(length"f")f;g=const(f!!)"#$%*,./23456789<>?@BCDFGHJOQRUVXY[\\^_bijkpquvxy|~"

```

Try it online! Usage: `g 3` gives `2`.

Added `"`, removed `<space>` and `-`. Does not use `&'-01AEIKLMNPSTZ`dmrz{}]Ww` or any white spcae.
> 2 votes

# Answer
# 30. Standard ML

Added `:`, removed `+` and `?`. Does not contain `!&'+-01?AEIKLMNPSTWZ`dmrwz{}` or any white space.

```
fun$(a,b,x)n=if(length(x)=n)then(length(a))else$(b,a@b,()::x)n;("#%*./23456789<>BCDFGHJOQRUVXY\\^_cjkopqvy|~";$([],[()],[]))

```

The first part `fun$(a,b,x)n=if(length(x)=n)then(length(a))else$(b,a@b,()::x)n` defines a function `$` which computes the `n`th fibonacci number itereatively using an unary list encoding. The length of argument `x` indicates the current number and `a` and `b` are lists of length `fib(length(x)-1)` and `fib(length(x))`. If `n` equals `length(x)` we return `length(b)`, otherwise recursively add `a` and `b` via list concatenation and increment `x` by adding an element `()` to it.

The second part `("#%*./23456789<>BCDFGHJOQRUVXY\\^_cjkopqvy|~";$([],[()],[]))` is a sequence where the string is discarded and `$([],[()],[])` is the initialisation of the function `$` with `a = 0`, `b = 1` and `x = 0`, resulting in an anonymous function which computes the nth fibonacci number.
> 2 votes

# Answer
# 32, Python 3

```
exec(chr(2**2+2**5+2**6)+chr((3^2)+2**2+2**5+2**6)+chr(2+2**2+2**5+2**6)+chr(2**5)+chr(2+2**2+2**5+2**6)+chr(2**3+2**5)+chr(2**3+2**4+2**5+2**6)+chr((3^2)+2**3+2**5)+chr(2+2**3+2**4+2**5)+chr(2+2**3)+chr(2**5)+chr((3^2)+2**5+2**6)+chr((3^2)+2**2+2**3+2**4+2**5)+chr(2**4+2**5)+chr(2+2**3)+chr(2**5)+chr(2+2**5+2**6)+chr((3^2)+2**2+2**3+2**4+2**5)+chr((3^2)+2**4+2**5)+chr(2+2**3)+chr(2**5)+chr(2+2**2+2**5+2**6)+chr((3^2)+2+2**2+2**3+2**5+2**6)+chr(2+2**4+2**5+2**6)+chr(2**5)+chr((3^2)+2+2**2+2**3+2**4+2**6)+chr(2**5)+chr((3^2)+2**3+2**5+2**6)+chr(2+2**2+2**3+2**5+2**6)+chr(2**5)+chr(2+2**4+2**5+2**6)+chr((3^2)+2**5+2**6)+chr(2+2**2+2**3+2**5+2**6)+chr((3^2)+2+2**2+2**5+2**6)+chr((3^2)+2**2+2**5+2**6)+chr(2**3+2**5)+chr(2**3+2**4+2**5+2**6)+chr((3^2)+2**3+2**5)+chr(2+2**3+2**4+2**5)+chr(2+2**3)+chr(2**5)+chr(2**5)+chr((3^2)+2**5+2**6)+chr(2**2+2**3+2**5)+chr(2+2**5+2**6)+chr(2**5)+chr((3^2)+2**2+2**3+2**4+2**5)+chr(2**5)+chr((3^2)+2**5+2**6)+chr((3^2)+2+2**3+2**5)+chr(2+2**5+2**6)+chr(2**2+2**3+2**5)+chr((3^2)+2**5+2**6)+chr(2+2**3)+chr(2**5)+chr(2+2**4+2**5+2**6)+chr((3^2)+2**2+2**5+2**6)+chr(2**2+2**4+2**5+2**6)+chr((3^2)+2**2+2**4+2**5+2**6)+chr(2+2**4+2**5+2**6)+chr(2+2**2+2**3+2**5+2**6)+chr(2**5)+chr((3^2)+2**5+2**6))#"$%,.789:;<=>@BCDFGHJOQRUVXY[]_abfgijklnopqstuvy

```

Added `r` and removed `|~`. Solution contains no `!&'/\-01?AEIKLMNPSTWZ`dmrwz{}|~`, no tab, no newline, and no space characters.
> 2 votes

# Answer
# 38. Matl

Added `q`. Removed `0 <newline>`. Doesn't use `!&'()/1?AEIKLM0NPSTW{Z`dmntwxz}|~[]`, tab, newline, or space.

```
5X^Hq+G^Hq5X^-G^-HG^5X^*Hqqq^*Yo%"#$,.2346789:;<=>@BCDFJORUV_abcefghijklprsuvy

```

Try it online
> 2 votes

# Answer
# 39. Python 2

Added `0`. Removed `@^`. Doesn't use `!^&'()/1?@AEIMNPSTWZdmntwz{}|~[] ``, tab or newline.

```
C=u"f=la\u006Db\u0064a\u0020X:3-2if\u0020X<2else\u0020f\u0028X-3+2\u0029+f\u0028X-2\u0029";exec""+C#$%*,.57>BFGHJKLOQRUVY_ghjkopqrvy

```

Argument to exec without escape sequences:

```
f=lambda X:3-2if X<2else f(X-3+2)+f(X-2)

```

Try it online!
> 2 votes

# Answer
# 7, Python 2

Re-included `_`. Removed characters: *tab* and `AEIU``, and (just to get a little nasty) `0` and `1`. Otherwise, just a copy of Wheat Wizard's answer (hence the community wiki).

```
# !"$%&'*./456789;<>?@BCDFGHJKLMNOPQRSTVWXY[\]^chjklmpqsvwxyz{|}

def f(x):
 a=2-2
 b=3-2
 for _ in range(x):
  a,b = a+b,a
 return a

```

Try it online!
> 1 votes

# Answer
## 13. Standard ML (mosml)

Added `x`. Removed `:r`. Doesn't contain `:;{}0`1AEIPQr` or tab character.

```
(* !"#$%&\',./23456789<>?@BCDFGHJKLMNORSTUVWXYZ[\]^_abcdgjkmopqvwxyz|~ *)
fun f s = if s = 2-2 then 2-2 else if s = 3-2 then 3-2 else f (s-4+2) + f (s-3+2)

```

After we've pretty much excluded C-style languages, let's go after Python. This answer is pretty much identical to answer 11.
> 1 votes

# Answer
# 14. Octave

Added `r` and removed newline and space. Solution contains no `{}:;`01AEIPQ`, no tab, no newline, and no space characters.

```
f=@(n)round(((2/2+sqrt(5))/2)^n/sqrt(5))%!"#$&'*-,.346789<>?BCDFGHJKLMNORSTUVWXYZ[\]_abceghijklmpvwyz|~

```

Based on a closed form formula (7).
> 1 votes

# Answer
# 15. Standard ML (mosml)

Added space and removed `%/`. Doesn't contain `{}:;`01AEIPQ`, tab, or newline.

```
fun f s = if s = 2-2 then 2-2 else if s = 3-2 then 3-2 else f (s-4+2) + f (s-3+2) (* !"#$&\',.23456789<>?@BCDFGHJKLMNORSTUVWXYZ[\]^_abcdgjkmopqrvwxyz|~ *)

```
> 1 votes

# Answer
# 16. Octave

Added `/` and removed * and space. Solution contains no `{}:;`*%01AEIPQ`, no tab, no newline, and no space characters.

```
f=@(n)round(((2/2+sqrt(5))/2)^n/sqrt(5))#!"$&'-,.346789<>?BCDFGHJKLMNORSTUVWXYZ[\]_abceghijklmpvwyz|~

```

Identical to answer 14, just a straight up attack on SML and Python :P
> 1 votes

# Answer
# 17. Standard ML (mosml)

Added space, removed `rd`. Contains no `{}:;`*%01AEIPQrd`, tab, or newline.

```
fun f s = #2("!#$&\\',.23456789<>?@BCDFGHJKLMNORSTUVWXYZ[]^_abcgjkmopqvwxyz|~", if s = 2-2 then 2-2 else if s = 3-2 then 3-2 else f (s-4+2) + f (s-3+2))

```

Again, a copy from my previous answers, but instead of a comment a string literal that gets discarded. And good bye, `sqrt` and `round`.
> 1 votes

# Answer
# 19. 05AB1E

Added `}`. Removed `Zz`. Contains no `{:`*%01AEIPQfrdZz`, tab, space, newline.

```
Xs2<<sFUX+Xs}q!"#$&'()+,-./23456789;<=>?@BCDFGHJKLMNORSTUVWXY[\]^_abceghijklmnopqstuvwxy|~

```

Try it online!
> 1 votes

# Answer
# 20. CJam

Added `{`, removed `M` and `m`. Doesn't contain `%*01:AEIMPQZ`dfmrz`, tab, space, or linefeed.

```
q~[XX]{_(j\((j+}je#!"$&'),-./23456789;<=>?@BCDFGHJKLNORSTUVWY^abcghiklnopstuvwxy|

```

0-indexed.

Try it online!
> 1 votes

# Answer
# 22. PHP

Added `f`, removed `&` and `L`. Doesn't use `%&*+01:AEILMPQZ`dmrzM{`, tab, or linefeed.

```
$a=aRRay(3-2,3-2);$i=ReaDline();$c=3-2;while(($c=$c- -3-2)<=$i)$a[$c]=$a[$c- -2-3]- -$a[$c-2];echo $a[count($a)- -2-3];#!"'+./456789>?@BCFGHJKNOSTUVWXY\^_bfgjkpqsvx|}~

```

0-indexed.

Try it online!
> 1 votes

# Answer
# 24. \>\<\>

Added `:`. Removed `Ww`. Doesn't use `%&*+01AEILMPZ`dmrzM{}]Ww`, tab or newline

Uses the `-v` flag.

```
55-54-:@55-$--@@54--:54-54-p@555-54-54-g?.~~~n; !"#'(),/236789<=>BCDFGHJKNOQRSTUVXY[\^_abcefhijkloqstuvxy|

```

Try it online!

As we really needed to add `:` in order to duplicate values.
So we can't include the newline, requiring a one liner.
The only control flow we have while using 1 line is jump (`.`).
Utilizing this, the trick is mostly about keeping the values in the correct order on the stack.
Unfortunately we can't use `}`, so we use a workaround with `g` and `p` instead.
> 1 votes

# Answer
# 31. CoffeeScript

Added `+` and removed `/\`. Solution contains no `!&'/\-01?AEIKLMNPSTWZ`dmrwz{}`, no tab, no newline, and no space characters.

```
f=(x)=>if(x<2)then(x)else(f(x+(~2|2))+f(x+(~3|2)))#"$%*,.456789:;@BCDFGHJOQRUVXY[]^_abcgjkopquvy

```

Basic recursive solution. Try it online!
> 1 votes

# Answer
# 35. MATL

Added 0, removed `[` and `]`. Doesn't use `!&'()/\1?AEIKLMNPSTWZ`dmntwz{}[]|~` , tab, or space.

```
5X^Hq+G^Hq5X^-G^-HG^5X^*Hqqq^*Yo%"#$,.2346789:;<=>@BCDFJOQRUV_abcefghijklprsuvxy0
<newline>

```

Try it online
> 1 votes

# Answer
# 40. Aceto (line-mode)

Added `d`. Removed `u\`. Doesn't use `!^&'()/1?@AEIMNPSTWZmntuwz{}|~\[] ``, tab, or newline.

Use command-line option `-l` (which I counted in the used characters)

```
ridd32-532-2:F+sFs32-532-2:F-sF-s2sF532-2:F*:ipX"#$%,.046789;<=>BCDGHJKLOQRUVY_abcefghjkloqvxy

```

---

I'm using Binet's formula for the nth fibonacci number. Since I can't really use more than one stack (as `[]{}()` are banned), I do it all on one, which is a bit annoying since the register is also blocked by the ban of `M`. Duplication and swapping still works, though. Instead of the number one I substract two from three (`32-`).

After printing, I exit with `X` and then just append the remaining characters (Aceto knows no comments).
> 1 votes

# Answer
# 41. Alphuck, 366 bytes

Added `!` and removed `+.`. Solution doesn't contain `!^&'()+./1?@AEIMNPSTWZmntuwz{}|~\[] ``, tab, or newline characters.

```
pisapiseppisapisopepiiiiiiiiiiipapiseeeeeepciiiiiiaisciiccpiaaeeeeeeeeeeccsaapicceaasceassscscaecpaaapisccpaaeccisapceaisapceaiscpceaaecisapceaiscccisaaapiscpiscpaaeaecccisaaapccceaaaiscceapciapaeeeeeeeeeecpiaipaeaasapepiceasaeaascccccsapiseeeeeeeepceeeeeeaisapcceaaisapcceaaisccsascpiaaeeeeeeeepceeeeeeaisscpjpiscsc!"#$%*-023456789:;<=>BCDFGHJKLOQRUVXY_bdfghklqrvxy

```

Try it online!
> 1 votes

# Answer
# 42. Headsecks

Added `^` and removed `Q_`. Solution doesn't contain `&'()+./1?@AEIMNPQSTWZ[\]_`mntuwz{|}~`, space, tab, or newline characters.

```
U6y#OH;0:jFqCsfic8JoB^!kp2G3KVa*xbh#;gr"R7Csl>YOvX9,4dLD$<e5=-%o

```

Below is a Python3 function to transpiles Headsecks to brainf\***

```
transpiler = lambda hs:"".join("+-<>.,[]"[ord(cmd)%8] for cmd in hs)

```

Code based on answer 34.

Let's see if we can get this chain going again! I added `^` to try and enable something like 38. Hopefully we can restore some stuff for other languages too.
> 1 votes

# Answer
# 21. 05AB1E

```
Xs2<<sFUX+Xs}q!"#$&'(),-./23456789<=>?@BCDFGHJKLNORSTUVWXY[\]^_abceghijklnopqstuvwxy|~

```

Added space, removed + and `{`. Doesn't contain `%*01:AEIMPQZ`dfmrzM{`, tab, or linefeed. I removed the bracket to make it harder Try it online!
> 0 votes

# Answer
# 29. Octave

Added `]` and removed `!:`. Solution contains no `&'-!:01AEIKLMNPSTZ`dmrz{}Ww`, no tab, no newline, and no space characters.

```
f=@(x)([length("l"),length("l");length("l"),length("")]^x)(3)#$%*+./2456789<>?BCDFGHJOQRUVXY\_abcijkopqsuvy|~

```

Same idea as answer 8
> 0 votes

---
Tags: sequence, restricted-source, fibonacci, printable-ascii, answer-chaining
---


title: Largest Prime Exponents

text:
# Question
Title: Largest Prime Exponents
Given an integer `n >= 2`, output the largest exponent in its prime factorization. This is OEIS sequence A051903.

## Example

Let `n = 144`. Its prime factorization is `2^4 * 3^2`. The largest exponent is `4`.

## Test Cases

```
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 1
7 -> 1
8 -> 3
9 -> 2
10 -> 1
11 -> 1
12 -> 2
144 -> 4
200 -> 3
500 -> 3
1024 -> 10
3257832488 -> 3

```

# Answer
> 8 votes
# 05AB1E, 2 bytes

```
ÓZ

```

Try it online!

**How?**

```
Ó   exponents of prime factors
 Z  maximum

```

# Answer
> 8 votes
# Python 2, ~~62~~ ~~57~~ 56 bytes

```
lambda n:max(k%n-n%(k/n+2)**(k%n)*n for k in range(n*n))

```

Try it online!

# Answer
> 6 votes
# Jelly, 3 bytes

```
ÆEṀ

```

**Try it online!**

```
ÆEṀ  - Full program / Monadic link.

ÆE   - Array of exponents of prime factorization.
  Ṁ  - Maximum.

```

This also works in . Try it online!

# Answer
> 4 votes
# Haskell, ~~61~~ ~~60~~ ~~50~~ ~~48~~ 46 bytes

-2 bytes thanks to xnor

```
f n=maximum[a|k<-[2..n],a<-[1..n],n`mod`k^a<1]

```

Try it online!

### 45 bytes with an import:

```
import NumberTheory
maximum.map snd.factorize

```

Try it Online!

# Answer
> 4 votes
# Ohm v2, 2 bytes

```
n↑

```

Try it online!

## Explanation?

No.

# Answer
> 4 votes
# Python 2, 78 bytes

```
n=input()
e=m=0
f=2
while~-n:q=n%f<1;f+=1-q;e=q*-~e;m=max(m,e);n/=f**q
print m

```

Try it online!

-5 thanks to ovs.

This answer doesn't do prime checks. Instead, it takes advantage of the fact that the highest exponent of a prime factor will be greater than or equal to the exponent of any other factor in any factorization of a number.

# Answer
> 4 votes
# Japt `-h`, ~~9~~ 7 bytes

```
k ü mÊn

```

Try it

```
k ü mÊn     :Implicit input of integer
k           :Prime factors
  ü         :Group by value
    m       :Map
     Ê      :  Length
      n     :Sort
            :Implicit output of last element

```

# Answer
> 3 votes
# Mathematica, 27 bytes

```
Max[Last/@FactorInteger@#]&

```

Try it online!

# Answer
> 3 votes
# MATL, 4 bytes

```
YFX>

```

Try it online!

```
       % implicit input
YF     % Exponents of prime factors
X>     % maximum
       % implicit output

```

# Answer
> 3 votes
# Husk, 5 bytes

```
▲mLgp

```

Try it online!

* `p` – Gets the prime factors.
* `g` – Groups adjacent values.
* `mL` – Gets the lengths of each group.
* – Maximum.

# Answer
> 3 votes
# Brachylog, 5 bytes

```
ḋḅlᵐ⌉

```

Try it online!

### Explanation

```
ḋ          Prime decomposition
 ḅ         Group consecutive equal values
  lᵐ       Map length
    ⌉      Maximum

```

# Answer
> 2 votes
# APL (Dyalog), 19 bytes

```
⎕CY'dfns'
⌈/1↓2pco⎕

```

Try it online!

**How?**

`2pco⎕` \- 2D array of prime factors and exponents

`1↓` \- drop the factors

`⌈/` \- maximum

# Answer
> 2 votes
# Javascript 54 bytes

\*assuming infinite stack (as do in code-golf challenges)

```
P=(n,i=2,k)=>i>n?k:n%i?k>(K=P(n,i+1))?k:K:P(n/i,i,-~k)

console.log(P(2 )== 1)
console.log(P(3 )== 1)
console.log(P(4 )== 2)
console.log(P(5 )== 1)
console.log(P(6 )== 1)
console.log(P(7 )== 1)
console.log(P(8 )== 3)
console.log(P(9 )== 2)
console.log(P(10 )== 1)
console.log(P(11 )== 1)
console.log(P(12 )== 2)
console.log(P(144 )== 4)
console.log(P(200 )== 3)
console.log(P(500 )== 3)
console.log(P(1024 )== 10)
//console.log(P(3257832488 )== 3)
```

# Answer
> 2 votes
# PARI/GP, 24 bytes

```
n->vecmax(factor(n)[,2])

```

If I do not count the `n->` part, it is 21 bytes.

# Answer
> 2 votes
# Octave, 25 bytes

```
@(n)[~,m]=mode(factor(n))

```

**Try it online!**

### Explanation

`factor` produces the array of (possibly repeated) prime exponents The second output of `mode` gives the number of times that the mode (i.e. the most repeated entry) appears.

# Answer
> 1 votes
# Pyth, 7 bytes

```
eShMr8P

```

Try it here.

# Answer
> 1 votes
# Python 2, ~~90~~ 84 bytes

```
f=lambda n,i=2,l=[0]:(n<2)*max(map(l.count,l))or n%i and f(n,i+1,l)or f(n/i,2,l+[i])

```

Try it online!

# Answer
> 1 votes
# Gaia, 4 bytes

```
ḋ)⌠)

```

**Try it online!**

* \- Computes the prime factorization as **\[prime, exponent\]** pairs.

+ \- Map and collect the result with the maximal value.
    + `)` \- Last element (exponent).
    + `)` \- Last element (maximal exponent)

# Gaia, 4 bytes

```
ḋ)¦⌉

```

Try it online!

* \- Computes the prime factorization as **\[prime, exponent\]** pairs.

+ \- Map with the last element (exponent).
    + \- Gets the maximum element.

# Answer
> 1 votes
# MY, 4 bytes

```
ωĖ⍐←

```

Try it online!

## Explanation?

```
ωĖ⍐←
ω    = argument
 Ė   = prime exponents
  ⍐  = maximum
   ← = output without a newline

```

# Answer
> 1 votes
# Octave: 30 bytes

```
@(x)max(histc(a=factor(x),a));

```
1. `a=factor(x)` returns a vector containing the prime factors of `x`. This is a vector sorted in ascending order where the multiplication of all numbers in `factor(x)` yields `x` itself such that each number in the vector is prime.
2. `histc(...,a)` calculates a histogram on the prime factor vector where the bins are the prime factors. The histogram counts up how many times we have seen each prime number thus yielding the exponent of each prime number. We can cheat here a bit because even though `factor(x)` will return duplicate numbers or bins, only one of the bins will capture the total amount of times we see a prime number.
3. `max(...)` thus returns the largest exponent.

## Try it online!

# Answer
> 1 votes
# Racket, ~~83~~ 79 bytes

```
(λ(n)(cadr(argmax cadr((let()(local-require math/number-theory)factorize)n))))

```

Try it online!

(I'm not sure if there's a consensus on what constitutes a complete Racket solution, so I'm going with the Mathematica convention that a pure function counts.)

### How it works

`factorize` gives the factorization as a list of pairs: `(factorize 108)` gives `'((2 2) (3 3))`. The second element of a pair is given by `cadr`, a shorthand for the composition of `car` (head of a list) with `cdr` (tail of a list).

I feel silly doing `(cadr (argmax cadr list))` to find the maximum of the second elements, but `max` doesn't work on lists: `(max (map cadr list))` doesn't do what we want. I'm not an expert in Racket, so maybe there's a standard better way to do this.

# Racket, 93 bytes

```
(λ(n)(define(p d m)(if(=(gcd m d)d)(+(p d(/ m d))1)0))(p(argmax(λ(d)(p d n))(range 2 n))n))

```

Try it online!

### How it works

An alternative version that doesn't import `factorize` and instead does everything from scratch, more or less. The function `(p m d)` finds the highest power of `d` that divides `m` and then we just find highest value of `(p n d)` for `d` between `2` and `n`. (We don't need to restrict this to primes, since there will not be a composite power that works better than prime powers.)

# Answer
> 1 votes
## Alice, 17 bytes

```
/o
\i@/w].D:.t$Kq

```

Try it online!

### Explanation

```
/o
\i@/...

```

This is just a framework for simple-ish arithmetic programs with decimal I/O. The `...` is the actual program, which already has the input on the stack and leaves the output on top of the stack.

Alice actually has built-ins to get the prime factorisation of an integer (even with prime-exponent pairs), but the shortest I've come up with using those is 10 bytes longer than this.

Instead the idea is that we repeatedly divide one copy of each distinct prime factor out of the input, until we reach **1**. The number of steps this takes is equal to the largest prime exponent. We'll be abusing the tape head as the counter variable.

```
w      Remember the current IP position. Effectively starts a loop.
  ]      Move the tape head to the right, which increments our counter.
  .D     Duplicate the current value, and deduplicate its prime factors.
         That means, we'll get a number which is the product of the value's
         unique prime factors. For example 144 = 2^4 * 3^2 would become
         6 = 2 * 3.
  :      Divide the value by its deduplicated version, which decrements the
         exponents of its prime factors.
  .t     Duplicate the result and decrement it. This value becomes 0 once we
         reach a result of 1, which is when we want to terminate the loop.
$K     Jump back to the beginning of the loop if the previous value wasn't 0.
q      Retrieve the tape head's position, i.e. the number of steps we've taken
       through the above loop.

```

# Answer
> 1 votes
# Julia, 60 52 40 bytes

```
f(x)=maximum(collect(values(factor(x))))

```

-12 +correction thanks to Steadybox

# Answer
> 0 votes
# Actually, 4 bytes

```
w♂NM

```

Try it online!

```
w♂NM  - Full program.

w     - Pushes the prime factorization as [prime, exponent] pairs.
 ♂N   - Get the last element of each (the exponents).
   M  - Maximum.

```

# Answer
> 0 votes
# Python 2, 64 bytes

*-4 bytes thanks to H.PWiz.*

```
lambda n:max(a*(n%k**a<1)for a in range(n)for k in range(2,-~n))

```

Try it online!

Port of H.PWiz's Haskell answer. I'm only sharing this because I'm proud that I was able to understand this piece of Haskell code and translate it. :P

# Answer
> 0 votes
# Axiom, 61 bytes

```
f n==(a:=factors n;reduce(max,[a.i.exponent for i in 1..#a]))

```

This is the first time i find it is possible define the function without the use of () parenthesis. Instead of "f(n)==" "f n==" one character less...

# Answer
> 0 votes
# J, 9 bytes

```
[:>./_&q:

```

Max of `<./` all prime exponents `_&q:`

Try it online!

# Answer
> 0 votes
# APL(NARS), 15 chars, 30 bytes

```
{⌈/+/¨v∘=¨v←π⍵}

```

test:

```
  f←{⌈/+/¨v∘=¨v←π⍵}
  f¨2..12
1 1 2 1 1 1 3 2 1 1 2
  f¨144 200 500 1024 3257832488
4 3 3 10 3

```

comment:

```
{⌈/+/¨v∘=¨v←π⍵}
          v←π⍵    π12 return 2 2 3; assign to v the array of prime divisors of argument ⍵
      v∘=¨        for each element of v, build one binary array, show with 1 where are in v array, else puts 0
                  return one big array I call B, where each element is the binary array above
   +/¨            sum each binary element array of  B
 ⌈/               get the max of all element of B (that should be the max exponet)

```

---
Tags: code-golf, number-theory, primes, integer, factoring
---


title: Make a transparent 448*448 image

text:
# Question
Title: Make a transparent 448*448 image
This is a simple challenge.

The task is to write code that outputs a 448\*448 square image with 100% transparency. The output should follow the standard image rules.

# Answer
> 28 votes
# Imagemagick in some shell, 35

```
convert -size 448x448 xc:none a.png

```

Is this allowed?

# Answer
> 15 votes
# APL (Dyalog Unicode), 11 bytesSBCS

Full program. Prints 448-by-448-by-4 array representing a 448-by-448 rgba image.

```
448 448 4⍴0

```

Try it online!

is **r**eshape

# Answer
> 8 votes
# Go, 70

```
import i"image";func a()i.Image{return i.NewRGBA(i.Rect(0,0,448,448))}

```

Never seen a golf in Go before. Defines a function called a that outputs the image

# Answer
> 6 votes
# Java 8

**Saving the image to a file with path `s`, 101 bytes**

```
s->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",new java.io.File(s))

```

Try it online... somehow
**Returning the BufferedImage, 46 bytes**

```
v->new java.awt.image.BufferedImage(448,448,2)

```

**Saving the image to the file `f`, 83 bytes**

```
f->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",f)

```

**Dumping PNG to STDOUT, 92 bytes (thanks ASCII-only!)**

```
v->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",System.out)

```

Try it online!
Thanks to Kevin for saving a byte for the second and fourth solutions!

# Answer
> 6 votes
# Jelly, 8 bytes

```
448ṁ4¬¥þ

```

A niladic Link which yields a 448 by 448 RGBA array of transparent black pixels.

**Try it online!**

### How?

```
448ṁ4¬¥þ - Link: no arguments
448      - 448
       þ - outer-product with: -- i.e. [[f(x,y) for y in [1..448]] for x in [1..448]]
      ¥  -   last two links as a dyad:
   ṁ4    -     mould like [1,2,3,4]  -- e.g. x=7 -> [7,7,7,7]
     ¬   -     logical NOT                       -> [0,0,0,0]

```

# Answer
> 6 votes
## JavaScript (ES6), ~~74~~ 69 bytes

```
f=
(_=document.createElement`canvas`)=>_.toDataURL(_.height=_.width=448)
;document.write(f());
```

Returns a PNG image encoded as a data: URL suitable e.g. for setting as the `src` of an `HTMLImageElement`. Edit: Saved 3 bytes thanks to @Shaggy and a further 2 bytes thanks to @Arnauld.

# Answer
> 6 votes
# Java 8, 23 (or 20) bytes

```
v->new int[448][448][4]

```

Returns a 3D array of 448x448x4 0s.

Try it online.

**Explanation:**

```
v->  // Method with empty unused parameter and 3D integer-array as return-type
  new int[448][448][4]
     // Create a 3D array of dimensions 448 by 448 by 4 (filled with 0s by default)

```

---

```
v->new int[448][448]

```

Returns a 448x448 matrix of 0s.

In Java, RGBA values can be represented by an integer. The hexadecimal `0x00000000` would represent `00` for red, green, blue, and alpha respectively. And `0x00000000` is equal to the integer `0`.

Try it online.

# Answer
> 6 votes
# 05AB1E, ~~12~~ ~~10~~ 9 bytes

```
448LDδ4Å0

```

Try it online.

or alternatively:

```
¾4Ž1ÂDиии

```

Try it online.

-2 bytes thanks to *@Emigna*.
-1 byte thanks to *@Adnan*.

Outputs a 448x448x4 3D list of 0s.

**Explanation:**

```
448LD      # Push a list in the range [1,448], and duplicate it
     δ     # Outer product; apply the following double-vectorized:
      4Å0  #  Push a list of 4 0s: [0,0,0,0]
           # (and output the result implicitly)

  Ž1ÂD     # Push compressed integer 448, and duplicate it
      и    # Create a list of 448 times 448
 4     и   # Transform it into a list of 448 times 448 times 4
¾       и  # Transform it into a list of 448 times 448 times 4 times 0
           # (and output the result implicitly)

```

See this 05AB1E answer of mine (section *How to compress large integers?*) to understand why `Ž1Â` is `448`.

# Answer
> 5 votes
# Processing, 66 bytes

```
PGraphics g=createGraphics(448,448);g.beginDraw();g.save("a.png");

```

# Answer
> 5 votes
# dzaima/APL + APLP5, ~~18~~ 16 bytes

```
{P5.img⍴∘0,⍨448}

```

Function that outputs an image object that can be drawn to the screen (for no effect) or converted back to pixel values.

-2 thanks to ngn!

# Answer
> 5 votes
# Python 2.7, 17 Bytes (22 With Print)

```
[[[0]*4]*488]*488

```

With Print:

```
print[[[0]*4]*488]*488

```

As variable:

```
x=[[[0]*4]*488]*488

```

As an array of RGBA is allowed, that is what I have created above, defaulting to all 0's - meaning black, but totally transparent.

Try it online!

# Answer
> 5 votes
# HTML, 25 bytes

Is this valid?

```
<svg height=448 width=448

```

Test it (`background` applied with CSS so you can "see" it)

# Answer
> 5 votes
# Rust - ~~206~~ ~~201~~ 168 bytes

```
use std::{io::Write,fs::File};fn main(){let mut v=vec![0,0,2,0,0,0,0,0,0,0,0,0,192,1,192,1,32,0];v.extend(vec![0u8;802816]);File::create("o.tga").unwrap().write(&v);}

```

This writes an actual, readable o.tga file, without any libraries or builtin functions, using the TGA binary format per http://paulbourke.net/dataformats/tga/ , by hard coding the width and height into the binary file header.

---

-5 bytes shorten filename, fix img size, @ASCII-only

# Answer
> 5 votes
# C# (Visual C# Interactive Compiler), 21 bytes

```
_=>new int[448,448,4]

```

Try it online!

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), 48 bytes

```
_=>(Enumerable.Repeat((0,0,0,0),200704),448,448)

```

Apparently outputting `[1D array of pixels, width, height]` is ok, so this outputs a tuple of \`(IEnumerable of pixels, width, height).

Try it online!

# C# (Visual C# Interactive Compiler), 58 bytes

```
_=>Enumerable.Repeat(Enumerable.Repeat((0,0,0,0),448),448)

```

The original matrix returning answer.

Since the image IO rules allow output as a matrix of RGB values, this submission outputs a matrix of RGBA values, represented by tuples with four values, all being 0.

Try it online!

# Answer
> 4 votes
# PHP, 192 bytes

Sadly, PHP kinda sucks in that aspect because it requires a whole lot of code. But then again, where doesn't PHP suck.

```
$i=imagecreatetruecolor(448,448);imagesavealpha($i,true);$b=imagecolorallocatealpha($i,0,0,0,127);imagefill($i,0,0,$b);imagepng($i,'i.png');header('Content-type: image/png');readfile('i.png');

```

Ungolfed:

```
$i=imagecreatetruecolor(448,448);         // Create a new image with a set width
imagesavealpha($i,true);                  // Tell PHP to save alphachannels on that image
$b=imagecolorallocatealpha($i,0,0,0,127); // set the actual transparency values
imagefill($i,0,0,$b);                     // Fill the image with the color saved above
imagepng($i,'i.png');                     // Save the file as PNG
header('Content-type: image/png');        // Set the content type for the browser
readfile('i.png');                        // Read the file and output it

```

Obviously, if you just want to create it without outputting it, you can omit the `header()` and `readfile()` commands. Still, it's idiotically long.

# Answer
> 4 votes
**Python 3.7 - PIL Imported, 30 bytes**

```
Image.new("LA",[448]*2).show()

```

This requires an import but has the benefit of creating and displaying an actual image file rather than an abstract empty array.

Explanation:

```
from PIL import Image
Image.new(    // create a new image
mode="LA"     // select LA colour mode, this is grey-scale plus an alpha channel
size=[448]*2  // size argument needs to be a 2D tuple, [448*2] is a better golf shot than (448,448)
color=0       // populates the image with the specified colour, helpfully preset to transparent
).show()      // display the image object

```

Image.show() will open the image in your default image program. In my case this opens a temporary bitmap file in Windows Photo Viewer but results may vary. Arguably this is cheating since the bitmap representation contains no transparency

Variations...

```
Image.new("LA",[448]*2)                 // 24 bytes but doesn't open image
Image.new("LA",[448]*2).show()          // 30 bytes, shows you a bitmap
Image.new("LA",[448]*2).save("x.png")   // 37 bytes, saves image to disk

```

# Answer
> 4 votes
# MATLAB, 31 bytes

```
imwrite(nan(448),'.png','tr',1)

```

Creates a 448 x 448 matrix of `NaN` values, and then uses `imwrite` to save them to a PNG file named `'.png'` and sets the transparency to 1, making it transparent. The `'Transparency'` parameter name is able to be abbreviated to `'tr'` as MATLAB allows for partial string matching of parameter names as long as the shortened version is unique among available parameters.

# Answer
> 3 votes
# Jelly, ~~10~~ 9 bytes

```
x4Wẋ448Ɗ⁺

```

Try it online!

Outputs a 448x448x4 array

Thanks to @JonathanAllan for saving a byte.

# Answer
> 3 votes
# JavaScript (Node.js), 39 bytes

```
_=>[w=448,w,Array(w*w).fill([0,0,0,0])]

```

Apparently outputting `[height, width, 1d array of RGBA values]` is ok.

Try it online!

-3 bytes thanks to @Arnauld

# Answer
> 3 votes
# SmileBASIC, 27 bytes

```
DIM A[448,448]SAVE"DAT:I",A

```

Saves a 2-dimensional 448x448 array filled with 0s to a file named `DAT:I` (Which is shorter than defining a function that returns the array, somehow)

The standard formats (used by all graphics functions) for colors in SmileBASIC are 32 bit ARGB and 16 bit 5551 RGBA, and `0` is transparent in both of them.

# Answer
> 3 votes
# Red, 33 bytes

```
a: make image![448x448 0.0.0.255]

```

Opacity defaults to fully opaque(0)

This is how to use it /a full program/ :

```
Red [ ]
a: make image! [ 448x448 0.0.0.255 ]
view [ image a ]

```

# Answer
> 3 votes
# MathGolf, 10 bytes

```
º4♦7*_ß{.a

```

Try it online!

## Explanation

```
º            push [0]
 4           push 4
  ♦7*        push 64*7=448
     _       duplicate TOS
      ß      wrap last three elements in array (stack is now [[0], [4, 448, 448]])
       {     foreach in [4, 448, 448]
        .    repeat TOS x times
         a   wrap TOS in array

```

This method saves 1 byte compared to the "standard" `♦7*_4º*a*a*`

# Answer
> 3 votes
# ScPL for iOS Shortcuts, 98 bytes

```
Text"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
Base64Encode Decode
ResizeImage 448

```

Shortcut iCloud Link

Takes a 1x1 transparent gif encoded as base64 and resizes it

# Answer
> 2 votes
# Jstx, 24 bytes

```
♪☺ü@/øP♦£Q)%)£Q◄úæD)%)£Q

```

Explanation

```
♪☺ü@ # Push literal 448
/    # Store the first stack value in the a register.
ø    # Push literal 0
P    # Push four copies of the first stack value.
♦    # Push literal 4
£Q   # Push stack values into a list of the size of the first stack value starting with the second stack value.
)    # Push the value contained in the a register.
%    # Push the second stack value the absolute value of the first stack value times.
)    # Push the value contained in the a register.
£Q   # Push stack values into a list of the size of the first stack value starting with the second stack value.
◄úæ  # Push literal \n
D    # Push the sum of the second and first stack values.
)    # Push the value contained in the a register.
%    # Push the second stack value the absolute value of the first stack value times.
)    # Push the value contained in the a register.
£Q   # Push stack values into a list of the size of the first stack value starting with the second stack value.

```

Try it online!

# Answer
> 2 votes
# , 21 bytes

```
array(0,c(448,448,4))

```

Try it online!

Returns a 3D-array of zeroes.

# Answer
> 2 votes
# Japt, 9 bytes

```
448ÆZç4Æ0

```

Try it online!

# Answer
> 2 votes
## C++, SFML, 131 bytes

```
#include <SFML/Graphics.hpp>
void f(){sf::Image i;i.create(448,448);i.createMaskFromColor(sf::Color::Black);i.saveToFile("a.png");}

```

# Answer
> 2 votes
# JavaScript + HTML, 56 bytes

```
location=C.toDataURL()
```

```
<canvas id=C width=448 height=448>
```

Clicking "Run code snippet" will generate a 448x448 transparent PNG in an IFRAME. You may then right-click "Save image as..." to download it to your computer.

---
Tags: code-golf, graphical-output
---


# Question
Title: Find all diagonal counts in only one direction
If I need to get the number of diagonal squares in all directions:

I do the following formula `2 N − 2 − |x − y| − |x + y − N − 1|`

The above example has **13** and that's what the formula gives.

Now, what if you wanted to get the diagonal squares, but only in one direction?

The top right has **4** squares, the top left has **3**, the bottom left has **3** and the bottom right has **3**.

Assume I have that program to compute all legal diagonals for the *Queen*, and as I demonstrated above I can get all diagonals by one step using above formula, written like :

```
int positiveDiagonal = Math.abs(r_q - c_q);
int negativeDiagonal = Math.abs(r_q + c_q - n - 1);
int totalDiagonal = 2 * n - 2 - positiveDiagonal - negativeDiagonal;

```

So, assume there is a soldier on position **(5,5)**, that's make the *Queen* can't move to others diagonals in the same direction with total **4** count.

Sample Input - 1:

* Board length = 8
* Queen on position **(4, 4)**
* There is no soldiers.
* Explanation :

+ Because there is no pieces (*soldiers*), we just get all diagonals we calculated using our formula.

Output - 1: **13**

---

Sample Input - 2:

* Board length = 8
* Queen on position **(4, 4)**
* There is a soldiers on point **(5, 3)**
* Explanation :

+ Because there is a piece or whatever, on point **(5, 3)**, The Queen can't go to **(5, 3)**, **(6, 2)** and **(7, 1)**.

Output - 2: The total diagonals we got from formula is **13** and by calculating the soldier diagonals \[The steps that queen can't go through\], the result would be **10**.

---

Sample Input - 3:

* Board length = 5
* Queen on position **(5, 5)**
* There is a soldiers on point **(1, 1)**
* Explanation :

+ Because there is a piece (*soldier*), on point **(1, 1)**, The Queen can't go to that square.

Output - 3: By subtracting this **square** from total diagonals which equal **4** it's results **3**

---

Sample Input - 4:

* Board length = 5
* Queen on position **(3, 3)**
* Soldiers on positions **(5, 5)** , **(2, 1)**, and **(4, 4)**
* Explanation :

+ Because there is a piece (*soldier*), on point **(5, 5)** and **(4, 4)**, The Queen can't go to these squares.

Output - 4 = **6**

# Answer
# Jelly, ~~41~~ 37 bytes

```
æ.µṬ+ḢṬ$+⁴²x@0¤s⁴µŒD;UŒD$ṣ€1Ẏ=2Ẹ$ƇF¬S

```

Try it online!

A dyadic link that takes as its left argument the zero-indexed positions of the queen and any soldiers as a list (queen first, any subsequent entries a solider) and as right argument the board size. Returns an integer that represents the number of squares available for moves on the diagonal.

### Explanation

```
æ.                                    | dot product of piece positions with board size, right-padded with 1
  µ                                   | start new chain with this as input
   Ṭ                                  | make a boolean array with 1 at the position of each piece
    +ḢṬ$                              | and add the same again for the Queen so the Queen has a 2
        +⁴²x@0¤                       | expand to the board dimension square with zeroes
               s⁴                     | split into lists the length of the board dimension
                 µ                    | start a new chain
                  ŒD;UŒD$             | concatenate the diagonals and the diagonals of the flipped board
                         ṣ€1          | split at soldiers
                            Ẏ         | tighten (make a single list of lists)
                             =2Ẹ$Ƈ    | filter keeping only those diagonals with the Queen in
                                 F¬S  | count the number of zeroes

```
> 0 votes

---
Tags: code-golf, math, chess, factoring
---


title: Generate n-ary numbers

text:
# Question
Title: Generate n-ary numbers
A secondary number is a positive integer whose prime factors (without multiplicity) are all less than or equal to its square root. `4` is a secondary number, because its only prime factor is `2`, which equals its square root. However, `15` is not a secondary number, because it has `5` as a prime factor, which is larger than its square root (`~ 3.9`). Because all prime numbers have themselves as prime factors, no prime number is a secondary number. The first few secondary numbers are as follows:

```
1, 4, 8, 9, 12, 16, 18, 24, 25, 27, 30, 32, 36, 40, 45, 48, 49, 50, 54, 56

```

A tertiary number is defined similarly, except all the prime factors must be less than or equal to its cube root. The first few tertiary numbers are as follows:

```
1, 8, 16, 27, 32, 36, 48, 54, 64, 72, 81, 96, 108, 125, 128, 135, 144, 150, 160, 162

```

In general, an *n-ary number* is one whose prime factors are all less than or equal to its n-th root. Thus, a positive integer \\$x\\$ is an `n`-ary number *iff* each of its prime factors \\$p\\$ satisfies \\$p^n ≤ x\\$. Thus, primary numbers are all positive integers (all prime factors less than or equal to themselves), quartenary numbers have all their prime factors less than or equal to their fourth root, and so on.

## The Challenge

Given integers `k` and `n` as inputs, output the `k`th `n`-ary number. `k` may either be zero- or one-indexed (your choice), and `n` will always be positive.

## Examples

These are the first 20 elements in each sequence up to 10-ary numbers:

```
Primary: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
Secondary: 1, 4, 8, 9, 12, 16, 18, 24, 25, 27, 30, 32, 36, 40, 45, 48, 49, 50, 54, 56
Tertiary: 1, 8, 16, 27, 32, 36, 48, 54, 64, 72, 81, 96, 108, 125, 128, 135, 144, 150, 160, 162
Quarternary: 1, 16, 32, 64, 81, 96, 108, 128, 144, 162, 192, 216, 243, 256, 288, 324, 384, 432, 486, 512
5-ary: 1, 32, 64, 128, 243, 256, 288, 324, 384, 432, 486, 512, 576, 648, 729, 768, 864, 972, 1024, 1152
6-ary: 1, 64, 128, 256, 512, 729, 768, 864, 972, 1024, 1152, 1296, 1458, 1536, 1728, 1944, 2048, 2187, 2304, 2592
7-ary: 1, 128, 256, 512, 1024, 2048, 2187, 2304, 2592, 2916, 3072, 3456, 3888, 4096, 4374, 4608, 5184, 5832, 6144, 6561
8-ary: 1, 256, 512, 1024, 2048, 4096, 6561, 6912, 7776, 8192, 8748, 9216, 10368, 11664, 12288, 13122, 13824, 15552, 16384, 17496
9-ary: 1, 512, 1024, 2048, 4096, 8192, 16384, 19683, 20736, 23328, 24576, 26244, 27648, 31104, 32768, 34992, 36864, 39366, 41472, 46656
10-ary: 1, 1024, 2048, 4096, 8192, 16384, 32768, 59049, 62208, 65536, 69984, 73728, 78732, 82944, 93312, 98304, 104976, 110592, 118098, 124416

```

# Answer
# Jelly, 12 bytes

```
Æf*³<‘Ạ
1Ç#Ṫ

```

Takes **n** and **k** (one-indexed) as command-line arguments.

Try it online!

### How it works

```
1Ç#Ṫ     Main link. Left argument: n. Right argument: k

1        Set the return value to 1.
 Ç#      Execute the helper link above for r = 1, 2, 3, ... until k of them return
         a truthy value. Yield the list of all k matches.
   Ṫ     Tail; extract the last match.

Æf*³<‘Ạ  Helper link. Argument: r

Æf       Compute all prime factors of r.
  *³     Elevate them to the n-th power.
    <‘   Compare all powers with r + 1.
      Ạ  All; return 1 if all comparisons were true, 0 if one or more were not.

```
> 10 votes

# Answer
## JavaScript (ES7), ~~95~~ 90 bytes

Reasonably fast but sadly limited by the maximum number of recursions.

```
f=(k,n,i=1)=>(F=(i,d)=>i-1?d>1?i%d?F(i,d-1):F(i/d,x):1:--k)(i,x=++i**(1/n)|0)?f(k,n,i):i-1

```

### How it works

Rather than factoring an integer **i** and verifying that all its prime factors are less than or equal to **x = floor(i1/n)**, we try to validate the latter assumption directly. That's the purpose of the inner function **F()**:

```
F = (i, d) =>         // given an integer i and a divisor d:
  i - 1 ?             //   if the initial integer is not yet fully factored
    d > 1 ?           //     if d is still a valid candidate
      i % d ?         //       if d is not a divisor of i
        F(i, d - 1)   //         try again with d-1
      :               //       else
        F(i / d, x)   //         try to factor i/d
    :                 //     else
      1               //       failed: yield 1
  :                   //   else
    --k               //     success: decrement k

```

We check if any integer **d** in **\[2 ... i1/n\]** divides **i**. If not, the assumption is not valid and we return **1**. If yes, we recursively repeat the process on **i = i / d** until it fails or the initial integer is fully factored (**i == 1**), in which case we decrement **k**. In turn, the outer function **f()** is called recursively until **k == 0**.

*Note:* Due to floating point rounding errors such as `125**(1/3) == 4.9999…`, the actual computed value for **x** is **floor((i+1)1/n)**.

### Demo

(Here with a 97-byte ES6 version for a better compatibility.)

```
f=(k,n,i=1)=>(F=(i,d)=>i-1?d>1?i%d?F(i,d-1):F(i/d,x):1:--k)(i,x=Math.pow(++i,1/n)|0)?f(k,n,i):i-1

console.log(f(17, 3)); // 144
console.log(f(13, 4)); // 243
console.log(f(4, 10)); // 4096
```
> 6 votes

# Answer
# Brachylog, 21 bytes

```
:[1]cyt
,1|,.$ph:?^<=

```

Try it online!

This answer is one-indexed.

### Explanation

```
Input: [N:K]

:[1]cy              Retrieve the first K valid outputs of the predicate below with N as input
      t             Output is the last one

,1                  Output = 1
  |                 Or
   ,.$ph            Take the biggest prime factor of the Output
        :?^<=       Its Nth power is less than the Output

```
> 6 votes

# Answer
## JavaScript (ES7), ~~93~~ 79 bytes

```
f=(k,n,g=(i,j=2)=>i<2?--k?g(++m):m:j**n>m?g(++m):i%j?g(i,j+1):g(i/j,j))=>g(m=1)

```

I couldn't understand Arnauld's answer so I wrote my own and conveniently it came in at two bytes shorter. Edit: Saved 14 bytes with help from @ETHproductions. Ungolfed:

```
function ary(k, n) {
    for (var c = 1;; c++) {
        var m = c;
        for (var i = 2; m > 1 && i ** n <= c; i++)
            while (m % i == 0) m /= i;
        if (m == 1 && --k == 0) return c;
    }
}

```
> 6 votes

# Answer
# Haskell, 86 bytes

```
m#n=(0:1:filter(\k->last[n|n<-[2..k],all((>0).rem n)[2..n-1],k`rem`n<1]^n<=k)[2..])!!m

```

Explanation:

(`%%%%` denotes the code from the line above)

```
    [n|n<-[2..k],all((>0).rem n)[2..n-1],k`rem`n<1]  -- generates all prime factors of k
    last%%%%^n<=k                                    -- checks whether k is n-ary
    (0:1:filter(\k->%%%%)[2..])!!m                   -- generates all n-ary nubmers and picks the m-th
     m#n=%%%%                                        -- assignment to the function #

```
> 4 votes

# Answer
# Pyth, 13 bytes

```
e.f.AgL@ZQPZE

```

Try it online.

Works really just like the Jelly solution.

```
e.f.AgL@ZQPZE
                 Implicit: read n into Q.
            E    Read k.
 .f              Find the first k integers >= 1 for which
   .A            all
          P      prime factors of
           Z     the number
     gL          are at most
         Q       the n'th
       @         root of
        Z        the number.
e                Take the last one.

```
> 3 votes

# Answer
# Perl 6, 88 bytes

```
->\k,\n{sub f(\n,\d){n-1??n%%d??f n/d,d!!f n,d+1!!d};(1,|grep {$_>=f($_,2)**n},2..*)[k]}

```

My accidental insight is that you don't need to look at every factor of `n`, just the largest one, which is what the internal function `f` computes. Unfortunately, it blows the stack with larger inputs.

Robustness can be improved by adding a primality test, using the built-in `is-prime` method on Ints, at a cost of several more characters.
> 3 votes

# Answer
# Husk, 10 bytes

```
!fS≤ȯ^⁰→pN

```

Try it online!

### Explanation

Took me a while to figure out using  on the empty list returns `1` instead of `-Inf` for  which leaves `1` in the list (otherwise that would cost 2 bytes to prepend it again):

```
!fS≤(^⁰→p)N  -- input n as ⁰ and k implicit, for example: 4 3
!f        N  -- filter the natural numbers by the following predicate (example on 16):
  S≤(    )   --   is the following less than the element (16) itself?
        p    --   ..prime factors (in increasing order): [2]
       →     --   ..last element/maximum: 2
     ^⁰      --   ..to the power of n: 16
             --   16 ≤ 16: yes
             -- [1,16,32,64,81..
!            -- get the k'th element: 32

```
> 3 votes

# Answer
# R, 93 bytes

```
f=function(k,n){x='if'(k,f(k-1,n)+1,1);while(!all(numbers::primeFactors(x)<=x^(1/n)))x=x+1;x}

```

Zero-indexed.

It is a recursive function that just keeps going until it finds the next number in line. Uses to `numbers` package to find the prime factors.
> 2 votes

# Answer
# MATL, 21 bytes

```
x~`@YflG^@>~A+t2G<}x@

```

This solution uses one-based indexing and the inputs are `n` and `k`, respectively.

**Try it Online!**

**Explanation**

```
x       % Implicitly grab the first input and delete it
~       % Implicitly grab the second input and make it FALSE (0) (this is the counter)
`       % Beginning of the do-while loop
  @Yf   % Compute the prime factors of the current loop index
  1G^   % Raise them to the power of the first input
  @>    % Determine if each value in the array is greater than the current index
  ~A    % Yield a 0 if any of them were and a 1 if they weren't
  +     % Add this to the counter (increments only for positive cases)
  t2G<  % Determine if we have reached a length specified by the second input
}       % After we exit the loop (finally), ...
x@      % Delete the counter and push the current loop index to the stack
        % Implicitly display the result

```
> 2 votes

# Answer
# Brachylog v2, 16 bytes

```
{∧.ḋ,1⌉;?^≤}ᶠ⁽t

```

Try it online!

*Credit to Dennis's Jelly solution for getting me thinking in the right direction.*

### Explanation

Here's a slightly ungolfed version that's easier to parse:

```
↰₁ᶠ⁽t
∧.ḋ,1⌉;?^≤

```

Helper predicate (line 2): input is the exponent *n*, output is unconstrained:

```
∧           Break implicit unification
 .ḋ         Get the prime factors of the output
   ,1       Append 1 (necessary because 1 has no prime factors and you can't take
            the max of an empty list)
     ⌉      Max (largest prime factor, or 1 if the output is 1)
      ;?    Pair that factor with the input (n)
        ^   Take factor to the power of n
         ≤  Verify that the result is less than or equal to the output

```

Main predicate (line 1): input is a list containing the index *k* (1-based) and the exponent *n*; output is unconstrained:

```
  ᶠ⁽   Find the first k outputs of
↰₁     calling the helper predicate with n as input
    t  Get the last (i.e. kth) one

```
> 2 votes

# Answer
# APL(NARS), 53 chars, 106 bytes

```
r←a f w;c
c←0⋄r←1
→3×⍳∼∧/(πr)≤a√r⋄→0×⍳w≤c+←1
r+←1⋄→2

```

test:

```
  1 f¨1..20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
  2 f¨1..20
1 4 8 9 12 16 18 24 25 27 30 32 36 40 45 48 49 50 54 56
  3 f¨1..20
1 8 16 27 32 36 48 54 64 72 81 96 108 125 128 135 144 150 160 162
  4 f¨1..20
1 16 32 64 81 96 108 128 144 162 192 216 243 256 288 324 384 432 486 512
  10 f¨1..20
1 1024 2048 4096 8192 16384 32768 59049 62208 65536 69984 73728 78732 82944 93312 98304 104976 110592 118098 124416

```
> 0 votes

# Answer
# Python 2, 114 bytes

```
f=lambda K,n,i=1:K and f(K-all(j**n<=i for j in range(1,i+1)if i%j==0and all(j%k for k in range(2,j))),n,i+1)or~-i

```

Try it online!

1-indexed function.
> 0 votes

# Answer
# Japt, 14 bytes

Takes `n` as the first input and `k` (1-indexed) as the second.

```
@_k e§Vq}aXÄ}g

```

Try it
> 0 votes

---
Tags: code-golf, sequence, primes, integer, factoring
---