재귀(Recursion)란 자기 자신을 다시 호출하는 것입니다. 동일한 작동을 반복하는 알고리즘을 재귀 알고리즘이라 합니다.
양쪽에 거울이 있을 때 거울에 비친 자신이 무한 반복해서 비치는 현상 — 이것이 바로 재귀입니다!
인형 안에 같은 모양의 작은 인형이 계속 들어 있는 러시아 전통 인형입니다. 열 때마다 같은 동작을 반복합니다.
종이 상자를 겹겹이 열어서 마지막 상자에 반지를 넣고, 다시 역순으로 상자를 닫는 과정이 바로 재귀 호출입니다!
Recursion means a function calling itself. An algorithm that repeats the same operation is called a recursive algorithm.
When two mirrors face each other, the reflection repeats infinitely — that's recursion!
Russian nesting dolls: each doll contains a smaller version of itself. Opening each one is the same action repeated.
Open nested boxes one by one until you find the ring in the innermost box, then close them back in reverse order. This is exactly how recursion works!
Recursion has two phases:
Going deeper (opening boxes) → function calls itself
Coming back (closing boxes) → function returns
종료 조건이 없어 무한 반복됩니다. 실행하면 RecursionError가 발생합니다.
return을 만나면 자신을 호출한 곳으로 되돌아갑니다. 열었던 상자를 역순으로 닫는 과정입니다!
openBox() calls itself with no stopping condition → infinite loop → RecursionError!
1. count = 10 → open 10 boxes
2. Each call decrements count
3. When count == 0 → return (base case!)
4. After return, execute remaining code: "close box"
Base case: the condition that stops recursion (here: count == 0)
Recursive case: the function calling itself
Without a base case → infinite recursion → crash!
1부터 N까지의 합을 재귀로 구합니다.
addNumber(10) = 10 + addNumber(9) = 10 + 9 + addNumber(8) = ... = 10+9+8+...+1 = 55N! = N × (N-1) × ... × 1
addNumber(n) = n + addNumber(n-1)
Base case: n ≤ 1 → return 1
This replaces a for loop with recursion!
factorial(n) = n × factorial(n-1)
Base case: n ≤ 1 → return 1
5! = 5×4×3×2×1 = 120
Loop: result = 1; for i in range(1,n+1): result *= i
Recursion: return n * factorial(n-1)
Both give the same answer, but recursion is more elegant for problems that are naturally self-similar!
Every recursive function needs:
1. Base case: when to stop
2. Recursive case: calling itself with a smaller problem
Code10-04의 상세 실행 과정입니다.
factorial(5) → 5 * factorial(4) — need factorial(4) first!factorial(4) → 4 * factorial(3) — need factorial(3)!factorial(3) → 3 * factorial(2) — need factorial(2)!factorial(2) → 2 * factorial(1) — need factorial(1)!factorial(1) → return 1 (base case reached!)factorial(1) = 1
factorial(2) = 2 × 1 = 2
factorial(3) = 3 × 2 = 6
factorial(4) = 4 × 6 = 24
factorial(5) = 5 × 24 = 120
Winding: calls stack up, going deeper
Unwinding: results return back up the chain
Like opening boxes, then closing them in reverse!
10개의 종이 상자를 재귀적으로 열고, 마지막 상자에서 반지를 넣은 후, 역순으로 상자를 닫는 프로그램을 작성하시오.
두 숫자를 입력받아, 작은 수부터 큰 수까지의 합계를 재귀 함수로 구하시오. 예: 3, 7 → 3+4+5+6+7 = 25
Write a program that recursively opens 10 boxes, places a ring in the last box, then closes boxes in reverse order.
Input two numbers and compute the sum from smaller to larger using recursion. E.g., 3, 7 → 3+4+5+6+7 = 25
5 → 4 → 3 → 2 → 1 → 발사!!
★ ★★ ★★★ ★★★★ ★★★★★
Print before the recursive call → numbers print in descending order (5,4,3,2,1).
Base case: n == 0 → print "Launch!!"
Print after the recursive call → stars print in ascending order (1,2,3,4,5)!
printStar(n-1) is called first, then print('★'*n).
Print before recursion → descending (top-down)
Print after recursion → ascending (bottom-up)
This is the power of recursion: the order of operations around the recursive call determines output order!
gugu(2, 1) → 2×1 출력 후 gugu(2, 2) 호출 → ... → gugu(2, 9)에서 9 < 9 거짓이므로 종료
gugu(dan, num) — dan is fixed for each table, num increments from 1 to 9 via recursion.
The outer for loop handles switching between tables (2단~9단).
pow(x, n) = x × pow(x, n-1)
Base case: n == 0 → return 1
(anything to the power of 0 is 1)
pow(2,4) = 2 × pow(2,3)
pow(2,3) = 2 × pow(2,2)
pow(2,2) = 2 × pow(2,1)
pow(2,1) = 2 × pow(2,0)
pow(2,0) = 1 (base case)
→ 2×2×2×2×1 = 16
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
arySum(arr, n) = arySum(arr, n-1) + arr[n]
Base case: n ≤ 0 → return arr[0]
Recursively sums from index 0 to n!
F(0) = 0, F(1) = 1
F(n) = F(n-1) + F(n-2) for n ≥ 2
Each number is the sum of the two preceding ones.
Fibonacci calls itself twice per call: fibo(n-1) + fibo(n-2). This creates a tree of calls that grows exponentially — very slow for large n!
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
재귀 함수로 N!을 구하고, 호출/반환 과정을 출력하시오. 입력: 5 → 출력: 5! = 120
구구단을 가로로 출력하시오. 각 행에 2×1=2 3×1=3 ... 9×1=9 형태로 출력합니다.
Implement N! with recursion, printing call/return process. Input: 5 → Output: 5! = 120
Print multiplication table horizontally. Each row: 2×1=2 3×1=3 ... 9×1=9
회문(Palindrome)이란 앞에서 읽으나 뒤에서 읽으나 같은 문자열입니다. 예: "kayak", "주유소의 소유주"
.replace(' ',''))와 소문자 변환(.lower())으로 전처리 후 비교합니다. 슬라이싱 pStr[1:len(pStr)-1]로 양끝을 제거합니다.
A Palindrome is a string that reads the same forwards and backwards. E.g., "kayak", "racecar"
.replace(' ','') (remove spaces) and .lower() (lowercase) before comparison. Slicing pStr[1:len(pStr)-1] strips both ends.
프랙탈(Fractal)은 일부를 확대하면 전체와 같은 모양이 반복되는 구조입니다. 재귀 호출로 자연스럽게 구현할 수 있습니다.
r < radius//2이면 더 이상 재귀하지 않습니다. 원이 너무 작아지면 멈추는 것이 핵심입니다.
A Fractal is a structure where zooming into any part reveals the same repeating pattern as the whole. It maps naturally to recursion.
r < radius//2, stop recursing. The key is stopping when circles get too small.
10진수를 다른 진수로 변환할 때 "나누고 나머지를 역순으로 출력"하는 원리를 재귀로 구현합니다.
n < base일 때가 종료 조건입니다.
Converting decimal to another base uses the principle: "divide and print remainders in reverse order", implemented recursively.
n < base is the base case.
시에르핀스키 삼각형은 정삼각형을 4개의 작은 삼각형으로 나누고, 가운데 삼각형을 제거한 뒤 나머지 3개에 대해 같은 과정을 반복하는 프랙탈입니다.
size < 30에서 실제 삼각형을 그립니다.
The Sierpinski Triangle is a fractal formed by dividing an equilateral triangle into 4 smaller triangles, removing the center one, and repeating for the remaining 3.
size < 30.
10진수를 입력받아 2진수, 8진수, 16진수로 변환하는 재귀 함수 notation(base, n)을 작성하시오. 16진수에서는 A~F를 사용합니다.
tkinter를 사용하여 시에르핀스키 삼각형 프랙탈을 재귀적으로 그리는 프로그램을 작성하시오. size가 30 미만이면 빨간색 삼각형을 그립니다.
Write a recursive function notation(base, n) that converts a decimal number to binary, octal, and hexadecimal. Use A~F for hex digits.
Write a program using tkinter to recursively draw a Sierpinski triangle fractal. Draw red triangles when size is less than 30.