Leibniz golf in C#

As I suggested in a comment on VisualMelon's answer, the second for loop is being underutilised. By changing some variable scopes it's possible to use the fors in such a way that we save one set of curly brackets and one variable, and perform the sum in the correct order, fixing the bug in the supplied code.

Golfed:

using C=System.Console;class S{static void Main(){for(double n=int.Parse(C.ReadLine()),r,t;n-->0;C.WriteLine(r))for(r=0,t=2*int.Parse(C.ReadLine());t>0;t--)r-=(1-t%4)/--t;}}

Online demo

Ungolfed:

using C = System.Console;
class S {
    static void Main() {
        for (double n=int.Parse(C.ReadLine()), r, t; n-- > 0; C.WriteLine(r))
            for (r=0, t=2*int.Parse(C.ReadLine()); t>0; t--)
                r -= (1-t%4) / --t;
    }
}

Couple of simple things that apply in lots of places:

  1. You've got a free semi-colon in your first for loop which you can make use of

  2. You keep track of i against n, but you as you never use the value of n, you can use it as the counter itself.

  3. As someone else said, you can use int.Parse (or double.Parse) instead of the Convert namespace/class/whatever it is - this makes your using System directive less helpful, and you are better of using the classic using C=System.Console (unless C# 6 has come out, I can't say I'm sure, in which case you can using System.Console directly)

  4. There is an unneeded space after the first for (not sure if you'd accounted for this or not)

I haven't tested this code, but hopefully it will at least help:

using C=System.Console; // 3

class S
{
    static void Main()
    {
        for(int n=int.Parse(C.ReadLine()); // 1, 3, 4
            n-->0;) // 2
        {
            double r=0,t=int.Parse(C.ReadLine()),j=0; // 3
            for(;j<t;)
                r+=(1-j%2*2)/(2*j+++1);
            C.WriteLine(r); // 3
        }
    }
}

Is it possible that the shorter C# solution disregards the first line, and just assumes the input is clean? May well be cheaper to do that if it is allowed.

This is just a quick reply, I might have a better bash at this tomorrow when I have less going on.


  • Instead of Convert.ToInt32, use int.Parse; it saves a few characters.
  • Unless you really need a double, use a float; it's one char shorter than double.

Tags:

C#

Code Golf

Tips