Tech talent hiring knowledge & best practices straight to your inbox!

Leibniz CodeGolf

Leibniz was one of the simple challenges in the Hackathon. All you needed to do was use the Leibniz formula to calculate π/4 to the specified number of steps. This just involves alternating between adding and subtracting decreasing fractions. The goal was to accomplish this in as little code as possible.
As is common for Code Golf challenges, the top entries were all in Perl. Before looking at a Perl solution, we’ll examine a Python solution by Alexander Ramirez (adr2370). He started off with a straightforward solution:
He then did a series of steps until he got the code down to 78 characters:
This is still a pretty straightforward solution. It uses simple tricks to shorten the code, such as -1i to alternate between adding and subtracting each fraction.
One of the high-scoring Perl solutions was submitted by Matthew Jee (“mcjee”), and he agreed to share his solution and explanation. This was his code, which was only 62 characters:
It is also straightforward (at least for Perl!). This is what each part of the code accomplishes:

  • <>  skips the input specifying the number of cases.
  • for(<>){…} iterates through each subsequent input.
  • $s=0; initializes the sum to 0.
  • $s+=(-1)**$_/(2*$_+1) for(0..$_-1); iterates through each term in the series, adding each one to $s .
  • Lastly, print”$sn” prints the sum.

Would you like to receive similar articles straight to your inbox?