포스트

(C#) 15. 코드의 흐름 제어 (factorial)

factorial

(Factorial)

  • 최초 작성일: 2021년 3월 21일(월)

##

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;

namespace ex3
{
    class Program
    {
        // 팩토리얼
        static int Factorial(int n)
        {
            int ret = 1;
            for (int num = 1; num <= n; num++)
            {
                ret *= num;
            }
            return ret;
        }

        static int Factorial1(int n)
        {
            if (n <= 1)
                return 1;
            return n * Factorial(n - 1);
        }
        static void Main(string[] args)
        {
            // 5! = 5 * 4!
            // 5! = 5 * 4 * 3 * 2 * 1
            // n! = n * (n-1) * ... * 1 (n >= 1)
            int ret = Factorial(5);
            int ret1 = Factorial1(5);

            Console.WriteLine(ret);
            Console.WriteLine(ret1);
        }
    }
}

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.