# Code Golf: Leibniz Series

This is the same question as Solve the CodeSprint4 Leibniz code golf challenge in Python in 66 characters. The variation is that I'm a C programmer. My code for the above question is:

#include <math.h>
main(){
int i,t,p;
scanf("%d",&t);
while(t--)
{
double s=1;
scanf("%d",&p);
for(i=1;i<p;++i)
s+=pow(-1,i)/(2*i+1);
printf("%.12lf\n",s);
}
}


Now I just need to know the places where I could reduce my code length.

• You missed #include<stdio.h> Mar 1, 2015 at 10:21
• Actually, you don't need neither of the two #include @CoolGuy. Most C compilers will complain but compile nevertheless. Mar 2, 2015 at 21:03
• Please include a specification of the requirements in the body of the question. When the link's dead, it's impossible to know what inputs are expected and what output to produce, other than by grokking the code. Jul 20, 2018 at 8:55
• I'm guessing that the objective is to compute the Leibniz formula for π (1 - 1/3 + 1/5 - 1/7 +...) to p terms, t times - is that right? Jul 20, 2018 at 9:07

1. Do everything in one line.
2. Don't read number of test cases, scanf will return -1 on EOF
3. Don't include anything, pow(-1,i) can be replaced by 1-i%2*2
4. Do the sum loop in reverse to save a variable.

Here is my 102 bytes code

main(n){gets(&n);for(double s;s=scanf("%d",&n)>0;printf("%.15f\n",s))while(--n)s+=(1-n%2*2)/(1.+2*n);}

• (1-n%2*2) - It seems that signs depend on n's parity, but they shouldn't. Or not? Feb 15, 2015 at 10:28
• @Qwertiy n here is decreased every loop Feb 15, 2015 at 10:31
• Yes, you are right. By some reason I thought about sign using n and formula using i, but there is n in both parts. Feb 15, 2015 at 10:34

Remove include and replace pow by check.
Use the fact that scanf returns number of read and saved fields.
Replace while via for.
Remove figure brackets.
Use %f in printf for double - only scanf needs %lf.

I didn't check if following code works fine, but even if smth is wrong, the correct result have to be somewhere near it:

main(){
int i,t,p;
double s;
for(scanf("%d",&t);t--;printf("%.12f\n",s))
for(s=i=scanf("%d",&p);i<p;++i)
s+=(i&1?-1:1)/(2.*i+1);
}


By the way, what about making all variables double instead of int?

• Can't i write a code in the comments here? Feb 14, 2015 at 23:23
• Drop the i variable, you just need p and s in the inner loop: for(s=scanf("%d",&p);--p;s+=(p&1?-1:1)/(1+2.*p)); Feb 15, 2015 at 0:02
• (i&1?-1:1) --> (1-i%2*2) Feb 15, 2015 at 1:48
• From memory, I think you can do: main(i,t,p){ to declare them as ints.
– grc
Feb 15, 2015 at 3:23