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

คำนวณเลขยกกำลังด้วย Recursion ใน C#

ภาพรวม

ใช้ recursion คำนวณ base^exponent โดยเรียกฟังก์ชันตัวเองจน exponent = 0

โค้ดตัวอย่าง


using System;

public class Demo {
    public static void Main() {
        int n = 15;
        int p = 2;
        long result = Power(n, p);
        Console.WriteLine($"{n}^{p} = {result}"); // 225
    }

    static long Power(int n, int p) {
        if (p == 0) return 1;          // Base case
        if (p < 0) return 1 / Power(n, -p); // Negative exponent (คืนค่า int จะได้ 0)

        return n * Power(n, p - 1);    // Recursive case
    }
}

ผลลัพธ์


15^2 = 225

ปรับปรุง: รองรับ Negative Exponent และทศนิยม


static double Power(double n, int p) {
    if (p == 0) return 1;
    if (p < 0) return 1 / Power(n, -p);

    // Optimization: Exponentiation by squaring O(log p)
    if (p % 2 == 0) {
        double half = Power(n, p / 2);
        return half * half;
    }
    return n * Power(n, p - 1);
}

วิธีอื่นๆ

1. Math.Pow (Built-in)


double result = Math.Pow(15, 2); // 225

2. Iterative (Loop) - ไม่ใช้ Stack Overflow


static long PowerIterative(int n, int p) {
    long result = 1;
    for (int i = 0; i < p; i++) {
        result *= n;
    }
    return result;
}

3. Bit Shifting (สำหรับฐาน 2)


int pow2 = 1 << 5; // 2^5 = 32

ข้อควรระวัง

  • Recursion อาจก่อให้เกิด StackOverflowException ถ้า exponent ใหญ่
  • ใช้ long หรือ double ป้องกัน overflow
  • Exponentiation by squaring เร็วกว่ามาก (O(log n) vs O(n))