title: π Day puzzle for 3/14

text:
# Question
Title: π Day puzzle for 3/14
Happy π Day. The goal of this question is to calculate the area for a circle of radius 3, where A = πr².

The catch is that you have to use the constant π that is defined in a different language than the one you are programming in. For example, you can write a C program that uses Fortran's `MATH::PI`, or a Python program that uses Java's `java.lang.Math.PI`.

Rules:

* Your code must use a stored value of π from a different language for the calculation. (i.e. it must be stored in a constant or math library.)
* All of the code for your program must fit in a single file. For example, You cannot write one program in C to print π, then another in Java to run the C program. (However, you *can* write a Java program that writes and compiles a C program by itself.)
* You cannot download π from a webpage and claim that your constant came from PHP/ASP/HTML.

Here is an example that runs in Bash, and uses Python's stored `math.pi` value:

```
#!/bin/bash
PI=`python -c 'import math; print math.pi'`
bc -l <<< "3 * 3 * $PI"

```

Output:

```
28.27433388231

```

This is a Popularity Contest, so the entry with the most votes after a week wins.

**Edit:** After one week, the prize goes to DigitalTrauma with 93 points. Thanks for the awesome assembler tip - I did not know that the the FPU stored the constant in hardware. I expected this contest to be about finding funny ways to throw clock cycles away, but that one could actually save a few.

* Image courtesy of: http://xkcd.com/10/

# Answer
# C + x86 assembly

Not satisfied with a constant defined in the software of your language? Why not use a language that can access a constant value of PI right from your FPU hardware:

```
#include <stdio.h>

int main (int argc, char **argv) {
    double pi;
    __asm__("fldpi" : "=t" (pi));
    printf("%g\n", 3 * 3 * pi);
    return (0);
}

```
> 130 votes

# Answer
### Python, bash, C, J, PHP and Python3

```
import subprocess

p = subprocess.Popen("""
echo '
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <math.h>

int main(int pi) {
    if (pi == 1) printf("%.5f", M_PI);
    if (pi == 2) printf("o. 1");
    if (pi == 3) printf("<?php printf(\\"%%.5f\\", pi()); ?>");
    if (pi == 4) printf("import math; print(\\" %%.5f\\" %% math.pi)");
    return 0;
}
' > gcc -o pi
./pi
./pi J | jc
./pi and PHP | php
./pi and Python 3 | python3
""", shell=True, stdout=subprocess.PIPE)

values_of_pi = map(float, map(str.strip, p.stdout.read().split()))
pi = max(values_of_pi, key=values_of_pi.count)

print pi * 3 * 3

```

Just to be safe, this program retrieves pi from a few different languages, taking the most agreed upon value. More languages can easily be added for greater reliability.
> 80 votes

# Answer
# PHP/MYSQL

```
$link = mysqli_connect("localhost", "user", "password", "dbname");
$query = mysqli_query($link, 'SELECT PI() AS pi');
$row = mysqli_fetch_assoc($query);
echo 3*3*$row['pi'];

```
> 42 votes

# Answer
## Perl/Tk with C, Pascal, Java, JavaScript, LaTeX3, Prolog, Perl, Scheme, Lua, Python, TeX/PGF

The following Perl script displays a windows that lists the values of π and the calculated area. The value of π is taken from different languages as shown below.

The one-file script:

```
#!/usr/bin/env perl
use strict;
$^W=1;

use Tk;
use Tk::Font;
use Tk::HList;
use Tk::ItemStyle;
use Tk::PNG;

# Function to calculate the area of the circle with radius 3
sub A ($) {
    use bignum;
    return 9*$_[0];
}

my $title = 'Pi Day';

# Configuration of external program names
my %prg = qw[
    Pascal fpc
    Perl perl
    Prolog swipl
    Scheme guile1
    TeX  tex
    LaTeX latex
];
sub prg ($) {
    my $prg = shift;
    return $prg{$prg} // $prg;
}

# Column headers
my @header = (
    '',
    'Language',
    "\N{U+03C0}",
    "A(3) = A(r) = \N{U+03C0}\N{U+2009}r\N{U+00B2}",
);

my $mw = MainWindow->new(
    -title => $title,
);

# Font setup (larger font)
my $font_size = '22';
my $font = $mw->Font();
$font->configure(-size => $font_size);

# ---------
# Utilities
# ---------

# Run program in backticks, quote arguments if needed and some error checking
sub backticks_pi (@) {
    my @cmd = map{/[ ()$;<>|\x22]/ && length > 1 ? "'$_'" : $_} @_;
    print "[@cmd]\n";
    my $catch = `@cmd`;
    if ($? == -1) {
        warn "Failed to execute: $!\n";
    }
    elsif ($? & 127) {
        warn sprintf "Child died with signal %d!\n", $? & 127;
    }
    elsif ($?) {
        warn sprintf "Child exited with value %d!\n", $? >> 8;
    }
    else {
        return $1 if $catch =~ /^\s*(\d+\.\d+)\s*$/
                  or $catch =~ /\bpi\s*=\s*(\d+\.\d+)/;
    }
    warn "Could not find pi in the output of \"@cmd\"!\n";
    return 0;
}

# Run a program with error checking
sub run_cmd (@) {
    print "[@_]\n";
    system @_;
    if ($? == -1) {
        warn "Failed to execute: $!\n";
    }
    elsif ($? & 127) {
        warn sprintf "Child died with signal %d!\n", $? & 127;
    }
    elsif ($?) {
        warn sprintf "Child exited with value %d!\n", $? >> 8;
    }
    else {
        return $1;
    }
    return undef;
}

# Create a bitmap logo
sub make_logo ($$$@) {
    my $name = shift;
    my $logo = shift;
    my $contents = shift;
    my $file = "piday-logo-$name.tmp";
    if ($contents) {
        open(OUT, '>', $file) or die "!!! Error: Cannot write `$file': $!";
        print OUT $contents;
        close(OUT);
    }
    foreach (@_) {
        run_cmd @$_;
    }
    return $mw->Photo(
        -file => $logo,
    ) if -f $logo;
    return undef;
}

# Call foreign language to calculate pi
sub make_pi ($$@) {
    my $file = shift;
    my $source = shift;
    if ($source) {
        open(OUT, '>', $file) or die "!!! Error: Cannot write `$file': $!";
        print OUT $source;
        close(OUT);
    }
    my $cmd_last = pop;
    foreach (@_) {
        run_cmd @$_;
    }
    return backticks_pi @$cmd_last;
}

# Add result list table
my $h = $mw->HList(
    -header  => 1,
    -columns => scalar @header,
    -width   => 100,
    -height  => 20,
    -font    => $font,
)->pack(
  -expand => 1,
  -fill => 'both',
);

# Add header for the result list table
for (0 .. @header-1) {
    $h->header('create', $_,
        -text => $header[$_],
    );
}

# Exit button
my $quit = $mw->Button(
    -text => 'Quit',
    -command => sub {exit},
    -font => $font,
)->pack;

my @list;
my @cmd;
my $pi;
my $source;
my $img;

# GNU C
# -----

$img = make_logo(
    'C',
    'piday-logo-c.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-c-gccegg.png',
        'http://gcc.gnu.org/img/gccegg-65.png',
    ],
    [
        prg('convert'),
        '-scale', '54x64',
        'piday-logo-c-gccegg.png',
        'piday-logo-c.png',
    ],
);

$source = <<'END_SOURCE';
#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>

#define xstr(s) str(s)
#define str(s) #s

int main() {
  long double pi = M_PI;
  printf("pi=%s", xstr(M_PIl));
  return 0;
}
END_SOURCE

$pi = make_pi(
    'piday-c.c',
    $source,
    [
        prg('gcc'),
        '-o', 'piday-c',
        'piday-c.c',
    ],
    [
        prg('./piday-c')
    ],
);

push @list, {
    language => 'GNU C',
    pi       => $pi,
    image    => $img,
};

# Java
# ----

$img = make_logo(
    'Java',
    'piday-java.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-java.svg',
        'https://upload.wikimedia.org/wikipedia/commons/a/a4/Java_logo_and_wordmark.svg',
    ],
    [
        prg('convert'),
        '-scale', '35x64',
        'piday-java.svg',
        'piday-java.png',
    ],
);

$source = <<'END_SOURCE';
public class PiDayJava {
    public static void main(String args[]) {
        System.out.println(Math.PI);
    }
}
END_SOURCE

$pi = make_pi(
    'PiDayJava.java',
    $source,
    [
        prg('javac'),
        'PiDayJava.java',
    ],
    [
        prg('java'),
        'PiDayJava',
    ],
);
push @list, {
    language => 'Java',
    pi       => $pi,
    image    => $img,
};

# Perl
# ----

# Math/Complex.pm: sub pi () { 4 * CORE::atan2(1, 1) }
@cmd = (prg('Perl'), '-e', 'use Math::Complex; print pi');
$pi = backticks_pi @cmd;

my $img = Tk->findINC('Camel.xpm');
$img = $mw->Photo(
    -file => $img,
);

push @list, {
    language => 'Perl',
    pi => $pi,
    image => $img,
};

# Python
# ------

@cmd = (
    prg('echo'),
    'import math;print math.pi',
    '|',
    prg('python'),
);
$pi = backticks_pi @cmd;

$img = make_logo(
    'python',
    'piday-logo-python.png',
    '',
    [
        prg('wget'),
        '-O',
        'piday-logo-python-master.png',
        'http://www.python.org/static/community_logos/python-logo-master-v3-TM.png',
    ],
    [
        prg('convert'),
        '-crop', '111x111+79+33',
        'piday-logo-python-master.png',
        'piday-logo-python-crop.png'
    ],
    [
        prg('convert'),
        '-scale', '64x64',
        'piday-logo-python-crop.png',
        'piday-logo-python.png',
    ],
);

push @list, {
    language => 'Python',
    pi => $pi,
    image => $img,
};

# TeX
# ---

@cmd = (
    prg('TeX'),
    '\input pgf \pgfmathparse{pi}\message{pi=\pgfmathresult}\end',
);
$pi = backticks_pi @cmd;
my $img = make_logo(
    'tex',
    'piday-logo-tex.png',
    '',
    [
        prg('pdftex'),
        '\mag=4000 \nopagenumbers\font\sc=cmcsc10 \sc pgf\bye'
    ],
    [
        prg('pdfcrop'),
        'texput.pdf',
        'piday-logo-tex.pdf',
    ],
    [
        prg('convert'),
        'piday-logo-tex.pdf',
        'piday-logo-tex.png',
    ]
);
push @list, {
    language => 'TeX/PGF',
    pi => $pi,
    image => $img,
};

# LaTeX3
# ------

my $logo_source = <<'END_LOGO';
\mag=4000
\documentclass{article}
\usepackage{hologo}
\pagestyle{empty}
\begin{document}
\hologo{LaTeX3}
\end{document}
END_LOGO

$img = make_logo(
    'latex3',
    'piday-logo-latex3.png',
    $logo_source,
    [
        prg('pdflatex'),
        'piday-logo-latex3.tmp'
    ],
    [
        prg('pdfcrop'),
        'piday-logo-latex3.pdf',
        'piday-logo-latex3-crop.pdf',
    ],
    [
        prg('convert'),
        'piday-logo-latex3-crop.pdf',
        'piday-logo-latex3.png',
    ]
);
$source = <<'END_LATEX3';
\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\msg_term:n { pi=\fp_eval:n { pi } }
\ExplSyntaxOff
\stop
END_LATEX3
$pi = make_pi(
    'piday-latex3.tex',
    $source,
    [
        prg('LaTeX'),
        'piday-latex3.tex',
    ],
);
push @list, {
    language => 'LaTeX3',
    pi => $pi,
    image => $img,
};

print "****************\n";

# Lua
# ---

$img = make_logo(
    'Lua',
    'piday-logo-lua.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-lua.gif',
        'http://www.lua.org/images/lua-logo.gif',
    ],
    [
        prg('convert'),
        '-scale', '64x64', # '50x50',
        'piday-logo-lua.gif',
        'piday-logo-lua.png',
    ],
);

$source = 'print(math.pi)';
$pi = make_pi(
    'piday-lua.lua',
    $source,
    [
        prg('texlua'),
        'piday-lua.lua',
    ]
);
push @list, {
    language => 'Lua',
    pi => $pi,
    image => $img,
};

# JavaScript
# ----------

