Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Copied from http://stackoverflow.com/questions/14684511/reducing-perl-code-in-characters/14694805#14694805

So I had this question in a programming contest about calculating Leibniz formula in the least amount of characters

With the input format to the code as: The first line contains an integer T (<=100). T testcases follow. Each testcase has a single line with a positive integer n (< 10^7). and the output with each result on a new line

Now I came up with these two alternates:



for(1..<>){$s=0;$s+=($_&1||-1)/(2*$_-1)for 1..<>;print"$s\n"}

latest at 58 chars(thanks to melpomene):

for(1..<>){$s=0;$s-=(-1)**$_/(2*$_-1)for 1..<>;print$s.$/}

With 62 and 61 characters respectively, where as the best answer had only 55 characters. Now that the contest is over and I cant see the other solution I cant stop obsessing about how to reduce the characters further.

I am hoping someone here can show me the light.

reference: https://www.hackerrank.com/codesprint4/challenges/leibniz

share|improve this question
possible duplicate of Calculate pi to 5 decimals –  Peter Taylor Feb 5 '13 at 7:49
Why post the same question on two sites? I feel like it's either help or a puzzle, but not both. And as a puzzle it needs a puzzle-type (code-golf, coding-challenge) and objective winning criteria. –  luser droog Feb 5 '13 at 8:06
I was recommended that this question belongs here more then stackoverflow so posted here. –  Techmonk Feb 5 '13 at 8:16

2 Answers 2

up vote 1 down vote accepted

Perl 55 bytes


Without using any Perl non-standard features (such as say). 3 bytes are wasted removing the first value from the input.

Sample usage:



$ perl leibniz.pl < in.dat

Alternative, also 55 bytes

map{$s-=(-1)**$_/($_*2-1)for 1..<>;$s=!print$s,$/}1..<>

The alternative may be run interactively, without requiring an input file. Which, as I understand, is what you meant by running indefinitely.

share|improve this answer
That goes in an infinite loop, but using this notation for for can save 2 more bytes map($s-=(-1)**$_/(2*$_-1),1..<>),$s=!print$s.$/for 1..<> –  Techmonk Feb 5 '13 at 8:58
It will only cause an 'infinite' loop if the input given contains an infinite amount of lines. The for<> construction will iterate over every line in input passed to STDIN exactly once, without needing to 'know' beforehand how many there are. –  primo Feb 5 '13 at 9:07

Perl 53 bytes

You can save two more strokes:

share|improve this answer
Very clever. One would expect \map... to return a single array reference, and not a list of scalar references. –  primo Jun 10 '13 at 9:28

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.