숫자 x와 n을 사용하는 Find Power 함수를 만듭니다. 여기서 x는 2이고 n은 몇 번이고 거듭제곱을 해야 합니다. 숫자가 짝수이면 x*x를 수행해야 하고 숫자가 홀수이면 결과에 x*x를 곱해야 합니다. n이 0이 될 때까지 재귀 호출을 계속합니다.
숫자 2와 8이 있다고 가정하면 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);
}
}
} 출력
256