$img = make_logo(
    'JavaScript',
    'piday-logo-javascript.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-rhino.jpg',
        'https://developer.mozilla.org/@api/deki/files/832/=Rhino.jpg',
    ],
    [
        prg('convert'),
        '-scale', '127x64',
        'piday-logo-rhino.jpg',
        'piday-logo-javascript.png',
    ],
);

$source = 'print(Math.PI)';
$pi = backticks_pi(
    prg('java'),
    '-cp', prg('js.jar'),
    'org.mozilla.javascript.tools.shell.Main',
    '-e', $source,
);
push @list, {
    language => 'JavaScript',
    pi => $pi,
    image => $img,
};

# Scheme
# ------

$img = make_logo(
    'Scheme',
    'piday-logo-scheme.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-lambda.svg',
        'https://upload.wikimedia.org/wikipedia/commons/3/39/Lambda_lc.svg',
    ],
    [
        prg('convert'),
        '-scale', '64x64',
        'piday-logo-lambda.svg',
        'piday-logo-scheme.png',
    ],
);
$source = '(display (* 2 (acos 0)))';
$pi = backticks_pi(
    prg('Scheme'),
    '-c', $source,
);
push @list, {
    language => 'Scheme',
    pi => $pi,
    image => $img,
};

# Prolog
# ------

$img = make_logo(
    'Prolog',
    'piday-logo-prolog.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-swipl.png',
        'http://www.swi-prolog.org/icons/swipl.png',
    ],
    [
        prg('convert'),
        '-scale', '78x64',
        'piday-logo-swipl.png',
        'piday-logo-prolog.png',
    ],
);
$source = ":- format('~15f~n', [pi]).\n";
$pi = make_pi(
    'piday-prolog.pro',
    $source,
    [
        prg('Prolog'),
        '-c', 'piday-prolog.pro',
    ]
);
push @list, {
    language => 'Prolog',
    pi => $pi,
    image => $img,
};

# Pascal
# ------

$img = make_logo(
    'Pascal',
    'piday-logo-pascal.gif',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-pascal.gif',
        'http://www.freepascal.org/pic/logo.gif',
    ]
);
$source = <<'END_PASCAL';
program piday_pascal;

uses sysutils, math;

begin
  writeln(format('%.16f', [pi]));
end.
END_PASCAL
$pi = make_pi(
    'piday-pascal.pas',
    $source,
    [
        prg('Pascal'),
        'piday-pascal.pas',
    ],
    [
        prg('./piday-pascal'),
    ]
);
push @list, {
    language => 'Pascal',
    pi => $pi,
    image => $img,
};

# Sort and fill the table rows
@list = sort {
    my $diff = (length $b->{'pi'} <=> length $a->{'pi'});
    return $diff if $diff;
    return "\L$a->{'language'}\E" cmp "\L$b->{'language'}\E";
} @list;

foreach my $x (@list) {
    my $e = $h->addchild("");
    my $col = 0;
    if ($x->{'image'}) {
        $h->itemCreate($e, $col++,
            -itemtype => 'image',
            -image => $x->{'image'},
        );
    }
    else {
        $col++;
    }
    $h->itemCreate($e, $col++,
        -itemtype => 'text',
        -text => $x->{'language'},
    );
    $h->itemCreate($e, $col++,
        -itemtype => 'text',
        -text => $x->{'pi'},
    );
    $h->itemCreate($e, $col++,
        -itemtype => 'text',
        -text => A $x->{'pi'},
    );
}

MainLoop;

__END__

```

## Languages

The following list shows the languages and the code that is used to get π.

* **GNU C:** GNU extensions are used to get a higher precision of π.

```
#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>

#define xstr(s) str(s)
#define str(s) #s

int main() {
    long double pi = M_PI;
    printf("pi=%s", xstr(M_PIl));
    return 0;
}

```
* **Pascal:** Compiled with Free Pascal.

```
program piday_pascal;

uses sysutils, math;

begin
  writeln(format('%.16f', [pi]));
end.

```
* **Java:**

```
public class PiDayJava {
    public static void main(String args[]) {
        System.out.println(Math.PI);
    }
}

```
* **JavaScript:** Rhino is used for executing JavaScript.

```
print(Math.PI)

```
* **LaTeX3:**

```
\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\msg_term:n { pi=\fp_eval:n { pi } }
\ExplSyntaxOff
\stop

```
* **Prolog:** SWI Prolog is used as Prolog compiler.

```
:- format('~15f~n', [pi]).

```
* **Perl:** For fun and completeness.

```
use Math::Complex;
print pi;

```
* **Scheme:** The uses Scheme implementation is GNU Guile.

```
(display (* 2 (acos 0)))

```
* **Lua:** `texlua` is used as Lua interpreter.

```
print(math.pi)

```
* **Python:**

```
import math
print math.pi

```
* **TeX/PGF:** π is taken from its definition of package pgf and plain TeX is used as TeX format:

```
\input pgf
\pgfmathparse{pi}
\message{pi=\pgfmathresult}
\end

```
> 36 votes

# Answer
# dg

```
print ((import '/math/pi')*3**2)

