PowerOf calculation C# with 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 Tests in xUnit to verify the logic: if (e == 0) { return 1; } // math rule, exponent 0 always returns 1 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)); } return b * CalcPowerOf(b, e - 1); // actual recursive logic, where we split the problem, aka: 2 ³ public static IEnumerable PowerOfTestData() { yield return new object[] { 0, 0, 0 }; yield return new object[] { 0, 1, 0 }; yield return new object[] { 2, 0, 1 }; = 2 * 2² etc.. 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 }; }