Labyrinth, 29 bytes
1
?
:
} +{%!@
(:"'(
} {
:**
Reads an integer from STDIN and outputs ((n-1)!)^2 mod n
. Wilson's theorem is pretty useful for this challenge.
The program starts at the top-left corner, beginning with 1
which multiplies the top of the stack by 10 and adds 1. This is Labyrinth's way of building large numbers, but since Labyrinth's stacks are filled with zeroes, the end effect is as though we just pushed a 1.
?
then reads n
from STDIN and :
duplicates it. }
shifts n
to the auxiliary stack, to be used at the end for the modulo. (
then decrements n
, and we are ready to begin calculating the squared factorial.
Our second :
(duplicate) is at a junction, and here Labyrinth's control flow features come into play. At a junction after an instruction is executed, if the top of the stack is positive we turn right, for negative we turn left and for zero we go straight ahead. If you try to turn but hit a wall, Labyrinth makes you turn in the other direction instead.
For n = 1
, since the top of the stack is n
decremented, or 0
, we go straight ahead. We then hit a no-op "'
followed by another decrement (
which puts us at -1
. This is negative, so we turn left, executing +
plus (-1 + 10 = 0-1
), {
to shift n
back from the auxiliary stack to the main and %
modulo (0-1 % 1 = 0
). Then we output with !
and terminate with @
.
For n > 1
, at the second :
we turn right. We then shift }
our copied loop counter to the auxiliary stack, duplicate :
and multiply twice **
, before shifting the counter back {
and decrementing (
. If we're still positive we try to turn right but can't, so Labyrinth makes us turn left instead, continuing the loop. Otherwise, the top of the stack is our loop counter which has been reduced to 0, which we +
add to our calculated ((n-1)!)^2
. Finally, we shift n
back with {
then modulo %
, output !
and terminate @
.
I said that '
is a no-op, but it can also be used for debugging. Run with the -d
flag to see the state of the stack every time the '
is passed over!