This C program is just 143 characters long!
But it “decompresses” into the first 10,000 digits of Pi.
// Created by cheeseMan on 30/11/13.
long a[35014],b,c=35014,d,e,f=1e4,g,h;
int main(int argc, const char * argv[])
{
for(;(b=c-=14);
h=printf("%04ld",e+d/f))
for(e=d%=f;(g=--b*2);d/=g)
d=d*b+f*(h?a[b]:f/5), a[b]=d%--g;
}
I was doing some research on loss-less compression algorithms, still no luck yet, when I came across this pitiny.c
.
The weird thing is that it compiles successfully no errors or bugs, but like i said i cannot make heads or tales of the code, even its syntax. I just would like to know whats going on? what is it doing exactly?
Update
This program is a purposely obfuscated implementation of a spigot algorithm for the Digits of Pi from the book Pi - Unleashed and we can find the original version on page 37 of the book which is as follows:
the paper Unbounded Spigot Algorithms for the Digits of Pi does a good job in explaining the algorithm. Basically it is an implementation of this expansion:
Original
The reason it was designed this way other than to make the code impossible to comprehend and impress people escapes me but we can break down what is going on, first here:
the variables are static since they are global so all variables not explicitly initialized will be initialized to
0
. Next we have an outer for loop:14
fromc
and assigning the value back toc
and also assigning the same value tob
. This loop will execute2500
times since35014/14
is 2501 and on the2501
th iteration the result will0
and thus false and the loop will stop.h
is being assigned the result ofprintf
which is the number of characters printed. What is being printed out is the result ofe+d/f
and always at least 4 digits and zero padded due to04
in the format specifier.Now we have an inner for loop:
e
andd
tod modulus f
.b
and multiples that by2
and assigns the result tog
d
is being divided byg
and assigned the result.Finally the body of the inner for loop:
uses both the conditional operator in
1
and comma operator in2
. So we could at least split this into:(1)
can further be broken down into:The conditional operator only matters during the first iteration since
h
is intialized to0
but will never be0
again afterwards since it is always assigned a non-zero value in the outer for loop, so other then the first timeh
will be assigneda[b]
.(2)
will again due to precedence pre-decrementg
first and then evaluated
modulus the result and assign that toa[b]
.