PI Calculator, Interview Challenge
In an interview it usually doesn't matter if you actually solve the problem. What is most important is the way you (try to) solve it. If they don't tell you it should be the possibly fastest solution ever you should not optimize it prematurely but instead show that you know how to write SOLID code like encapsulate propertly, make the code testable etc. show that you know the techniques.



Here you could split the logic up into multiple methods for example you could have one generating the alternating sequence [1, -3, 5, -7, 9, -11, ...] that you can validate with a test:

public static IEnumerable&lt;int&gt; AlternatingSequence()
{
    var i = 1;
    yield return i;
    var b = false;
    while (true) yield return ((b = !b) ? -1 : 1) * (i = i + 2);
}


then you can work on the PI itself and use it for the actual calculation which is then as simple as a LINQ expression:

public static double EstimatePI(int sumLength) 
{
    return (4 * AlternatingSequence().Take(sumLength).Sum(x =&gt; 1.0 / x));
}

var pi = EstimatePI(500_000).Dump(); // 3,14159065358969




There's all kind of stuff you can show you are familiar with in this simple task like DI or strategy pattern:

public static double EstimatePI(int sumLength, IEnumerable&lt;int&gt; sequenceGenerator) 
{
    return (4 * sequenceGenerator.Take(sumLength).Sum(x =&gt; 1.0 / x));
}

var pi = EstimatePI(500_000, AlternatingSequence);


or even more advanced DI and encapsulation

class PiCalculator
{ 
    private readonly IEnumerable&lt;int&gt; _sequenceGenerator;

    public PiCalculator(IEnumerable&lt;int&gt; sequenceGenerator)
    {
        _sequenceGenerator = sequenceGenerator;
    }

    public double EstimatePi(int sumLength)
    {
        ...
    }
}


or you can add an interface to show you know what abstraction means:

interface IPiCalculator
{ 
    double EstimatePi(int sumLength);
}




Is this an overkill? It might be but it shows me that you are able to write modular and testable code. Writing short code is a good thing too but if you write only five lines inside a Main in a job interview, you'll go home without any prospects of getting the job. Again, in an inteview you should sell your coding skills and not show how smart you are in solving something with a fewest possible lines of code that no one can verify.