How to implement the power function in C#

1 Answer

0 votes
using System;

class PowerCalculation
{
    // Method to compute integer exponentiation
    static double MyPow(double baseValue, int exponent) {
        double result = 1;

        while (exponent > 0) {
            if ((exponent & 1) == 1) {
                result *= baseValue;
            }
            exponent >>= 1;
            baseValue *= baseValue;
        }

        return result;
    }

    static void Main()
    {
        Console.WriteLine(MyPow(2, 3));  // 8
        Console.WriteLine(MyPow(3, 3));  // 27
        Console.WriteLine(MyPow(3, 2));  // 9
        Console.WriteLine(MyPow(2, 2));  // 4
        Console.WriteLine(MyPow(5.0, 2));  // 25
        Console.WriteLine(MyPow(-2, 4)); // 16
    }
}



/*
run:

8
27
9
4
25
16

*/

 



answered Jun 11, 2025 by avibootz
edited Jun 11, 2025 by avibootz

Related questions

1 answer 158 views
1 answer 172 views
1 answer 156 views
1 answer 187 views
1 answer 168 views
1 answer 166 views
1 answer 159 views
...