PowerOf 计算

计算给定数字的功率也可以递归地完成。给定基数 n 和 exponent e,我们需要确保通过减少指数 e 来分解问题。

理论范例:

  • 2²= 2x2
  • 2³= 2x2x2 或者 2³=2²x2
    这就是我们的递归算法的秘密(参见下面的代码)。这是关于解决问题并将其分解为更小和更简单的解决方块。
  • 笔记
    • 当基数为 0 时,我们必须知道返回 0 为 0³= 0 x 0 x 0
    • 当指数为 0 时,我们必须知道总是返回 1,因为这是一个数学规则。

代码示例:

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..
}

在 xUnit 中进行测试以验证逻辑:
虽然这不是必需的,但编写测试来验证逻辑总是好的。我包括那些在 xUnit 框架中编写的内容。

    [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 };
}