C# Language Recursion PowerOf calculation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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:

  • 2² = 2x2
  • 2³ = 2x2x2 or, 2³ = 2² x 2
    In there lies the secret of our recursive algorithm (see the code below). This is about taking the problem and separating it into smaller and simpler to solve chunks.
  • 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 };
}


Got any C# Language Question?