-
재귀함수 문제(반복문 치환)@ 16. 1 ~ 17. 1/면접관련 2017. 1. 6. 18:49
팩토리얼
재귀함수
int fac(int num)
{
if(num <= 1)
return 1;
return n * fac(num - 1);
}
반복문
int fac(int num)
{
if(num <= 1)
return 1;
int current = 1;
for(int i = 2; i <= num; ++i)
{
current = current * i;
}
}
피보나치수열
재귀함수
int fibona(int num)
{
if(num == 0)
return 0;
if(num == 1)
return 1;
return fibona(n - 1) + finoba(n - 2);
}
반복문
if (num < 2)
return 1;
int prev = 1;
int current = 1;
for (int i = 3; i <= num; ++i)
{
int temp = prev;
prev = current;
current = temp + current;
}
return current;
최대공약수 찾기(유클리드 기법)
재귀함수
int Eucild(int a, int b)
{
if (a >= b)
{
if (a%b == 0)
return b;
else
return Eucild(b, a%b);
}
else
{
if (b%a == 0)
return a;
else
return Eucild(a, b%a);
}
}
반복문
int Eucild2(int a, int b)
{
int tempA = a;
int tempB = b;
if (a >= b)
{
while (true)
{
if ((tempA % tempB) == 0)
return tempB;
int tempC = tempA;
tempA = tempB;
tempB = tempC% tempB;
}
}
else
{
}
}
하노이탑재귀함수void hanoi_tower(int n, char from, char temp, char to){if (n == 1){cout << "원판 1을" << from << "에서" << to << "로 옮김" << endl;return;}hanoi_tower(n - 1, from, to, temp);cout << n << "번째 원판을" << from << "에서" << to << "로 옮겼습니다" << endl;hanoi_tower(n - 1, temp, from, to);}1 + 2 + 3 + ...+ n까지 더하는 것
재귀함수
int Test(int n)
{
if (n == 1)
return 1;
return n + Test(n - 1);
}
반복문
int sum2(int n)
{
if (n == 1)
return 1;
int current = 1;
for (int i = 2; i <= n; ++i)
{
current += i;
}
return current;
}
1 + 1/2 + 1/3 + 1/4 ....... + 1/n 까지 더한것
재귀함수
float Test(float n)
{
if (n == 1)
return 1;
return (1.0 / n) + Test(n - 1);
}
'@ 16. 1 ~ 17. 1 > 면접관련' 카테고리의 다른 글
투영변환 정리 (0) 2017.01.08 면접 필기 예상문제 (0) 2017.01.08 콜백함수 정의 정리 (0) 2017.01.06 힙 자료구조 추가 설명 (0) 2017.01.05 원형큐 / 해시테이블 의사코드 정리 (0) 2017.01.05