Search code examples
c#mathmathematical-optimization

How to compute equations of this type (x^1+...x^n) in C#?


I have a math problem which is written like this:

x^1+x^2+x^3+...+x^n

Are there any constructs in C# that will help me solve these kinds of equations?

I know I could write a for loop or use recursion to accomplish this, but I remember reading about some construct in c# that will pre-compile such a statement for later execution.

Are there any interesting ways to solve these kinds of equations?


Solution

  • To calculate x^n use Math.Pow:

    Math.Pow(x, n)
    

    If you want to calculate the sum you could use a loop or LINQ. I don't think there's anything wrong with a simple loop here:

    double total = 0;
    for (int i = 1; i <= n; ++i)
    {
        total += Math.Pow(x, i);
    }
    Console.WriteLine(total);
    

    You can write this in LINQ but I don't see any particularly strong reason to do so. Perhaps you could expand on what features you are looking for? Are you looking for better performance?

    Since your question is tagged 'mathematical-optimization' you might also want to optimize it by finding a shortcut. In this specific case it is a geometric series so you can use the formula:

    alt text

    Or in C#:

    static double geometricSeries(double a, double r, int n)
    {
        return a * (1 - Math.Pow(r, n + 1)) / (1 - r);
    }
    

    In other more complex cases finding the formula might be more difficult.