On Monday, 23 February 2015 at 21:30:51 UTC, Steven Schveighoffer
wrote:
On 2/23/15 3:21 PM, Charles wrote:
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? :)
I didn't beat your score, but I did it with ranges (full
character count was 174):
stdin.readln();
foreach(x; stdin.byLine)
writefln("%0.15f", map!(a =>
(a&1?-1:1)/(2.0*a+1))(iota(x.to!int)).sum);
I think if I didn't have to import so many things, I would have
done much better :)
-Steve
It can get down to 155 using ranges, but those imports really are
killer.
void main(){import
std.algorithm,std.conv,std.range,std.stdio;foreach(n;stdin.byLine.drop(1))writefln("%.15f",iota(n.to!int).map!"(-1.0)^^a/(2*a+1)".sum);}