Let's Play Code Golf

Charles via Digitalmars-d digitalmars-d at puremagic.com
Mon Feb 23 12:21:19 PST 2015


For the uninitiated, Code Golf is producing the correct answer to 
a question with minimal syntax (whitespace included). I found a 
couple questions on HackerRank, which allows D compilation. So 
far there's only two entries for D (mine and another) for the 
first problem.

Here's the problem:

In Calculus, the Leibniz formula for π is given by:

1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = pi/4

You will be given an integer n. Your task is to print the 
summation of the Leibniz formula up to the nth term of the series 
correct to 15 decimal places.

Input Format

The first line contains the number of test cases (T) which is 
less than 100. Each additional line is a test case for a positive 
integer value (p) less than 10^7.

Sample Input

2
10
20

Output Format

Output T lines, with each line containing the summation up to nth 
term.

Sample Output

0.760459904732351
0.772905951666960

Scoring

This is a code golf question. The goal is to write a solution 
with as little code as possible. A correct submission with a 
source code of X characters will receive the following score:

maxScore * (300 - X)/300

Any correct code longer than 300 characters will receive a score 
of maxScore * 0.001.
MaxScore is the maximum score attainable for the problem.
Note that whitespace is also treated as a character.





My solution (150 characters, 15 points):

     void main(){import std.stdio;int t,n;readf(" 
%d",&t);while(t--){readf(" %d",&n);real 
a=0,i=0;for(;i<n;i++)a+=(i%2?-1:1)/(i+i+1);writefln("%.15f",a);}}

Link to problem site: 
https://www.hackerrank.com/challenges/leibniz

Anyone care to do better? :)


More information about the Digitalmars-d mailing list