C#/수업 과제
[알고리즘] 재귀함수 구현
Bueong_E
2023. 2. 7. 23:50
반응형
SMALL
재귀함수를 이용한 팩토리얼 과 피보나치 수열 구현
using System;
namespace RecursivePractice
{
internal class Program
{
static void Main(string[] args)
{
//재귀함수를 이용한 팩토리얼
Console.WriteLine("5*4*3*2*1 = {0}", RecursiveFact(5));
//재귀함수를 이용한 피보나치 수열
Console.WriteLine("0,1,1,2,3 --> {0}", RecursiveFibonacci(5));
}
public static int RecursiveFact(int n)
{
if (n == 1) return 1;
else
return n * RecursiveFact(n - 1);
}
public static int RecursiveFibonacci(int n)
{
int result = 0;
// n 이 1 혹은 2일 경우 1 을 담아 반환
if (n == 1 || n == 2) result = 1;
// 그외의 경우 F(n) = F(n-1) + F(n-2) 담아 반환
else result = RecursiveFibonacci(n - 1) + RecursiveFibonacci(n - 2);
return result;
}
}
}
재귀함수 이용시 유의할점
- 재귀함수 사용시 종료조건 주의
- 스택 오버플로우 (Stack Overflow) 주의할것 (메모리에 한계가 있음)
반응형
LIST