Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีหาค่ยกกำลังของตัวเลขที่กำหนดโดยใช้ Backtracking ด้วย C#


สร้างฟังก์ชัน FindPower ที่รับตัวเลข x และ n โดย x คือฐาน และ n คือจำนวนครั้งที่ต้องยกกำลัง หากตัวเลขเป็นคู่ ให้ทำ x*x และหากเป็นคี่ ให้คูณผลลัพธ์กับ x*x ทำการเรียก recursive ต่อไปจนกว่า 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