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

I have a math problem that is written like this:

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

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

I know that I can write a for loop or use recursion to accomplish this, but I remember reading about some construction in C # that would precompile such an operator for later execution.

Are there any interesting ways to solve these equations?

+3
source share
6 answers

To calculate x ^ n, use Math.Pow :

Math.Pow(x, n)

, LINQ. , - :

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

LINQ, . , , ? ?

" ", , . , :

alt text

#:

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

.

+8

, . , , , - , Horner. #.

+7

, . , . , "" :

public static double SumExponents(double x, int n)
{
    double total = 0;
    for (int i = 1; i <= n; i++)
    {
         total += Math.Pow(x, i);
    }
    return total;
}

LINQ :

public static double SumExponents(double x, int n)
{
    return Enumerable.Range(1, n)
                     .Select(i => Math.Pow(x, i))
                     .Sum();
}

:

Func<double, int, double> func = (x, n) => Enumerable.Range(1, n)
                                              .Select(i => Math.Pow(x, i))
                                              .Sum();

, ? , . , .

+5

# . O (1) . (, .)

x*(x^n - 1)/(x - 1)
+1
source
int total = 0;
for(int i = 1; i <= n; i++)
    total += Math.Pow(x, i);
0
source

Just like select \ sum, you can also use Aggregatebending sequences.

int n;
double x;
double result = Enumerable.Range(1, n)
    .Aggregate(0.0, (acc, i) => acc + Math.Pow(x, i));
0
source

Source: https://habr.com/ru/post/1759686/


All Articles