How to calculate power of three using C#?

CsharpProgrammingServer Side Programming

For power of 3, se the power as 3 and apply a recursive code like the following snippet −

if (p!=0) {
return (n * power(n, p - 1));
}

Let’s say the number is 5, then the iterations would be −

power(5, 3 - 1)); // 25
power (5,2-1): // 5

The above would return5*25 i.e 125 as shown below −

Example

 Live Demo

using System;
using System.IO;

public class Demo {
   public static void Main(string[] args) {
      int n = 5;
      int p = 3;
      long res;
      res = power(n, p);
      Console.WriteLine(res);
   }
   static long power (int n, int p) {
      if (p!=0) {
         return (n * power(n, p - 1));
      }
      return 1;
   }
}

Output

125
raja
Published on 08-Aug-2018 10:57:26
Advertisements