Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Copied from

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.


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
up vote 3 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 < 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.