```

How it works:

dg is a language that compiles to CPython bytecode. Conveniently, it's compatible with python libraries. `import` statements in dg return the object they're importing, so this program basically does this:

```
print (<PYTHON'S MATH.PI>*3**2)

```

No, I don't expect any upvotes. :)
> 16 votes

# Answer
## C++ & Lua 5.2

Nothing says overkill quite like embedding an entire language interpreter to access the pi constant.

```
#include <lua.hpp>
#include <cmath>
#include <iostream>

#define R 3

int main( void )
{
    lua_State* vm = luaL_newstate();

    luaL_openlibs( vm );
    luaL_dostring( vm, "function get_pi() return math.pi end" );
    lua_getglobal( vm, "get_pi" );
    lua_call( vm, 0, 1 );

    lua_Number PI_ = lua_tonumber( vm, -1 );

    std::cout << PI_ * pow( R, 2 ) << std::endl;

    lua_close( vm );
    return 0;
}

```
> 15 votes

# Answer
# bash + PHP + bc

A fairly simple one-liner:

```
echo "scale=14;3*3*`php -r 'echo pi();'`"|bc

```

Output:

```
28.274333882308

```
> 13 votes

# Answer
# MATLAB + Java (21 bytes)

Not sure if MATLAB is cheating, but here we go

```
java.lang.Math.PI*3^2

```

Output: `Format Short`

```
28.2743

```

Output: `Format Long`

```
28.2743338823081

```

Formatting type does not affect the value that is stored, it only impacts how it is printed out into the console
> 10 votes

# Answer
# Bash, Node, Ruby, Python

```
#!/bin/bash

node -pe 'Math.PI' \
| ruby -e 'puts ARGF.read.to_f * 3' \
| python -c 'import sys; print(float(sys.stdin.read()) * 3)'

```
> 10 votes

# Answer
# perl

```
perl -ne '/M_PI\s*([\d.]*)/&&print $1*3*3' < /usr/include/math.h

```
> 7 votes

# Answer
# JavaScript/PHP

Has to be saved as a \*.php file and called in a browser from some server which interprets PHP.

```
<script type="text/javascript">
    alert(3*3*<?php echo M_PI;?>);
</script>

```

Could be golfed by using short tags and substituting 3\*3 with 9 (is this allowed?):

```
<script type="text/javascript">
    alert(9*<?=M_PI?>);
</script>

```

pi() has the same length as M\_PI, so there's no winner.
> 7 votes

# Answer
## Powershell + MS SQL Server

Here is one for Powershell and SQL server (from 2005 up)

```
add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100
$pi=Invoke-Sqlcmd -query "select PI() as sql"
$pi.sql *3*3

```

and here as a single liner:

```
add-pssnapin sqlserverprovidersnapin100;add-pssnapin sqlservercmdletsnapin100;(Invoke-Sqlcmd -query "select PI() as sql").sql*3*3

```

Will post some more later on:)
> 7 votes

# Answer
## Emacs Lisp: writing, compiling, and running C

```
(with-temp-buffer
  (with-temp-file"/#rad.c"(insert"#include<math.h>\n#include<stdio.h>\nint main(void){printf(\"%f\",M_PI*3*3);}"))
  (shell-command"gcc /#rad.c -o /#rad && /#rad"(current-buffer))(string-to-number(buffer-string)))

```

ungolfed

```
(with-temp-buffer
  (with-temp-file "/#rad.c"
    (insert"
#include<math.h>
#include<stdio.h>
int main(void){
  printf(\"%f\",M_PI*3*3);
}"))
  (shell-command "gcc /#rad.c -o /#rad && /#rad"
         (current-buffer))
  (string-to-number(buffer-string)))

```

bonus:

You could triple language this one by running emacs in batch using -eval and surrounding the expression in `(print)`. This would result in Bash running lisp which writes compiles and runs C reads the output and prints it out to your shell in bash.
> 6 votes

# Answer
For this question, I created my own language,called Digits. The syntax consists of p, a constant representing pi, and digits. When run, it returns all of the digits (and p) multiplied together. Here is my interpreter and code, written in Python:

```
def interpret(kode):
    out=1.0
    for i in kode:
        if(i=='p'):
            out*=3.14159265
        else:
            out*=int(i)
    return out
print(interpret("p33"))
```
> 5 votes

# Answer
# bc + dc + bash (30 chars for the golfers)

Here's a golfy little one:

```
$ dc<<<"3d*`bc -l<<<'a(1)*4'`*p"
28.27433388230813914596
$

```
* `bc -l<<<'a(1)*4'` produces pi (it is stored as a constant in the bc math lib for the a() (arctan) function.
* `dc<<<"3d*`pi`*p"` pushes 3 to the stack, duplicates the value on the top of the stack (3) and multiples, then pushes pi to the stack and multiples, then prints the top of the stack.
> 4 votes

# Answer
# OCaml + awk

Nobody likes OCaml?

* Use OCaml to *compute* Pi
* `awk` to calculate Pi\*r2

Here it is:

```
ocaml <<< "4.0 *. atan 1.0;;" | awk '/float/{printf("%.12f", 3*3*$NF)}'

```

The answer is:

```
28.274333882308

```
> 4 votes

# Answer
# VimScript + Python

```
:py import math
:ec pyeval("math.py")*3*3

```

result:

```
28.274334

```
> 4 votes

# Answer
# C++/C

```
#include <math.h>
#include <iostream>

int main(int argc, char** argv) {
    std::cout << 3*3*M_PI << std::endl;
    return 0;
}

```
> 4 votes

# Answer
Very simple, uses bash to access the C math library:

```
bc -l <<< "3 * 3 * `grep -w M_PI /usr/include/math.h | awk '{ print $4 }'`"

```
> 4 votes

# Answer
Since Fortran does not actually have an intrinsic value for pi (which is was OP seems to indicate with the statement "Fortran's `MATH::PI`"), I had to write one for C. I opted, rather than actually defining it, that I'd just determine it using some fast algorithm:

```
#include <math.h>
double pi_eval(){
    double a = 1.0;
    double b = 1.0/sqrt(2.0);
    double t = 0.25;
    double x = 1.0;
    double y;
    int i;

    for(i=0; i<4; i++){
        y = a;
        a = 0.5*(a+b);
        b = sqrt(b*y);
        t -= x*(y-a)*(y-a);
        x *= 2.0;
    }
    return (a+b)*(a+b)/(4.0*t);
}

```

(saved as `pi_calc.c`) Which is then used in `area_calc.f90`:

```
program area_calc
   use, intrinsic :: iso_c_binding
   implicit none

   interface
     function pi_eval() bind(c)
       use, intrinsic :: iso_c_binding
       real(c_double) :: pi_eval
     end function pi_eval
   end interface
   real(c_double) :: pi, area

   pi = pi_eval()
   print *,"area=",3.0*3.0*pi

end program area_calc

```

This outputs the required

```
 area=   28.2743338823081

```

One compiles this using

```
gcc -c pi_calc.c
gfortran -o area pi_calc.o area_calc.f90

```
> 4 votes

# Answer
# R & C++

Requires the `inline` and `Rcpp` packages in R.

```
get.pi <- inline::cxxfunction(plugin="Rcpp", includes="#include <cmath>", body="return wrap(M_PI);")

get.pi() * 3 ^ 2

```

`cxxfunction` creates, compiles and links a C++ function behind the scenes. Yes, there is quite a lot of code generation happening, and `return wrap(M_PI);` is C++ code (along with the `#include` part).
> 3 votes

# Answer
# Java + JavaScript

```
class Pi {
    public static void main(String... args) throws Throwable {
        System.out.println((double) new javax.script.ScriptEngineManager()
                .getEngineByName("JavaScript").eval("Math.PI")
                * Math.pow(3, 2));
    }
}

```

```
28.274333882308138

```
> 3 votes

# Answer
# Julia using Python

```
julia> using PyCall
julia> @pyimport math
julia> math.pi*3^2
28.274333882308138

```

That was fun, I'd never used PyCall before. The interface is super easy to use.
> 3 votes

# Answer
# R + grep + awk + dc

```
echo pi | R --no-save --quiet | grep -v '^>' | awk '{print $2}' | dc -e '?3 3 **p'

```

Output:

```
28.274337

```
> 3 votes

# Answer
## Using Lua's π in Java

This program uses the library LuaJ to evaluate Lua in Java and get π. It also squares the area with Lua. Enjoy!

```
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine se = sem.getEngineByName("luaj");
    se.eval("pi = math.pi");
    double pi = (double) se.get("pi");

    int r = 3;

    se.eval("radius = "+r);
    se.eval("rsquared = math.pow(radius, 2)");
    int rsquared = (int) se.get("rsquared");

    double area = pi * rsquared;
    System.out.println("For a circle with a diameter of "+r+", the area is "+area+".");

```

The output:

`For a circle with a diameter of 3, the area is 28.274333882308138.`
> 3 votes

# Answer
# Jython + Java

This should work in Jython. I'm not sure, as I have no way to test it ATM.

```
from java.lang import Math
print Math.PI * 3 ** 2

```

Jython can access the Java libraries, so I can just import the Math class from java.lang and use its PI constant to calculate the area of the circle.

Golfed:

```
import java.lang.Math.PI;print PI*3*3

```

Or, if I'm allowed to code in 3^2:

```
import java.lang.Math.PI;print PI*9

```
> 2 votes

# Answer
# bash (PI from perl,python,c)

Maybe if we combine everything we've got, we get a more accurate result? :)

```
#!/bin/bash
exec >&>(bc -l|tail -n1)
perl <<EOF
use Math::Trig;
print pi
EOF
echo -n +
python <<EOF
import sys
from math import pi
sys.stdout.write(str(pi))
EOF
echo -n +
cat > pi.c <<EOF
#include <math.h>
main(){printf("%.16f",M_PI);}
EOF
gcc pi.c -o pi &>/dev/null
./pi
rm -f pi pi.c
echo ";"
echo "(last/3)*3.^2"

```
> 2 votes

# Answer
## Ruby+Python

```
puts `python -c "from math import pi; print pi"`.to_f * 3**2

```
> 2 votes

# Answer
HTML + PHP

```
<html><body>
value of area of circle is <br>
<?php echo 3*3*M_PI; ?>
</body></html>

```

Confused whether it satisfy the 3rd rule. but since M\_PI is already used so it should count.
> 2 votes

# Answer
# **ACTIONSCRIPT3 + javascript(using parse.com)**

```
Parse.CFunction('getPi',{},function(returned){trace(3*3*returned.result)});

```

parse class link https://github.com/camdagr8/AS3-Parse-Class/blob/master/com/illumifi/Parse.as

with code:

```
public static function CFunction(className:String, params:Object = null, success:Function = null, error:Function = null) {
            var url:String = Parse.api + "functions/" + className;
            Parse.Call(url, URLRequestMethod.POST, params, null, success, error);
        }

```

parse main.js:

```
Parse.Cloud.define("getPi", function(request, response) {
  response.success(Math.PI);
});

```

result:

```
28.274333882308138

```
> 2 votes

# Answer
## Mathematica + R

```
Needs["RLink`"]
InstallR[]
 = REvaluate["pi"][[1]];
R = 3;
 R^2

```
> 2 votes

# Answer
# bash + html + APL

```
 echo '<html><body><p>○3*2</p></body></html>' | w3m -dump -T text/html | apl -f -

```
> 2 votes

# Answer
Ok I'll bite...

# AWK + PHP

```
$ awk -v PI=`php -r 'echo pi();'` 'BEGIN{print 3*3*PI}'

```

# PHP + AWK

```
$ php -r "echo 3*3*`awk 'BEGIN{printf 4*atan2(1,1)}'`;"

```

# BASH + PHP

```
$ PI=$(php -r 'echo pi();');C=$((${PI/\./}*3*3));echo ${C:0:2}.${C:2}

```

nJoy!
> 2 votes

# Answer
## Ruby + Python + C++ + Batch (if you want to include it)

Oh, this took much longer than I wanted it to. As far as I know this will only work on Windows, though if you edit the `rm` command it may work on Linux.

Here's what it does:

1. Ruby creates pi.cpp
2. Ruby runs batch code to compile pi.cpp using MinGW or GCC
3. Ruby runs pi.exe
4. Pi.exe runs Python code to find pi
5. Python saves pi to pi.txt
6. Ruby reads pi.txt, does the math to find the area, and prints it

Comment out the last line to see the remnants of the process.

```
p = "\\\"import math; import subprocess; f = open('pi.txt', 'w'); print(math.pi, file=f)\\\""

c = '''#include <iostream>
#include <cstdlib>

int main()
{
    system("python -c '''+p+'''");
    return(0);
}'''

command2 = "g++ pi.cpp -o pi.exe"
command3 = "pi.exe"
command4 = "rm pi.cpp && rm pi.exe && rm pi.txt"

File.open("pi.cpp", "w+") do |file|
    file.puts c
end

system(command2)
system(command3)

my_very_own_pi = ''

File.open("pi.txt", "r") do |file|
    my_very_own_pi = file.gets
end

puts "The answer is: #{(3**2)*(my_very_own_pi.to_f())}"

system(command4)

```
> 2 votes

# Answer
## Obligatory GolfScript+Ruby answer :)

```
"#{Math::PI*9}"

```
> 2 votes

# Answer
## ASP.net / JS

```
alert(3*3*<%Response.Write(Math.PI)%>)

```
> 1 votes

# Answer
# Matlab & Python

```
[~, pi] = system('python -c "import math; print(math.pi)"');
area = str2num(pi) * 3^2;
disp(area)

```

Output:

```
28.274333882308138

```
> 1 votes

# Answer
## Groovy + Java (Someone had to do it... :) )

```
println java.lang.Math.PI * 3 * 3

```
> 1 votes

# Answer
HTML + JAVASCRIPT

```
<label>Price 1</label><input type="text" class="price" /><br/>
<label>Price 1</label><input type="text" class="price" /><br/>
<label>Total</label><input type="text" id="total" /><br/>
<script>
var $prices=$('.price').keyup(calcTotal);
function calcTotal(){
  var tot=Math.PI;
  $prices.each(function(){
      tot*=$(this).val() | 0;
    });
   $('#total').val( tot);
}
</script>

```
> 1 votes

# Answer
## Java & JavaScript

```
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main {
    public static void main(String[] args) {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        try {
            System.out.println((double)engine.eval("Math.PI") * 3 * 3);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

```
> 1 votes

# Answer
# C# and VB.NET

This one creates a VB.NET assembly on the fly (using Microsoft CodeDom) to get the value of Pi. No need to invoke shells, external interpreters, or any of those other tricks. You get two languages, not just in a single process, but in a single thread!

```
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using Microsoft.VisualBasic;

namespace PiDay2014CSharpConsole
{
    public class AreaCalculator
    {
        private double Pi()
        {
            StringBuilder vb = new StringBuilder();
            vb.AppendLine("Public Class PiDay");
            vb.AppendLine("    Public Function VbPi() As Double");
            vb.AppendLine("        Return System.Math.PI");
            vb.AppendLine("    End Function");
            vb.AppendLine("End Class");
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            cp.ReferencedAssemblies.Add("System.dll");
            CodeDomProvider provider = new VBCodeProvider();
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, vb.ToString());
            var piDay = cr.CompiledAssembly.CreateInstance("PiDay");
            Type t = piDay.GetType();
            object result = t.InvokeMember("VbPi",
               BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
               null, piDay, null);
            return (double)result;
        }

        public double CalculateArea(double radius)
        {
            return Pi() * radius * radius;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            AreaCalculator calc = new AreaCalculator();
            Console.Out.WriteLine("{0}", calc.CalculateArea(3.0));
            Console.In.ReadLine();
        }
    }
}

```

Output:

`28.2743338823081`
> 1 votes

# Answer
# Ruby+Python

```
require 'bigdecimal'
require 'bigdecimal/util'
File.open("pi.py", 'w') {|f| f.write("import math\nfrom decimal import *\ngetcontext().prec = 100\nprint Decimal(math.pi)") }
puts %x(python pi.py).to_d*3*3
%x(rm pi.py)

```

result:

```
0.28274333882308138043981671216897666454315185546875E2

```
> 1 votes

# Answer
**x86 Assembly Language**

NASM syntax

```
global _start

section .data
val: dq 3.0

section .text

_start:

fldpi
fld qword [val]
fmul st0,st0
fmul st1,st0

```
> 0 votes

---
Tags: popularity-contest, pi, polyglot
---


title: How long is this string?

text:
# Question
Title: How long is this string?
It's strange this question hasn't been asked yet, so here it is:

**Calculate the length of a string given through STDIN**

## Rules

* As said, your string will be given through STDIN, not via command line arguments
* Print the length of the string to STDOUT
* Only ASCII chars will be given, **and all printable ASCII chars count!**
* This is a , so the answer with the shortest length wins!

Good Luck and have fun!

# Answer
> 7 votes
# Shakespeare Programming Language, 156 bytes

Thanks JoKing for nice trick with `[Exeunt]`.

`,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Ajax and Page]Ajax:Open mind Be you nicer zero?Page:If soyou be the sum ofa cat you.If solet usact I.Open heart`

Try it online!

# Answer
> 4 votes
## Golfscript (1 byte)

```
,

```

And that's why this question hadn't already been asked.

# Answer
> 3 votes
# 05AB1E, 1 byte

```
g

```

Try it online.

**Explanation:**
(As if it would be necessary..)

```
     # Implicit input from STDIN
g    # Length
     # Implicit output to STDOUT

```

# Answer
> 3 votes
# Java 8, 63 bytes

A lambda taking empty input and throwing `IOException`.

```
n->{int c=0;while(System.in.read()>=0)c++;System.out.print(c);}

```

Try It Online

# Answer
> 3 votes
# brainfuck, 163 bytes

```
,[>+<,]>[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<[.[-]<]<

```

Try it online!

Somebody had to make this a little interesting.

## Explanation:

```
,[>+<,]>

```

This is a modified cat program that, rather than outputting each read value, increments the 2nd cell each time a value is read.

The entire rest of the program is for outputting a cell's value as a number rather than an ASCII codepoint.

# Answer
> 2 votes
# Hexagony, 11 bytes

```
,~<@!"/>"){

```

Try it online!

More readable version:

```
  , ~ <
 @ ! " /
> " ) { .
 . . . .
  . . .

```

# Answer
> 1 votes
# Pyth, 2 bytes

```
lz

```

**Explanation**

```
l          #length of
 z         #input

```

Try it online!

# Answer
> 1 votes
# Haskell, ~~25~~ 20 bytes

<sup>-5 bytes for making this a function only (initially thought that it has to be a full program)</sup>

```
interact$show.length

```

Try it online!

# Answer
> 1 votes
# Brain-Flak \+ `-a` flag, 6 bytes

Even Brain-Flak has a built-in for this challenge...

```
([]<>)

```

Try it online!

Without using `[]` but still rather simple (10 bytes): `({<{}>()})`

# Answer
> 1 votes
# Whitespace, ~~73~~ 64 bytes

```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][S N
S _Duplicate][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S S S T  S T T   S T T   S N
_Push_182][T    S S T   _Subtract][N
T   S S N
_If_0_jump_to_Label_PRINT_AND_EXIT][S S S T N
_Push_1][T  S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_AND_EXIT][T N
S T _Print_to_STDOUT]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Input requires a trailing , because Whitespace has no way to tell when the input-characters are complete. Whitespace only has two STDIN inputs: integer or character. A full string should be inputted one by one, but Whitespace doesn't know when it has all. So perhaps this answer is non-competing due to the restriction of Whitespace, but I've chosen a character outside the printable ASCII range to add as leading character for inputs, so the program knows when to stop and output the length.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer counter = 0
Start LOOP:
  Integer input = STDIN as character
  If(input == '¶')
    Jump to function PRINT_AND_EXIT
  counter = counter + 1
  Jump to next iteration of LOOP

function PRINT_AND_EXIT:
  Print counter as integer to STDOUT

```

**Example input: `acb¶`**

```
Command        Explanation                 Stack        HEAP                    STDIN   STDOUT  STDERR

SSSN           Push 0                      [0]
NSSN           Create Label_LOOP           [0]
 SNS           Duplicate top (0)           [0,0]
 SNS           Duplicate top (0)           [0,0,0]
 TNTS          Read STDIN as character     [0,0]        {0:97}                  'a'
 TTT           Retrieve                    [0,97]       {0:97}
 SSSTSTTSTTSN  Push 182                    [0,97,182]   {0:97}
 TSST          Subtract top two (97-182)   [0,-85]      {0:97}
 NTSSN         If 0: Jump to Label_EXIT    [0]          {0:97}
 SSSTN         Push 1                      [0,1]        {0:97}
 TSSS          Add top two (0+1)           [1]          {0:97}
 NSNN          Jump to Label_LOOP          [1]          {0:97}

 SNS           Duplicate top (1)           [1,1]        {0:97}
 SNS           Duplicate top (1)           [1,1,1]      {0:97}
 TNTS          Read STDIN as character     [1,1]        {0:97,1:99}             'c'
 TTT           Retrieve                    [1,99]       {0:97,1:99}
 SSSTSTTSTTSN  Push 182                    [1,99,182]   {0:97,1:99}
 TSST          Subtract top two (99-182)   [1,-83]      {0:97,1:99}
 NTSSN         If 0: Jump to Label_EXIT    [1]          {0:97,1:99}
 SSSTN         Push 1                      [1,1]        {0:97,1:99}
 TSSS          Add top two (1+1)           [2]          {0:97,1:99}
 NSNN          Jump to Label_LOOP          [2]          {0:97,1:99}

 SNS           Duplicate top (2)           [2,2]        {0:97,1:99}
 SNS           Duplicate top (2)           [2,2,2]      {0:97,1:99}
 TNTS          Read STDIN as character     [2,2]        {0:97,1:99,2:98}        'b'
 TTT           Retrieve                    [2,98]       {0:97,1:99,2:98}
 SSSTSTTSTTSN  Push 182                    [2,98,182]   {0:97,1:99,2:98}
 TSST          Subtract top two (98-182)   [2,-84]      {0:97,1:99,2:98}
 NTSSN         If 0: Jump to Label_EXIT    [2]          {0:97,1:99,2:98}
 SSSTN         Push 1                      [2,1]        {0:97,1:99,2:98}
 TSSS          Add top two (2+1)           [3]          {0:97,1:99,2:98}
 NSNN          Jump to Label_LOOP          [3]          {0:97,1:99,2:98}

 SNS           Duplicate top (3)           [3,3]        {0:97,1:99,2:98}
 SNS           Duplicate top (3)           [3,3,3]      {0:97,1:99,2:98}
 TNTS          Read STDIN as character     [3,3]        {0:97,1:99,2:98,3:182}  '¶'
 TTT           Retrieve                    [3,182]      {0:97,1:99,2:98,3:182}
 SSSTSTTSTTSN  Push 182                    [3,182,182]  {0:97,1:99,2:98,3:182}
 TSST          Subtract top two (182-182)  [3,0]        {0:97,1:99,2:98,3:182}
 NTSSN         If 0: Jump to Label_EXIT    [3]          {0:97,1:99,2:98,3:182}

NSSSN          Create Label_EXIT           [3]          {0:97,1:99,2:98,3:182}
 TNST          Print as integer to STDOUT  []                                          3
                                                                                error

```

Stops program with error: No exit defined.

# Answer
> 1 votes
# APL+WIN, 2 bytes

Prompts for character string input then counts characters:

```
⍴⍞

```

# Answer
> 1 votes
## Keg, 3 bytes

```
?!.

```

Well, I can't golf this program well.

TIO

# Answer
> 0 votes
# Octave, 14 bytes

```
nnz(input(''))

```

Try it online!

# Answer
> 0 votes
# , 23 bytes

```
cat(nchar(readLines()))

```

Try it online!

# Answer
> 0 votes
# Retina, 3 bytes

```
s`.

```

Try it online!

This isn't even technically a built-in function, but it is a central feature of the language: counting matches of a regular expression, in this case `.` (wildcard matching any character). The ``` makes Retina treat the character(s) preceding it in the line as configuration, so `s` activates SingleLine mode, which makes `.` match newlines also, because they are part of printable ASCII.

# Answer
> 0 votes
## Batch, 182 bytes

```
@set s=
@set/ps=
@set "t=%s:"=""%"
@if "%t:"=""%"=="""=""""" goto g
@for %%s in ("%s:"=%" "%t%")do @echo(%%~s>>_
@for %%s in (_)do @set s=%%~zs
@del _
:g
@cmd/cset/as/2-2*!!s

```

Testing for the empty string without breaking when quotes were present was cumbersome! Explanation:

```
@set s=

```

Clear `s` as `set/p` leaves `s` unchanged if the input was empty.

```
@set/ps=

```

Take input on STDIN into `s`.

```
@set "t=%s:"=""%"

```

Try to quote all of the quotes in `s`. However, if `s` is empty, Batch throws a wobbly, and sets `t` to `"=""` instead, which still has an odd number of quotes.

```
@if "%t:"=""%"=="""=""""" goto g

```

Quote all of the quotes in `t`, and compare the result to `""=""""`. This can only happen if `s` was empty, in which case we skip the measurement step.

```
@for %%s in ("%s:"=%" "%t%")do @echo(%%~s>>_

```

Print `s` without quotes and `s` with quoted quotes on separate lines to a temporary file. The `(` is needed in case `s` only contains quotes.

```
@for %%s in (_)do @set s=%%~zs

```

Obtain the length of the temporary file.

```
@del _

```

Delete the temporary file.

```
:g

```

Jump here if the input was empty.

```
@cmd/cset/as/2-2*!!s

```

Halve and subtract 2 from the length of the temporary file. However if the input was empty then `s` will be treated as the numeric value zero, and the result of the expression is then zero as desired.

117 bytes without empty string support:

```
@set/ps=
@for %%s in ("%s:"=%" "%s:"=""%")do @echo(%%~s>>_
@for %%s in (_)do @set s=%%~zs
@del _
@cmd/cset/as/2-2

```

93 bytes if support for `"`s is not necessary (84 bytes without `"` or empty string support):

```
@set s=
@set/ps=
@set n=0
:l
@if not "%s%"=="" set/an+=1&set "s=%s:~1%"&goto l
@echo %n%

```

Empty strings and quotes can even be handled for 212 bytes without resorting to file length builtins:

```
@set s=
@set/ps=
@set "t=%s:"=""%"
@set n=0
@if "%t:"=""%"=="""=""""" goto g
:l
@set/an+=1
@set "s=%t:~,1%%t:~,1%"
@if "%s%" neq """" set "t=.%t%"
@set "t=%t:~2%"
@if not "%t%"=="" goto l
:g
@echo %n%

```

Here after quoting the quotes in `s` we have to be careful to double the first character of `t` in case it is a quote, then if it is not then prefix a dummy character to `t` so that the first two characters may be safely removed. This ends up counting the quoted quotes as single characters again.

# Answer
> 0 votes
# Ruby, 16 Bytes

This was rather easy.

```
puts gets.length

```

needs no explanation ;)

# Answer
> 0 votes
# Perl 6,  ~~15~~  14 bytes

```
slurp.codes.say

```

Try it

```
say +$*IN.comb

```

Try it

---

* `slurp` reads everything
* `codes` gets the number of Unicode codepoints
(this is different than `chars` for `\r\n`)
* `say` print the `.gist` with trailing newline
(`put` could have been used, which just adds the newline)
* `&prefix:« + »` converts to `Numeric`
* `$*IN` is STDIN
* `comb` splits its input into a sequence of characters
(Which when converted to `Numeric` returns a count)

# Answer
> 0 votes
# Python 3, 19 bytes

```
print(len(input()))

```

Try it online!

# Answer
> 0 votes
## `s`, 1 byte

```
k

```

## Explanation

```
% s: we have to read from STDIN.
% Implicitly prepend an input
k % (k)ount the number of items in this thing
% Implicit output

```

## How do I use the parameter?

The cli param system is quite weird (to allow people to type less), so here is an example of how it is used:

```
$ ..\python W.py code.w [] s
'Hello'
Code: k
#0: a []
#1: k ['a[0]']
out: lambda a:mylen(a[0])
5

```

---
Tags: code-golf, string, counting
---


title: Decompose Commutators

text:
# Question
Title: Decompose Commutators
A theorem in this paper1 states that every integral n-by-n matrix **M** over the integers with **trace M = 0** is a *commutator*, that means there are two integral matrices **A,B** of the same size as **M** such that **M = AB - BA**.

### Challenge

Given an integral matrix **M** with **trace M = 0** find some integral matrices **A,B** such that **M = AB - BA**.

### Details

* Let **A,B** be two matrices of compatible size, then **AB** denotes the matrix product of **A** and **B** which in general does not commute, so in general **AB = BA** does *not* hold. We can "measure" how close two matrices are to commuting with eachother by measuring how close the *commutator* \- which is defined as **AB - BA** \- is to being zero. (The commutator is sometimes also written as **\[A, B\]**.)
* The *trace* of a matrix is the sum of the diagonal entries.
* The decomposition is not necessarily unique. You have to provide one decomposition.

### Examples

Since the decomposition is not unique, you might get different results that are still valid. In the following we just consider some possible example.

```
M:       A:      B:
[ 1  0]  [1  1]  [1  0]
[-2 -1]  [1 -1]  [1  1]

```

In the trivial case of **1 x 1** matrices only **M = 0** is possible, and any two integers **A,B** will solve the problem

```
M:   A:   B:
[0]  [x]  [y] for any integers x,y

```

Note that for **M = 0** (a zero matrix of arbitrary size) implies **AB = BA**, so in this case any two matrices **(A, B)** that commute (for example if they are inverse to each other) solve the problem.

```
M:     A:     B:
[0 0]  [2 3]  [3   12]
[0 0]  [1 4]  [4   11]

M:           A:         B:
[11 12  12]  [1  1  1]  [1  2  3]
[ 7  4   0]  [0  1  1]  [4  5  6]
[ 0 -7 -15]  [0  0  1]  [7  8  9]

M:                    A:          B:
[-11811 -9700 -2937]  [ 3 14 15]  [ 2 71 82]
[ -7749 -1098  8051]  [92 65 35]  [81 82 84]
[  3292  7731 12909]  [89 79 32]  [59  4 52]

```

1: *"Integral similarity and commutators of integral matrices"* by Thomas J.Laffey, Robert Reams, 1994

# Answer
# 05AB1E, ~~36~~ 29 bytes

```
ÄàD(Ÿsgãsgãã.ΔD2FsN._`øδ*O}-Q

```

-7 bytes thanks to *@ovs* in another answer of mine.

Extremely slow since I'm using a brute-force approach with three cartesian products. But performance is irrelevant for challenges I guess (would love to see this same challenge as or ).

Try it online (only works for matrices of size 2x2, and even then usually times out if the absolute maximum of the integers in the matrix \\$M\\$ is too large..)
Verify whether the output \\$\[A,B\]\\$ results in the input \\$M\\$.

**Explanation:**

*Assumes* all the integers used in the resulting matrices \\$\[A,B\]\\$ will be within the range \\$\[-\max(\lvert M\rvert), \max(\lvert M\rvert)\]\\$. If you know any way to prove or disprove this assumption, let me know.
Note that there are of course matrices \\$\[A, B\]\\$ with integers larger than the integers of the resulting matrix \\$M\\$. But this \\$M\\$ will have other possible \\$\[A, B\]\\$ which are within this min-max range. I.e. \\$\[A,B\]=\\$ `[[[1,2],[3,4]], [[-1,-2],[-3,-3]]]` will have \\$M=\\$ `[[0,2],[-3,0]]`, but using this \\$M\\$ to find a possible \\$\[A,B\]\\$ will result in `[[[3,2],[3,3]], [[2,2],[3,3]]]`, which are all within the range \\$\[-3,3\]\\$.

Let me start with an explanation of `2FsN._`øδ*O}-`, which will calculate \\$M = AB-BA\\$ of a given matrix-pair \\$\[A,B\]\\$ (which is the same code as in the verifier TIO-link above).

```
2F       # Loop 2 times:
  s      #  Swap the top two values on the stack
         #  (so the matrix-pair is at the top again after the first iteration)
   N._   #  Rotate the pair of matrices the (0-based) loop-index amount of times
         #  (to reverse the order from [A,B] to [B,A] in the second iteration)
      `  #  Push both matrices separated to the stack
  ø      #  Zip/transpose the top matrix; swapping rows/columns
   δ     #  Apply double-vectorized:
    *    #   Multiply
     O   #  And then sum each inner row together
 }       # After the loop:
  -      # Subtract the values at the same positions in the two matrices from each other

```

As for the rest of the program to create all possible matrices and brute-force over them:

```
Ä        # Convert each integer in the (implicit) input-matrix `M` to its absolute value
 à       # Pop and push the flattened maximum of these absolute values of `M`
  D(     # Duplicate it, and negate the maximum
    Ÿ    # Pop both and push a list in the range [max, -max]
s        # Swap to get the input matrix again
 g       # Pop and push its length to get the matrix dimension
  ã      # Create the cartesian product of the [max, -max]-list that many times
         # (i.e. if the input-matrix has a dimension of 3, we'll now have all possible
         #  triplets of integers within the [max, -max]-range)
sgã      # Do the same, to create all possible combinations of these triplets
         # (so we now have all possible matrices of the same dimensions as the input-matrix,
         #  using integers within the [max, -max]-range)
ã        # Cartesian product yet again (defaults to 2) to create all possible pairs of matrices
.Δ       # Then find the first pair of matrices which is truthy for:
  D      #  Duplicate the current pair
   2FsN._`øδ*O}-
         #  Calculate M as mentioned above
    Q    #  And check if its equal to the (implicit) input-matrix
         # (after which this matrix-pair is output implicitly as result)

```

*Just to give an idea of how inefficient this brute-force approach is:*

The given example input-matrix \\$M=\\$ `[[11,12,12],[1,1,1],[1,2,3]]` of the challenge description, will create all possible matrix-pairs of the same 3x3 dimensions with integers in the range \\$\[-12,12\]\\$. This means the list of matrix-pairs will contain \\$(((12^2+1)^3)^3)^2=802830827198685151406498569488525390625\\$ matrix-pairs.

And the given example input-matrix \\$M=\\$ `[[-11811,-9700,-2937],[3,14,15],[2,71,82]]` would result in \\$(((11811^2+1)^3)^3)^2=400239694511528196808960294025932709663435907226315389994060779277222573307615163703296535923733538440194289670070277830289553752923910908747710464\\$ matrix-pairs..
> 3 votes

---
Tags: code-golf, math, integer, matrix, linear-algebra
---


title: Can this knot be colored with 3 colors?

text:
# Question
Title: Can this knot be colored with 3 colors?
In this challenge you will be asked to take a knot and determine if it can be colored in a particular way.

First we draw a diagram of the knot. We use the standard way of drawing knots where we put gaps in strands where they pass under each other. Here is an example of some knots drawn this way:

*Taken with permission from wikimedia user Jkasd*

Once we have drawn the knot we want to color the knot with three colors such that:

* Every contiguous length of string in the knot's diagram is colored with the same color (String on the opposite ends gaps where we pass under do not need to be the same color)
* The three strands that meet at an intersection are either
    + all the same color
    + or all different colors
* At least two colors must be used in total

Some knots can be drawn in this way for example:

*Taken with permission from wikimedia user n4nojohn*

and some cannot for example

*Taken with permission from wikimedia user n4nojohn*

Your task is to take a knot as input and determine whether or not it can be colored. You may take a knot in any reasonable format (some examples listed below) and you may output two distinct consistent values one indicating that it can be colored one that it cannot.

This is so answers will be scored in bytes with fewer bytes being better.

---

## Example input formats

Some nice ways of taking knots as input:

# Answer
# Haskell, ~~249~~ 246 bytes

```
(i#x)a=[head$[x|j==i]++[s]|(j,s)<-zip[0..]a]
(s%i)[]=i<2&&elem 2(concat s)
(s%i)((l,a):b)|l,[]<-s!!a=or[(a#[i,x]$s)%x$b|x<-[1..3]]|[]<-s!!a=(a#[i]$s)%i$b|[x]<-s!!a,x==i=s%i$b|[x]<-s!!a=s%(6-i-x)$b|u<-s!!a=mod(sum$i:u)3<1&&(s%i)b
f x=(x>>[[]])%1$x

```

Try it online!

Takes input as a Gauss Code, (`[(Bool, Int)]`) where `False` represents crossing over and `True` represents under

## Explanation

This algorithm works by stepping though each intersection and trying to resolve the colors of that intersection. It keeps track of what color the strand is and branches if multiple colors are possible at a given point.

The function that we build to do this is called `r`. It takes, 3 arguments:

* The Gauss Code of the knot we are working on (which it will consume in order)
* A list of "intersections" and what colors we have already filled in
* The color of the strand where we are currently processing.

Our intersections are represented as a list of colors (`Int`), which we know to be at that intersection. There are three possible states for this:

* It is empty, meaning we have not visited this intersection yet.
* It has one element, meaning we visited the intersection going *over*.
* It has two elements (possibly equal), meaning we visited the intersection going *under*.

We can't have 3 elements because when we visit an intersection the second time we don't have to add the third element since we are never coming back. Since we don't have to and this is code-golf, we don't.

At each step of the way we can use a very simple case analysis to determine how to branch. Here is a diagram showing each case and the possible outputs (no possible outputs is a contradiction and return `False` if we reach it). Incoming color and location are indicated with the small arrow.

Here are some sample paths of execution on the granny knot and the figure 8 knot as shown in the question. I skip over steps where we went over a unvisited intersection, since they are quite trivial and the diagrams are quite large even without them.

Since Haskell is lazy we only ever evaluate two of these paths, the left-most path, and when that fails because the result doesn't have two colors we evaluate the second left-most. Since that one passes we exit without further evaluation.

Here the only branch that does not encounter an error colors everything the same way.

Here is my code ungolfed a bit and commented. I will expand this a little bit shortly.

```
-- Update an element of a list
q i x a=[head$[x|j==i]++[s]|(j,s)<-zip[0..]a]
-- Perform the algorithm
-- Iterates through the intersections in order
-- It records colors at each intersection and searches for a contradiction
r[]s i=i<2&&elem 2(concat s)
r((l,a):b)s i
  -- If we reach a new intersection passing under
  -- Branch on the three possible colors
  -- label the intersection with the incoming and outgoing colors
  |l,[]<-s!!a=or[r b(q a[i,x]s)x|x<-[1..3]]
  -- If we reach a new intersection passing over
  -- label the intersection with the incoming color
  |[]<-s!!a=r b(q a[i]s)i
  -- If we reach an intersection going under where the over strand is the same color as the incoming
  -- The outgoing strand is the same color
  |[x]<-s!!a,x==i=r b s i
  -- If we reach an intersection going under where the over strand is different from the incoming
  -- The outgoing strand is the third color
  |[x]<-s!!a=r b s(6-i-x)
  -- If we reach an intersection going under
  -- Check that the three strands have either all the same or all different colors
  -- Since we use 1,2 and 3 for the colors this is the same as checking if their sum is divisible by 3
  |u<-s!!a=mod(sum$i:u)3<1&&r b s i
f x=r x(x>>[[]])1

```
> 7 votes

---
Tags: code-golf, math, topology, knot-theory
---


title: Longest Prime Sums

text:
# Question
Title: Longest Prime Sums
Sandbox

There are special sets *S* of primes such that \\$\sum\limits\_{p\in S}\frac1{p-1}=1\\$. In this challenge, your goal is to find the largest possible set of primes that satisfies this condition.

**Input**: None

**Output**: A set of primes which satisfies the conditions above.

This challenge is a , where your score is the size of the set you output.

# Examples of Valid Outputs and their scores

```
{2} - 1
{3,5,7,13} - 4
{3,5,7,19,37} - 5
{3,5,7,29,31,71} - 6

```

**Important**: This challenge doesn't require any code, simply the set. However, it would be helpful to see how you generated your set, which probably involves some coding.

**Edit**: Found the math.stackexchange post that inspired this thanks to @Arnauld

# Answer
> 30 votes
# Score ~~100~~ 8605

I used an algorithm that starts with one solution and repeatedly tries to split a prime \\$p\\$ in the solution into two other primes \\$q\_ 1\\$ and \\$q\_ 2\\$ that satisfy \\$\frac1{p-1} = \frac1{q\_1-1}+\frac1{q\_2-1}\\$.

It is known (and can be quickly checked) that the positive integer solutions to \\$\frac1n = \frac1x + \frac1y\\$ are in one-to-one correspondence with factorizations \\$n^2 = f\_ 1 f\_ 2\\$, the correspondence being given by \\$x = n + f\_ 1\\$, \\$y = n + f\_ 2\\$. We can search through the factorizations of \\$(p-1)^2\\$ to see if any of them yielded a solution where both new denominators \\$x,y\\$ were one less then primes; if so, then \\$p\\$ can be replaced by \\$q\_1=x+1\\$, \\$q\_2=y+1\\$. (If there were multiple such factorizations, I used the one where the minimum of \\$q\_1\\$ and \\$q\_2\\$ was smallest.)

I started with this seed solution of length 44:

```
seed = {3, 7, 11, 23, 31, 43, 47, 67, 71, 79, 103, 131, 139, 191, 211, 239, 331, 419, 443, 463, 547, 571, 599, 647, 691, 859, 911, 967, 1103, 1327, 1483, 1871, 2003, 2311, 2347, 2731, 3191, 3307, 3911, 4003, 4931, 6007, 6091, 8779}

```

This seed was found using an Egyptian fraction solver that a former research student of mine, Yue Shi, coded in ChezScheme. (The primes \\$p\\$ involved all have the property that \\$p-1\\$ is the product of distinct primes less than 30, which increased the likelihood of Shi's program finding a solution.)

The following Mathematica code continually updates a current solution by looking at its primes one by one, trying to split them in the manner described above. (The number 1000 in the third line is an arbitrary stopping point; in principle one could let the algorithm run forever.)

```
solution = seed;
j = 1; (* j is the index of the element of the solution that we'll try to split *)

While[j <= 1000 && j <= Length[solution],
  currentP = solution[[j]];
  allDivisors = Divisors[(currentP - 1)^2];
  allFactorizations = {#, (currentP - 1)^2/#} & /@
    Take[allDivisors, Floor[Length[allDivisors]/2]];
  allSplits = currentP + allFactorizations;
  goodFactorizations = Select[allSplits,
    And @@ PrimeQ[#] && Intersection[#, solution] == {} &];
  If[goodFactorizations == {},
    j++,
    solution = Union[Complement[solution, {currentP}], First@goodFactorizations]
  ]
]

```

The code above yields a solution of length 4126, whose largest element is about \\$8.7\times10^{20}\\$; by the end, it was factoring integers \\$(p-1)^2\\$ of size about \\$8.8\times10^{21}\\$.

In practice, I ran the code several times, using the previous output as the next seed in each case and increasing the cutoff for j each time; this allowed for the recovery of some small prime splits that had become non-redundant thanks to previous splitting, which somewhat mitigated the size of the integers the algorithm factored.

The final solution, which took about an hour to obtain, is too long to fit in this answer but has been posted online. It has length 8605 and largest element about \\$4.62\times10^{19}\\$.

Various runs of this code consistently found that the length of the solution was about 3–4 times as long as the set of primes that had been examined for splitting. In other words, the solution was growing much faster than the code scanned through the initial elements. It seems likely that this behavior would continue for a long time, yielding some gargantuan solutions.

# Answer
> 14 votes
# Score ~~263~~ ~~385~~ ~~425~~ 426 with only primes \< 1.000.000 (*was*: non-competitive, now it is; score can be increased by running the program longer)

I followed the same path as Wheat Wizard: iteratively search for primes in the solution that can be replaced with a longer list of primes with the same result. I wrote that Python program that does exactly this. It starts with solution `S = {2}` and than iterates of all elements of that solution and tries to find a decomposition of that prime for which 1/(p-1) = sum(1/(q-1) for all q in the decomposition.

After I realized that S should be a set (and not a list), I altered the program to take this into account. I also added a ton of performance optimizations. The solution of 263 came up within 200 seconds or so (running under pypy3), but if you let it running, it steadily keeps coming with additional (longer) solutions.

Current best solution (425 elements, with all primes \< 1M, calculated in ~ 15 min.):

```
S = [3, 5, 13, 19, 29, 37, 103, 151, 241, 281, 409, 541, 577, 593, 661, 701, 751, 1297, 1327, 2017, 2161, 2251, 2293, 2341, 2393, 2521, 2593, 2689, 2731, 3061, 3079, 3329, 3361, 3457, 6301, 6553, 7057, 7177, 7481, 7561, 8737, 9001, 9241, 9341, 10501, 11617, 12097, 12547, 14281, 14449, 14561, 15121, 17761, 17851, 18217, 18481, 20593, 21313, 22441, 23189, 23761, 24571, 26041, 26881, 28351, 28513, 29641, 30241, 36529, 37441, 46993, 49921, 51169, 57331, 58109, 58313, 58369, 58831, 59659, 60737, 60757, 61001, 61381, 61441, 61561, 61609, 63067, 63601, 64513, 64901, 65053, 65089, 65701, 65881, 66301, 66931, 67049, 69389, 69941, 70181, 72161, 72481, 72577, 72661, 73061, 73699, 74521, 77521, 78241, 79693, 81181, 86951, 88741, 90631, 98011, 100297, 102181, 107641, 108991, 109201, 109537, 114913, 117841, 118429, 121993, 122761, 123001, 124561, 127601, 128629, 130073, 130969, 131561, 133387, 133813, 138181, 138403, 139501, 146077, 149521, 159457, 160081, 162289, 163543, 166601, 174241, 175891, 176401, 177913, 180181, 182711, 189421, 199921, 201781, 206641, 218527, 223441, 227089, 229739, 234961, 238081, 238141, 238897, 239851, 246241, 250057, 261577, 266401, 267961, 280321, 280837, 280897, 281233, 283501, 283861, 284161, 287233, 288049, 291721, 297601, 299053, 302221, 306853, 309629, 313153, 316681, 322057, 325921, 332489, 342211, 342241, 349981, 352273, 354961, 355321, 360977, 365473, 379177, 390097, 390961, 394717, 395627, 401057, 404251, 404489, 412127, 412651, 416881, 417649, 418027, 424117, 427681, 428221, 428401, 429409, 430921, 434521, 435481, 441937, 443873, 444641, 451441, 453601, 454609, 455149, 459649, 466201, 468001, 473617, 474241, 480737, 481693, 483883, 496471, 498301, 498961, 499141, 499591, 499969, 501601, 501841, 502633, 513067, 514513, 517609, 523261, 524521, 525313, 529381, 538721, 540541, 545161, 550117, 552553, 560561, 562633, 563501, 563851, 568177, 570781, 575723, 587497, 590669, 591193, 599281, 601801, 601903, 604001, 605551, 607993, 609589, 611389, 617401, 621007, 627301, 628561, 628993, 629281, 635449, 637201, 639211, 642529, 645751, 651361, 651857, 653761, 654853, 655453, 657091, 662941, 664633, 667801, 669121, 669901, 670177, 673201, 673921, 675109, 688561, 689921, 691363, 692641, 694033, 695641, 697681, 698293, 700591, 703081, 703561, 705169, 705181, 707071, 709921, 713627, 732829, 735373, 737413, 739861, 742369, 745543, 750121, 750721, 754771, 756961, 757063, 758753, 759001, 760321, 761671, 762721, 766361, 773501, 774181, 776557, 779101, 782461, 784081, 784981, 786241, 788317, 794641, 795601, 797273, 800089, 801469, 808081, 808177, 810151, 813121, 815671, 819017, 823481, 823621, 825553, 831811, 833281, 833449, 836161, 839161, 840911, 846217, 859657, 859861, 860609, 863017, 865801, 869251, 870241, 875521, 876929, 878011, 880993, 884269, 891893, 895681, 898921, 899263, 902401, 904861, 905761, 907369, 908129, 914861, 917281, 917317, 921601, 922321, 923833, 926377, 939061, 941641, 942401, 943009, 943273, 944161, 944821, 944833, 949621, 949961, 950041, 950401, 953437, 953443, 954001, 957349, 957529, 960121, 960961, 963901, 964783, 967261, 967627, 967751, 968137, 971281, 973561, 973591, 984127, 984341, 984913, 986437, 991381, 992941, 994561, 995347, 996001]

```

Proof that is satisfies the challenge:

Some of the decompositions used:

```
1/(  2-1) = sum(1/(p-1)) for p in: {(5, 7, 13, 3)}
1/(  3-1) = sum(1/(p-1)) for p in: {(7, 13, 5)}
1/(  5-1) = sum(1/(p-1)) for p in: {(13, 7)}
1/(  7-1) = sum(1/(p-1)) for p in: {(13, 19, 37)}
1/( 13-1) = sum(1/(p-1)) for p in: {(19, 37)}
1/( 19-1) = sum(1/(p-1)) for p in: {(29, 71, 181)}
1/( 29-1) = sum(1/(p-1)) for p in: {(37, 127)}
1/( 37-1) = sum(1/(p-1)) for p in: {(43, 281, 2521)}
1/( 43-1) = sum(1/(p-1)) for p in: {(53, 223, 13469)}
...
1/(8779-1) = sum(1/(p-1)) for p in: {(8969, 739861, 941641)}
1/(8807-1) = sum(1/(p-1)) for p in: {(9001, 773501, 865801)}
1/(8821-1) = sum(1/(p-1)) for p in: {(8941, 657091)}
1/(8941-1) = sum(1/(p-1)) for p in: {(9041, 808177)}
1/(8969-1) = sum(1/(p-1)) for p in: {(9463, 227089, 705169)}
1/(9001-1) = sum(1/(p-1)) for p in: {(9109, 759001)}
1/(9041-1) = sum(1/(p-1)) for p in: {(9241, 417649)}
1/(9109-1) = sum(1/(p-1)) for p in: {(10891, 55661)}
1/(9181-1) = sum(1/(p-1)) for p in: {(9343, 529381)}
1/(9241-1) = sum(1/(p-1)) for p in: {(9341, 863017)}
1/(9341-1) = sum(1/(p-1)) for p in: {(15121, 25219, 784561)}
1/(9343-1) = sum(1/(p-1)) for p in: {(9689, 261577)}
1/(9463-1) = sum(1/(p-1)) for p in: {(10957, 69389)}
1/(9689-1) = sum(1/(p-1)) for p in: {(12457, 43597)}
1/(10333-1) = sum(1/(p-1)) for p in: {(10501, 645751)}
...
1/(131561-1) = sum(1/(p-1)) for p in: {(237361, 295153)}
1/(166601-1) = sum(1/(p-1)) for p in: {(243433, 527851)}
1/(266401-1) = sum(1/(p-1)) for p in: {(386401, 857809)}
1/(355321-1) = sum(1/(p-1)) for p in: {(639577, 799471)}

```

Python3 code:

```
import itertools
import sympy
import cProfile
import functools
import bisect
import operator

def sundaram3(max_n):
    # Returns a list of all primes under max_n
    numbers = list(range(3, max_n + 1, 2))
    half = (max_n) // 2
    initial = 4
    for step in range(3, max_n + 1, 2):
        for i in range(initial, half, step):
            numbers[i - 1] = 0
        initial += 2 * (step + 1)
        if initial > half:
            return [2] + list([_f for _f in numbers if _f])

# Precalculate all primes up to a million to speed things up
PRIMES_TO_1M = list(sundaram3(1000000))

def nextprime(number):
    # partly precalculated fast version for calculating the
    # first (e.g. smallest) prime that is largest than numer
    global PRIMES_TO_1M

    if number <= PRIMES_TO_1M[-2]:
        return PRIMES_TO_1M[bisect.bisect(PRIMES_TO_1M, number)]
    return sympy.nextprime(number)

def isprime(number):
    # partly precalculated fast version to determine of number is prime
    global PRIMES_TO_1M

    if number < 1000000:
        return number in PRIMES_TO_1M
    return sympy.isprime(number)

def upper_limit(prime, length=2):
    # Returns the largest prime q in the decomposition of prime with the given
    # length such that 1 / (prime - 1) = sum( 1 / (q - 1)) for q in
    # set V, with V has the given length.
    # ASSUMPTION: all q are unique; this assumption is not validated,
    # but for this codegolf, the solution must be a set, so this is safe.
    if length == 1:
        return prime
    nextp = nextprime(prime)
    largestprime = (prime * nextp - 2 * prime + 1 ) // (nextp - prime)
    if not isprime(largestprime):
        largestprime = nextprime(largestprime)
    return upper_limit(largestprime, length - 1)

def find_decomposition(prime, length=2):
    # Returns a list of primes V = {q1, q2, q3, ...} for which holds that:
    # 1 / (prime - 1) = sum(1 / (q - 1)) for q in V.
    # Returns None if this decomposition is not found.
    # Note that there may be more than one V of a given prime, but this
    # function returns the first found V (implementation note: the sortest one)
    print(f"Searching decomposition for prime {prime} with length {length} in range ({prime}, {upper_limit(prime, length)}]")
    prime_range = PRIMES_TO_1M[bisect.bisect(PRIMES_TO_1M, prime) + 1:
                               bisect.bisect(PRIMES_TO_1M, upper_limit(prime, length) + 1)]
    # we only search for combinations of length -1; the last factor is calculated
    for combi in itertools.combinations(prime_range, length - 1):
        # we find the common factor of prime and all primes in combi
        # and use that to calculate the remaining prime. This is faster
        # than trying all prime combinations.
        factoritems = [-prime + 1] + [c - 1 for c in combi]
        factor = -functools.reduce(operator.mul, factoritems)
        remainder = - factor / sum(factor // p for p in factoritems) + 1
        if remainder == int(remainder) and isprime(remainder) and remainder not in combi:
            combi = combi + (int(remainder),)
            print(f"Found decomposition: {combi}")
            return combi
    return None

def find_solutions():
    # Finds incrementally long solutions for the set of primes S, for which:
    # sum(1/(p-1)) == 1 for p in S.
    # We do this by incrementally searching for primes in S that can be
    # replaced by longer subsets that have the same value of sum(1/p-1).
    # These replacements are stored in a dictionary "decompositions".
    # Starting with the base solution S = [2] and all decompositions,
    # you can construct S.
    decompositions = {}  # prime: ([decomposition], max tried length)
    S = [2]
    old_solution_len = 0

    # Keep looping until there are no decompositions that make S longer
    while len(S) > old_solution_len:
        # Loop over all primes in S to search for decompositions
        for p in sorted(set(S)):
            # If prime p is not in the decompositions dict, add it
            if p not in decompositions:
                decompositions[p] = (find_decomposition(p, 2), 2)
            # If prime p is in the decompositions dict, but without solution,
            # try to find a solution 1 number longer than the previous try
            elif not decompositions[p][0]:
                length = decompositions[p][1] + 1
                decompositions[p] = (find_decomposition(p, length), length)
            # If prime p is in decompositions and it has a combi
            # and the combi is not already in S, replace p with the combi
            elif all(p not in S for p in decompositions[p][0]):
                old_solution_len = len(S)
                print(f"Removing occurence of {p} with {decompositions[p][0]}")
                S.remove(p)
                S.extend(decompositions[p][0])
                S = sorted(S)
                break  # break out of the for loop
        print(f"Found S with length {len(S)}: S = {S}")
        print(f"Decompositions: ")
        for prime in sorted(decompositions.keys()):
            print(f"    1/({prime:3}-1) = sum(1/(p-1)) for p in: \u007b{decompositions[prime][0]}\u007d")

def main():
    cProfile.run("find_solutions()")

if __name__ == "__main__":
    main()

```

# Answer
> 12 votes
# Score ~~32~~ ~~34~~ 36

```
{5, 7, 11, 13, 17, 23, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 101, 113, 131, 137, 151, 211, 229, 241, 281, 313, 379, 401, 433, 457, 491, 521, 571, 601, 25117, 293362609}

```

This is an improvement of Arnauld's answer. I just noticed that

\\$ \dfrac{1}{19-1}=\dfrac{1}{73-1}+\dfrac{1}{61-1}+\dfrac{1}{41-1} \\$

But 41 and 61 were already used in Arnauld's answer so I had to then figure out that

\\$ \dfrac{1}{61-1} = \dfrac{1}{151-1} + \dfrac{1}{101-1} \\$ and \\$ \dfrac{1}{41-1} = \dfrac{1}{281-1}+\dfrac{1}{211-1}+\dfrac{1}{151-1}+\dfrac{1}{101-1} \\$

But now I am using 151 and 101 twice. So I spent some time and discovered that

\\$ \dfrac{1}{151-1} = \dfrac{1}{401-1} + \dfrac{1}{241-1} \\$ and \\$ \dfrac{1}{101-1} = \dfrac{1}{601-1} + \dfrac{1}{571-1} + \dfrac{1}{457-1} + \dfrac{1}{229-1} \\$

So now I can just replace the `19` with `71, 151, 101, 151, 211, 229, 241, 281, 401, 457, 471, 601` and the sequence will maintain it's properties.

I also discovered that I can replace `19` with the sequence `71, 151, 101, 151, 211, 241, 241, 281, 401, 433, 541, 601`, but that has `241` twice.

After that improvement I also noticed that 79 could be replaced with `521, 313, 131`, to increase the size by 2 more. And 73 can be replaced with `113, 379, 433` for another 2.

# Answer
> 8 votes
# Score 22

Just to get the ball rolling.

```
{5,7,11,13,17,19,23,31,37,41,43,47,53,59,61,67,71,79,137,491,25117,293362609}

```

Compute the fraction

I suspect that the sequence can be made arbitrary large, but my code is currently too messy and inefficient for anything significantly better than that.

# Answer
> 4 votes
This non-answer expands on the modifications to @GregMartin's answer referenced in this comment there.

The `allDivisors` to `goodFactorizations` block can be sped up noticeably by not asking `Divisors` to factor the square of a number (and also a few other changes). The @GregMartin's original code:

```
divMethod[p_] := Module[{},
   allDivisors = Divisors[(p - 1)^2];
   allFactorizations = {#, (p - 1)^2/#} & /@
      Take[allDivisors, Floor[Length[allDivisors]/2]];
   allSplits = p + allFactorizations;
   goodFactorizations = Select[allSplits,
      And @@ PrimeQ[#] &]
]

```

The intersection check at the end is removed, since it is common to both the above and my proposed replacement:

```
g[p_] := Module[
   {pm1s, factorization, divisors},
   pm1s = (p - 1)^2;
   (* Since the original seed contains only odd
      primes, we know one factor of p-1. *)
   factorization = FactorInteger[(p - 1)/2];
   (* For divisors d1, d2, such that d1 d2 = pm1s,
      we require d1+p and d2+p are prime.  p>2, so p
      is odd and both d1+p and d2+p are odd, so d1
      and d2 are necessarily both even.  This means
      we only consider splitting the powers of 2 so
      that at least one falls in each divisor; we
      want to know the power of 2 in pm1s, minus 1.
      *)
   If[factorization[[1, 1]] != 2,
      pow2m1 = 1,
      pow2m1 = 2 factorization[[1, 2]] + 1
   ];
   divisors = Outer[Times,
      2^Range[1, pow2m1],
      Sequence @@ (
         Select[
            #[[1]]^Range[0, 2 #[[2]]],
            (# < p - 1 &)] & /@
         Rest[factorization])];
   (* The Join@@ is a hack to deal with Reap's
      denormalized output on no-Sow runs.  See
      https://mathematica.stackexchange.com/questions/67625/what-is-shorthand-way-of-reap-list-that-may-be-empty-because-of-zero-sow *)
   Join @@ Reap[
      Map[
         (If[#1 < p - 1 && PrimeQ[#2],
            (If[PrimeQ[#2],
               Sow[{#1, #2}]
               ] &)[#2, pm1s/#1 + p]
            ] &)[#, # + p] &,
         divisors,
         {-1}];
      ][[2]]
]

```

Note: the replacement makes no attempt to sort the collection of pairs. The following tests do not demonstrate the potential difference in order of results from `divMethod` and `g`.

```
divMethod[3]
g[3]
(* {} *)
(* {} *)

divMethod[29]
g[29]
(* {{31, 421}, {37, 127}} *)
(* {{31, 421}, {37, 127}} *)

p = NextPrime[10^3]
RepeatedTiming[divMethod[p]]
RepeatedTiming[g[p]]
(* {0.00041, {{1201, 6301}}} *)
(* {0.000487, {{1201, 6301}}} *)

p = NextPrime[10^6]
RepeatedTiming[divMethod[p]]
RepeatedTiming[g[p]]
(* {0.000271, {}} *)
(* {0.0000619, {}} *)

p = NextPrime[10^9]
RepeatedTiming[divMethod[p]]
RepeatedTiming[g[p]]
(* {0.000271, {}} *)
(* {0.000103, {}} *)

```

Let's collect timing data for sets of 1000 consecutive primes starting at powers of 10 and see what trends we see.

```
divTiming = Table[{10^k, RepeatedTiming[
   p = NextPrime[10^k];
   For[count = 1, count <= 1000, count++,
      divMethod[p];
      p = NextPrime[p];
   ]
 ][[1]]}, {k, 3, 22}];

fiTiming = Table[{10^k, RepeatedTiming[
   p = NextPrime[10^k];
   For[count = 1, count <= 1000, count++,
      g[p];
      p = NextPrime[p];
   ]
 ][[1]]}, {k, 3, 22}];

ListLogLinearPlot[{divTiming, fiTiming},
   PlotLegends -> {"Divisors", "FactorInteger"}]

```

```
ListLogLinearPlot[
   Transpose[{
      divTiming[[All, 1]],
      (divTiming/fiTiming)[[All, 2]]}],
   PlotLegends -> {"Divisors/FactorInteger"}]

```

So around 10^7 or 10^8, the `Divisors` method is noticeably slower than the `FactorInteger` method. The ratio of times rises to 3-ish for primes around 10^15. There is a dip, for slightly larger primes, but the trend suggests the speed-up will improve as we go to larger primes than tested.

---
Tags: math, code-challenge, number-theory, primes
---


title: On the Subject of Memory

text:
# Question
Title: On the Subject of Memory
This challenge is from a game called Keep Talking And Nobody Explodes.

*Memory is a fragile thing but so is everything else when a bomb goes off, so pay attention!* – from the manual

# The Objective

A number from 1–4 is given as the "display", along with scrambled numbers 1–4 as the "buttons."

The output must be the label of the correct "button." Repeat this process 5 times.

# The Format

The input format must be:

```
<display #> <buttons #>

```

Repeated 5 times. As long as the numbers are distinguishable and the `<display #>` is dedicated separately, the input format and type don't matter. For any input that doesn't fit this format, the entire challenge falls in *don't care* situation.

The output format and type don't matter as long as the numbers are distinguishable.

# Which button to press

Pressing a button means to output the label of the button.

The buttons are indexed from left to right, and are 1-indexed.

**For the 1st line:**

If the display is 1, press the button in the second position.
If the display is 2, press the button in the second position.
If the display is 3, press the button in the third position.
If the display is 4, press the button in the fourth position.

**For the 2nd line:**

If the display is 1, press the button labeled “4”.
If the display is 2, press the button in the same position as you pressed in line #1.
If the display is 3, press the button in the first position.
If the display is 4, press the button in the same position as you pressed in line #1.

**For the 3rd line:**

If the display is 1, press the button with the same label you pressed in line #2.
If the display is 2, press the button with the same label you pressed in line #1.
If the display is 3, press the button in the third position.
If the display is 4, press the button labeled “4”.

**For the 4th line:**

If the display is 1, press the button in the same position as you pressed in line #1.
If the display is 2, press the button in the first position.
If the display is 3, press the button in the same position as you pressed in line #2.
If the display is 4, press the button in the same position as you pressed in line #2.

**For the last line:**

If the display is 1, press the button with the same label you pressed in line #1.
If the display is 2, press the button with the same label you pressed in line #2.
If the display is 3, press the button with the same label you pressed in line #4.
If the display is 4, press the button with the same label you pressed in line #3.

# An Example

Given the following input:

```
2 1432
4 3214
2 4213
1 4231
1 3214

```

For the 1st line, press the button in the second position, so output `4`.
For the 2nd line, press the button in the same position as you pressed in line #1, so output `2`.
For the 3rd line, press the button with the same label you pressed in line #1, so output `4`.
For the 4th line, press the button in the same position as you pressed in line #1, so output `2`.
For the last line, press the button with the same label you pressed in line #1, so output `4`.

So the entire output is `42424`, in any format and type.

# Answer
> 3 votes
# Charcoal, 74 bytes

```
Ｓθ≔∨⊖Ｓ¹η⊞υ§θηＳθ≔§⟦⌕θ4η⁰η⟧⊖Ｓζ⊞υ§θζ⊞υ§⁺⮌υ⟦§Ｓ²4⟧⊖Ｓ⊞υ§Ｓ§⟦η⁰ζζ⟧⊖ＳＳθ⊞υ§υ⌕1243Ｓ↑υ

```

Try it online! Link is to verbose version of code. Takes input as `buttons#1 display#1 buttons#2 ... display#5`. Explanation:

```
Ｓθ

```

Input the first buttons.

```
≔∨⊖Ｓ¹η

```

Decrement the first display to make it 0-indexed, but if that results in zero, increment it again. Save the result for steps 2 and 4.

```
⊞υ§θη

```

Save the appropriately indexed button in the predefined empty list.

```
Ｓθ

```

Input the second buttons.

```
≔§⟦⌕θ4η⁰η⟧⊖Ｓζ

```

Make a list of four elements: the index of "4" in the buttons; the index of the first button; `0` (representing the button in first position); the index of the first button. Get the element corresponding to the (decremented) second display. Save the result for step 4.

```
⊞υ§θζ

```

Add the appropriately indexed button to the list.

```
⊞υ§⁺⮌υ⟦§Ｓ²4⟧⊖Ｓ

```

Input the third buttons and make a list of four elements: the two buttons so far in reverse order, the button at index 2 (i.e. third position), and `4`. Index this using the (decremented) third display. Add the result to the list.

```
⊞υ§Ｓ§⟦η⁰ζζ⟧⊖Ｓ

```

Input the fourth buttons, and index them from a list of four elements: the position used for the first button, `0` (representing the first button), and the position used for the second button (twice), first indexed using the (decremented) fourth display. Add the result to the list.

```
Ｓθ

```

Input the fifth buttons.

```
⊞υ§υ⌕1243Ｓ

```

Input the fifth display, find its index into the string `1243`, and index that into the list so far, adding the result to the list.

```
↑υ

```

Output the result.

# Answer
> 8 votes
# JavaScript (ES6),  ~~109 106 105~~  104 bytes

Takes input as a list of pairs `[display, "buttons"]`. Returns a list of pressed buttons.

```
a=>a.map(([d,b],i)=>a[i]=b[a[~i]=(n='_5567.848106.80990132'[i*4+d])>3?n>7?a[7-n]:n-4:b.search(a[n]||4)])

```

Try it online!

### How?

The action for each line and each displayed value is encoded as a single character as follows (with 0-indexed lines and positions):

* \\$n=0\\$ to \\$3\\$: press the button with the same label that we pressed in line \\$n\\$
* \\$n=4\\$ to \\$7\\$: press the button in position \\$n-4\\$
* \\$n=8\\$ or \\$9\\$: press the button in the same position as we pressed in line \\$n-8\\$
* `"."`: press the button labeled "\\$4\\$"

Translating the rules described in the challenge into these codes leads to the groups `5567`, `.848`, `106.`, `8099` and `0132`, which are concatenated into a single lookup string. The purpose of the leading `"_"` is just to deal with the 1-indexed input.

The input array \\$a\[\\:\]\\$ is re-used to store both the labels that are pressed and their positions. For each line \\$i\\$, we store the label in \\$a\[i\]\\$ and its position in \\$a\[-i-1\]\\$.

### Commented

```
a =>                              // a[] = input
  a.map(([d, b],                  // for each pair of displayed value d and buttons b
                 i) =>            // at position i in a[]:
    a[i] = b[                     //   save the label in a[i]
      a[~i] =                     //     save its position in a[-i-1]
        ( n =                     //       n = action code taken from ...
          '_5567.848106.80990132' //           ... our lookup string ...
          [i * 4 + d]             //           ... at position i * 4 + d
        ) > 3 ?                   //       if n is greater than 3:
          n > 7 ?                 //         if n is greater than 7:
            a[7 - n]              //           re-use the position used at line n - 8,
                                  //           stored in a[-(n-8)-1], i.e. a[7-n]
          :                       //         else:
            n - 4                 //           use the position n - 4
        :                         //       else:
          b.search(a[n]           //         look for the label used at line n
                        || 4)     //         or look for '4' if a[n] is undefined,
                                  //         which happens only when n is '.'
    ]                             //   end of button lookup
  )                               // end of map()

```

# Answer
> 5 votes
# Python 2, 415 375 351 317 299 273 265 bytes

```
a=[0]*5;x=input()
for i,z in enumerate(x):j,q=z;exec'a[i]'+['=[q[j-1],j]',';k=a[0][1];a[i]=[4,q.index(4)+1]if j<2else[q[k-1],k]if j-3else[q[0],1]','=[4if j>3else a[j<2][0]if j<3else q[0]]','=[q[a[j>1][1]-1]]if j-2else[q[0]]','=a[6>>4-j&3];print[l[0]for l in a]'][i]

```

Try it online!

-40 bytes by making everything ternary
-24, -18, -10 by removing unnecessary code
-16 by using (label,position) rather than (position,label)
-4, -4 thanks to @Arnauld
-26, -8 thanks to @Chas Brown

Not quite as competitive as @Arnauld's solution... probably a bit naive as its basically just logic.

Very happy with how this progressed, thanks everyone for the suggestions!

---
Tags: code-golf, game
---


title: Challenge: Functioning Blackjack Game

text:
# Question
Title: Challenge: Functioning Blackjack Game
This is kept fairly original:

Write a program that creates a standard blackjack game:

* input "h" means hit or draw another card
* input "s" means stand, or take what you have already

Rules:
* cards values are as follows:
* 2-9 = face value of card
* 10, J, Q, K = 10
* aces = 11 unless player busts, then it's only a 1
* if 2 or more aces are drawn the first is 11, and each one after is a 1
* the bank needs 18-21, and has to draw another card until they are in this range
* this game runs forever

Procedure:

+ The player gets 2 cards at the beginning, shown by "Player:" in the console (Example: Player gets 2 and 5 at the beginning. Console output: "Player: 2, 5").
    + The cards can be shown in the console by their values (For example: 2, 10, 1 | No need for: 2, K, A), but you can also use the card-names instead. Your choice
    + The input by the player is "h" for "hit" and "s" for "stand". Also allowed is 1 and 0
    + The bank gets one card at the beginning, shown by "Bank:"
    + At the end you get the output "Win", "Lose", "Draw", or "Blackjack", depending on the game

This game is a challenge.

# Answer
> 3 votes
# Python 3, ~~574~~ \\$\cdots\\$ ~~338~~ 337 bytes

```
from random import*
e,L,B,P=exit,"Lose","Bank:","Player:"
d=[*range(2,12)]*4+[10]*12
c=d.pop
def h(l,m):
 l+=[c()]
 if sum(l)>21and 11in l:l[l.index(11)]=1
 print(m,*l);return sum(l)
shuffle(d)
b=[]
t=h(b,B)
p=[c()]
u=h(p,P)
u>20<e("Blackjack")
while'h'==input():u=h(p,P)
u>21<e(L)
while t<18:t=h(b,B)
22>t>u<e(L)
u==t<e("Draw")
e("Win")

```

Try it online!

Saved 34 bytes thanks to @ReinstateMonica!!!

---
Tags: code-golf, card-games
---


title: Hexagonify™ a String Block

text:
# Question
Title: Hexagonify™ a String Block
Sandbox

### What is Hexagonification™?

Hexagonification™ is a transformation that creates a hexagon with 3 copies of a rectangle block, each skewed to the right by 30 degrees and then rotated by 0, 120 and 240 degrees respectively, as shown in the following image. A triangle hole may appear in the middle, but that isn't a great deal.

### Challenge

Write a program or function that receives a block of string as an input and outputs the hexagonified™ input. You may assume that the input consists of only ASCII characters and new lines, and each line of the input has been padded so that all lines are of equal length. Empty spaces should be filled with space characters.

The input and output formats are flexible. You may receive a single string, a list of lines or a 2D array as input, and output a single string or a list of lines. You may have leading/trailing spaces on each line and leading/trailing newlines, provided that the hexagon is properly formed. See Sample IO for how the blocks should be positioned.

### Sample IO

Input:

```
3x3
squ
are

```

Output:

```
   3 x 3
  e s q u
 u r a r e
3 q a a s 3
 x s r q x
  3 e u 3

```

Input:

```
longer.....
rectangular
block......

```

Output:

```
   l o n g e r . . . . .
  . r e c t a n g u l a r
 r . b l o c k . . . . . .
. a .                 b r l
 . l .               l e o
  . u .             o c n
   . g .           c t g
    . n k         k a e
     r a c       . n r
      e t o     . g .
       g c l   . u .
        n e b . l .
         o r . a .
          l . r .

```

Input:

```
vb
el
ro
tc
ik
c2
ax
l8

```

Output:

```
        v b
       8 e l
      x l r o
     2 a   t c
    k c     i k
   c i       c 2
  o t         a x
 l r           l 8
b e l a c i t r e v
 v 8 x 2 k c o l b

```

Input:

```
1.line

```

Output:

```
 1 . l i n e
e           1
 n         .
  i       l
   l     i
    .   n
     1 e

```

Input:

```
1
.
l
i
n
e

```

Output:

```
      1
     e .
    n   l
   i     i
  l       n
 .         e
1 e n i l . 1

```

### Scoring

Your score will be the area of the hexagonified™ source code (including the triangle hole). Assuming your code can just fit inside a rectangle of width \\$w\\$ and height \\$h\\$, the score will be:

$$3wh+\frac{(w-h)(w-h+1)}{2}$$

### Winning Criteria

The submission with the lowest score in each language wins. No standard loopholes.

# Answer
> 5 votes
# Charcoal, score ~~235~~ 168

```
→ＷＳ⊞υιＦυＦ
«Ｐ↙ιＭ²←»Ｆ
Ｍ⊖⌈ＥυＬκ↙Ｆ
Ｆυ«Ｐ↖κ↗»Ｆ
Ｍ⊖⌈ＥυＬκ↖Ｆ
Ｆυ«Ｐ⪫κ ↘»

```

Try it online! Takes input as a newline-terminated list. Charcoal's problem here is that a newline is a command, so I can't just throw newlines in arbitrarily. Instead, I'm passing them as arguments to the `For` command, which loops over each character in the string, which here is just the one character, therefore not modifying the behaviour of the program (except to change the implicit loop variables). As such, these dummy `For` instructions are not included in the explanation. Explanation:

Another no-op, just to make the code exactly rectangular.

```
ＷＳ⊞υι

```

Input the list.

```
Ｆυ«Ｐ↙ιＭ²←»

```

Print the lower right diagonal side.

```
Ｍ⊖⌈ＥυＬκ↙

```

Move to the bottom.

```
Ｆυ«Ｐ↖κ↗»

```

Print the lower left diagonal side.

```
Ｍ⊖⌈ＥυＬκ↖

```

Move to the top left.

```
Ｆυ«Ｐ⪫κ ↘»

```

Print the top side.

# Answer
> 4 votes
# Python 2, score 918

```
m=input()
d={};h=len(m)
w=len(m[0])
r=range
for i in r(h*w):
 j,i=divmod(i,h)
 d[(i,i+j*2)]=d[
(h+j,h+2*w-2*i-j
-2)]=d[(w-j+h+~i
,w+i-j+~h)]=m[i
][j]
y,x=zip(
*d.keys())
for i in r(min
(y),max(y)+1):
 print''.join(d
.get((i,j),' ')
for j in r(min
(x),max(x)+1))

```

Try it online!

# Answer
> 3 votes
# Jelly, width × height = ~~9 × 9~~ 9 × 6, score = ~~243~~ 168

```
ṚZÑṚŻL}¡
J’0ẋ;"K€
ṚÇḟ€⁶ZUÇŻ
Z,ṖẈ+L0ẋ
Ṫ;Ɱ";⁶o/
U¹ƭṛĿ¥Ɱ4Ç

```

Try it online!

A set of links that takes a list of Jelly strings as its input and returns a list of Jelly strings.

# An alternative 8 × 7 with score of 169:

```
ṚZÑṚŻL}¡
J’0ẋ;"K€
ṚÇḟ€⁶ZUÇ
Z,ṖẈ+L0ẋ
Ṫ;Ɱ";⁶o/
ṛĿ"JŻ€3¦
U3Ð¡ṚÇ5Ŀ

```

Try it online!

# Answer
> 3 votes
# Jelly, Score (8 by  ~~9~~  8) =  ~~216~~  192

```
¹¹ẈṀ_$⁶ẋ
ŒdṙLC$UŻ
ÇżUṚżZṚ$
ÇṚUF€ḟ€0
0ẋṂ;r/_Ṃ
Z,$ẈÇṖ⁶ẋ
4ĿŒHj¥"Ç
ỴÇµÑżK€Y

```

A full-program which prints the result.

**Try it online!** Or see the test-suite.

### How?

Starts at the Main (unnumbered) Link, which is the bottom line of code.

```
¹¹ẈṀ_$⁶ẋ - Link 1: the output lines without leading spaces, A
¹        - no-op -> A
 ¹       - no-op -> A
  Ẉ      - length of each (A)
     $   - last two links as a monad - f(Ẉ(A))
   Ṁ     -   maximum
    _    -   subtract (vectorises)
      ⁶  - literal space character
       ẋ - repeat (vectorises)

ŒdṙLC$UŻ - Link 2: lines
Œd       - anti-diagonals (e.g. ["abcd","1234"] -> ["d3","c2","b1","a4"])
     $   - last two links as a monad - f(lines)
   L     -   length
    C    -   complement (1 - that)
  ṙ      - rotate (anti-diagonals) left by (1 - length(lines))
              i.e. rotate right by (#lines - 1)
      U  - reverse each
       Ż - prepend a zero (allows us to start the join one further
                           down - removed in Link 4 with ḟ€0)

ÇżUṚżZṚ$ - Link 3: lines
Ç        - call the last Link (2) as a monad = Link_2(lines)
  U      - reverse each (lines)
 ż       - zip together
       $ - last two links as a monad - f(lines)
     Z   -   transpose (lines)
      Ṛ  -   reverse
    ż    - zip together

ÇṚUF€ḟ€0 - Link 4: lines
Ç        - call the last Link (3) as a monad = Link_3(lines)
 Ṛ       - reverse
  U      - reverse each
   F€    - flatten each
     ḟ€0 - remove zeros from each

0ẋṂ;r/_Ṃ - Link 5: [w,h]       e.g. [8,3]
0        - literal zero             0
  Ṃ      - minimum (of w and h)     3
 ẋ       - repeat                   [0,0,0]
     /   - reduce ([w,h]) by:
    r    -   inclusive range        [8,7,6,5,4,3]
   ;     - concatenate              [0,0,0,8,7,6,5,4,3]
       Ṃ - minimum (of w and h)     3
      _  - subtract                 [-3,-3,-3,5,4,3,2,1,0]

Z,$ẈÇṖ⁶ẋ - Link 6: lines
  $      - last two links as a monad:
Z        -   transpose
 ,       -   pair
   Ẉ     - length of each - i.e. [w=width(S), h=height(S)]
    Ç    - call the last Link (5) as a monad = f([w,h])
     Ṗ   - pop (remove rightmost)
      ⁶  - literal space character
       ẋ - repeat (vectorises) - Note: z ẋ -n = []

4ĿŒHj¥"Ç - Link 7: lines
4Ŀ       - call Link 4 as a monad = Link_4(lines)
       Ç - call the last Link (6) as a monad = Link_6(lines)
      "  - zip with - i.e. for i in [1..] f(left[i],right[i]):
     ¥   -   last two links as a dyad:
  ŒH     -     split (Link_4(lines)[i]) into two halves
    j    -     join with (Link_6(lines)[i])

ỴÇµÑżK€Y - Main Link: List of characters, S
Ỵ        - split (S) at newline characters
 Ç       - call the last Link (7) as a monad = Link_7(lines)
  µ      - start a new monadic chain - i.e. f(Link_7(lines))
   Ñ     - call the next Link (1) as a monad = Link_1(Link_7(lines))
     K€  - join each (line) with space characters
    ż    - zip these together
       Y - join with newline characters
         - implicit print

```

---
Tags: string, ascii-art, code-challenge
---