본문 바로가기
알고리즘/수업 과제

[알고리즘] 재귀함수

by 왹져박사 2023. 2. 8.
728x90

재귀함수의 대표적인 예 팩토리얼과 피보나치수열로 재귀함수를 연습하였다. 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace reflexive
{
    class Program
    {
        static void Main()
        {
            int input = 5;
            int factorial = Factorial(input);
            Console.WriteLine("{0}! = {1}", input, factorial);
            int fibpnacci = FibonacciN(input);
            Console.WriteLine("{0}번째 항 : {1}", input, fibpnacci);
        }

        static int Factorial(int n)
        {
            if (n == 0 || n == 1)  return 1;

            return n * Factorial(n - 1);
        }

        static int FibonacciN(int n)
        {
            if (n <= 1) return n;

            return FibonacciN(n - 2) + FibonacciN(n - 1);
        }
    }
}

728x90