본문 바로가기
C# 언어/C# 문제 풀이

[C#] 팩토리얼 / 재귀함수

by 후야- 2024. 3. 19.
using System.Security.Cryptography.X509Certificates;

namespace CShop
{
    class Program
    {
        // 팩토리얼 5! = 5 + 4 + 3 + 2 + 1
        static int Factorial(int n)
        {
            int ret = 1;
            for (int num = 1; num <= n; num++)
            {
                ret *= num;
            }
            return ret;
        }


        static void Main(string[] args)
        {
            int ret = Factorial(5);
            Console.WriteLine(ret);

        }
    }
}

 

 

 

✳ 재귀함수

→ 자기 자신을 반복해서 호출

using System.Security.Cryptography.X509Certificates;

namespace CShop
{
    class Program
    {
        // 재귀함수 : 자기 자신을 반복해서 호출
        static int Factorial(int n)
        {
            if (n <= 1)
                return 1;   // 1을 반환해주세요
            return n * Factorial(n - 1);
        }


        static void Main(string[] args)
        {

            // 5! = 5 * (4*3*2*1) (4!) (3*2*1) (3!)
            int ret = Factorial(5);
            Console.WriteLine(ret);
        }
    }
}

'C# 언어 > C# 문제 풀이' 카테고리의 다른 글

[C#] 피라미드  (0) 2024.03.19
[C#] 구구단  (0) 2024.03.19