본문 바로가기

자료구조

재귀함수 - 팩토리얼

더보기
using System;

namespace HelloWorld
{
    class App
    {
        //생성자
        public App()
        {
            int result = Factorial(9);
            Console.WriteLine(result);
        }
        //int result = Factorial(5)
        //팩토리얼 구하는 메서드를 작성하세요 
        //5! = 5x4x3x2x1
        //4! = 4x3x2x1
        //3! = 3x2x1
        //2! = 2x1
        //1! = 1
        //0! = 1

        int Factorial(int num)
        {
            int temp = num;
            if (temp == 0)
            {
                Console.Write("{0}! = ", num);
                return 1;
            }
            else
            {
                Console.Write("{0}! = {0}", num);
            }
            while (temp > 1)
            {
                --temp;
                Console.Write("x{0}", temp);
            }
            Console.WriteLine();
            Factorial(num - 1);
            return 1;
        }
    }
}

더보기
using System;

namespace HelloWorld
{
    class App
    {
        //생성자
        public App()
        {
            int result = Factorial(10);
            Console.WriteLine(result);
        }
        //int result = Factorial(5)
        //팩토리얼 구하는 메서드를 작성하세요 
        //5! = 5x4x3x2x1
        //4! = 4x3x2x1
        //3! = 3x2x1
        //2! = 2x1
        //1! = 1
        //0! = 1

        int Factorial(int num)
        {
            int temp = num;
            int temp2 = 1;
            if (temp == 0)
            {
                Console.Write("{0}! = ", num);
                return 1;
            }
            else
            {
                while (temp > 1)
                {
                    temp2 = temp * temp2;
                    --temp;
                }
                Console.Write("{0}! = {1}", num, temp2);
            }
            Console.WriteLine();
            Factorial(num - 1);
            return 1;
        }
    }
}

'자료구조' 카테고리의 다른 글

스택 (stack) Push  (0) 2021.12.28
재귀함수 - Linked List에서 head부터 시작해서 마지막노드 반환  (0) 2021.12.28
재귀함수  (0) 2021.12.28
노드 찾아서 앞쪽에 붙이기  (0) 2021.12.28
Node  (0) 2021.12.28