Create a function to Find Power which takes the number x and n, where x is the 2 and n is how many times, we have to do the power. If the number is even then we have to do x*x and if the number is odd multiply the result with x*x. Continue the recursive call until the n becomes 0.
Suppose if we have a number 2 and 8, then 2*2*2*2*2*2*2*2 =256.
Example
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);
}
}
}Output
256