Code Golf: Leibniz Series

2

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.

Gaurav

Posted 2015-02-14T21:32:02.080

Reputation: 21

You missed #include<stdio.h> – Spikatrix – 2015-03-01T10:21:35.270

Actually, you don't need neither of the two #include @CoolGuy. Most C compilers will complain but compile nevertheless. – Stefano Sanfilippo – 2015-03-02T21:03:55.480

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. – Toby Speight – 2018-07-20T08:55:38.600

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?

– Toby Speight – 2018-07-20T09:07:03.177

Answers

4

  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);}

JayXon

Posted 2015-02-14T21:32:02.080

Reputation: 159

(1-n%2*2) - It seems that signs depend on n's parity, but they shouldn't. Or not? – Qwertiy – 2015-02-15T10:28:08.840

@Qwertiy n here is decreased every loop – JayXon – 2015-02-15T10:31:16.957

Yes, you are right. By some reason I thought about sign using n and formula using i, but there is n in both parts. – Qwertiy – 2015-02-15T10:34:44.763

1

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?

Qwertiy

Posted 2015-02-14T21:32:02.080

Reputation: 2 697

Can't i write a code in the comments here? – Gaurav – 2015-02-14T23:23:44.980

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)); – edc65 – 2015-02-15T00:02:24.557

(i&1?-1:1) --> (1-i%2*2) – Level River St – 2015-02-15T01:48:56.700

From memory, I think you can do: main(i,t,p){ to declare them as ints. – grc – 2015-02-15T03:23:23.180