C# Program to Find Power of Number
Math.Pow(base, exponent) or by writing a loop to multiply the base number by itself exponent times.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { double baseNum = 2; int exponent = 3; double result = Math.Pow(baseNum, exponent); Console.WriteLine($"{baseNum} to the power {exponent} is {result}"); } }
Dry Run
Let's trace the example where base=2 and exponent=3 through the code using Math.Pow.
Set base and exponent
baseNum = 2, exponent = 3
Calculate power
result = Math.Pow(2, 3) which equals 8
Print result
Output: '2 to the power 3 is 8'
| Step | Operation | Value |
|---|---|---|
| 1 | Set baseNum and exponent | 2, 3 |
| 2 | Calculate Math.Pow(2,3) | 8 |
| 3 | Print output | 2 to the power 3 is 8 |
Why This Works
Step 1: Using Math.Pow
The Math.Pow method takes two arguments: the base and the exponent, and returns the base raised to that exponent.
Step 2: Why it works
It internally multiplies the base by itself exponent times, handling decimal and negative exponents correctly.
Step 3: Output formatting
The result is printed with a message showing the base, exponent, and the calculated power.
Alternative Approaches
using System; class Program { static void Main() { double baseNum = 2; int exponent = 3; double result = 1; for (int i = 0; i < exponent; i++) { result *= baseNum; } Console.WriteLine($"{baseNum} to the power {exponent} is {result}"); } }
using System; class Program { static double Power(double baseNum, int exponent) { if (exponent == 0) return 1; return baseNum * Power(baseNum, exponent - 1); } static void Main() { double baseNum = 2; int exponent = 3; double result = Power(baseNum, exponent); Console.WriteLine($"{baseNum} to the power {exponent} is {result}"); } }
Complexity: O(n) time, O(1) space
Time Complexity
Using a loop to multiply the base n times results in O(n) time, where n is the exponent. Math.Pow is optimized and faster internally.
Space Complexity
The space used is constant O(1) since only a few variables store the base, exponent, and result.
Which Approach is Fastest?
Math.Pow is the fastest and most reliable method as it uses optimized native code, while loops and recursion are slower and limited to integer exponents.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Math.Pow | O(1) (optimized) | O(1) | All exponent types, including decimals and negatives |
| Loop multiplication | O(n) | O(1) | Simple integer exponents, beginner understanding |
| Recursive method | O(n) | O(n) due to call stack | Learning recursion, small integer exponents |
Math.Pow for simplicity and to handle all exponent types safely.