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

โปรแกรม C# คำนวณแฟกทอเรียล (Factorial)

แฟกทอเรียล n! = n × (n-1) × ... × 1

ใช้ while loop คำนวณ:

int result = 1;
while (n != 1) {
    result = result * n;
    n = n - 1;
}

ตัวอย่าง: 5! = 120

รอบที่ 1: n=5, result=1×5=5
รอบที่ 2: n=4, result=5×4=20
รอบที่ 3: n=3, result=20×3=60
รอบที่ 4: n=2, result=60×2=120
รอบที่ 5: n=1, หยุดลูป

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

using System;
namespace MyApplication {
    class Factorial {
        public int Calculate(int n) {
            int result = 1;
            while (n != 1) {
                result = result * n;
                n = n - 1;
            }
            return result;
        }
        static void Main(string[] args) {
            int value = 5;
            Factorial fact = new Factorial();
            int ret = fact.Calculate(value);
            Console.WriteLine("Value is : {0}", ret); // 120
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Value is : 120

วิธีทางเลือก (Recursive):

int Factorial(int n) {
    return n <= 1 ? 1 : n * Factorial(n - 1);
}

ข้อควรระวัง: int เก็บได้สูงสุด 12! (479001600) ต้องใช้ long หรือ BigInteger สำหรับเลขใหญ่กว่า