How to find the power of any given number by backtracking using C#?



Suppose if we have a number 2 and 8, then 2*2*2*2*2*2*2*2 =256.

using System;
namespace ConsoleApplication{
   public class BackTracking{
      public int FindPower(int x, int n){
         int result;
         if (n == 0){
            return 1;
         }
         result = FindPower(x, n / 2);
         if (n % 2 == 0){
            return result * result;
         }
         else{
            return x * result * result;
         }
      }
   }
   class Program{
      static void Main(string[] args){
         BackTracking b = new BackTracking();
         int res = b.FindPower(2, 8);
         Console.WriteLine(res);
      }
   }
}

0 Comment's

Comment Form

Submit Comment