[Solved] How do i calculate power without math.pow c# [closed]


Using loops you could do something like this:

public double Pow(double num, int pow)
{
    double result = 1;

    if (pow > 0)
    {
        for (int i = 1; i <= pow; ++i)
        {
            result *= num;
        }
    }
    else if (pow < 0)
    {
        for (int i = -1; i >= pow; --i)
        {
            result /= num;
        }
    }

    return result;
}

Using enumerables you could do something like this:

using System.Collections;
using System.Collections.Generic;

public double Pow(double num, int pow)
{
    var sequence = Enumerable.Repeat(num, pow);

    if (pow > 0)
    {
        return sequence.Aggregate(1, (accumulate, current) => accumulate * current);
    }
    else if (pow < 0)
    {
        return sequence.Aggregate(1, (accumulate, current) => accumulate / current);
    }
    else
    {
        return 1;
    }
}

1

solved How do i calculate power without math.pow c# [closed]