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

3 วิธีการคำนวณแฟกทอเรียลใน C#

การคำนวณแฟกทอเรียลด้วยลูป for

วิธีการที่ตรงไปตรงมาที่สุดคือการใช้ลูป for เพื่อคูณค่าตัวเลขจาก n ลงมาจนถึง 1

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

using System;

namespace FactorialDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int value = 5;
            int result = value;

            for (int i = value - 1; i >= 1; i--)
            {
                result = result * i;
            }

            Console.WriteLine($"\nแฟกทอเรียลของ {value} = {result}");
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

แฟกทอเรียลของ 5 = 120

การคำนวณแฟกทอเรียลด้วยลูป while

วิธีนี้ใช้ลูป while แทน ซึ่งเหมาะสำหรับกรณีที่ไม่ทราบจำนวนรอบล่วงหน้า

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

using System;

namespace FactorialWhile
{
    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("ค่าที่ได้: {0}", ret);
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

ค่าที่ได้: 120

การคำนวณแฟกทอเรียลด้วย Recursion (การเรียกซ้ำ)

วิธีนี้ใช้ฟังก์ชันเรียกตัวเอง จนถึงค่าฐาน (base case) ที่ n = 1

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

using System;

namespace FactorialRecursive
{
    class Factorial
    {
        public int Calculate(int n)
        {
            if (n == 1)
                return 1;
            else
                return n * Calculate(n - 1);
        }

        static void Main(string[] args)
        {
            int value = 5;
            Factorial fact = new Factorial();
            int ret = fact.Calculate(value);
            Console.WriteLine("ค่าที่ได้: {0}", ret);
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

ค่าที่ได้: 120

สรุปการเปรียบเทียบ

วิธีการ ข้อดี ข้อเสีย
for loop เข้าใจง่าย ประสิทธิภาพดี โค้ดยาวกว่าเล็กน้อย
while loop ยืดหยุ่น สามารถใช้กับเงื่อนไขซับซ้อน ต้องระวัง infinite loop
Recursion โค้ดสั้น อ่านง่าย สวยงาม ใช้หน่วยความจำมากกว่า อาจเกิด StackOverflow ได้