PowerOf calculation

suggest change

Calculating the power of a given number can be done recursively as well. Given a base number n and exponent e, we need to make sure to split the problem in chunks by decreasing the exponent e.

Theoretical Example:

Notes

  • when the base number is 0, we have to be aware to return 0 as 0³ = 0 x 0 x 0
  • when the exponent is 0, we have to be aware to always return 1, as this is a mathematical rule.

Code Example:

public int CalcPowerOf(int b, int e) {
    if (b == 0) { return 0; } // when base is 0, it doesn't matter, it will always return 0
    if (e == 0) { return 1; } // math rule, exponent 0 always returns 1
    return b * CalcPowerOf(b, e - 1); // actual recursive logic, where we split the problem, aka: 2³ = 2 * 2² etc..
}

Tests in xUnit to verify the logic: Although this is not necessary, it’s always good to write tests to verify your logic. I include those here written in the xUnit framework.

[Theory]
[MemberData(nameof(PowerOfTestData))]
public void PowerOfTest(int @base, int exponent, int expected) {
    Assert.Equal(expected, CalcPowerOf(@base, exponent));
}

public static IEnumerable<object[]> PowerOfTestData() {
    yield return new object[] { 0, 0, 0 };
    yield return new object[] { 0, 1, 0 };
    yield return new object[] { 2, 0, 1 };
    yield return new object[] { 2, 1, 2 };
    yield return new object[] { 2, 2, 4 };
    yield return new object[] { 5, 2, 25 };
    yield return new object[] { 5, 3, 125 };
    yield return new object[] { 5, 4, 625 };
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Recursion:
* PowerOf calculation

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
52 Recursion
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script