สร้างฟังก์ชันหากำลังซึ่งใช้ตัวเลข x กับ n โดยที่ 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