Iteration は loop を使い、recursion は self-call を使います。表現できる力は同じですが、clarity と cost が異なります。
side by side
python
():
total =
i (, n + ):
total += i
total
():
n == :
n + sum_rec(n - )
Iteration は loop を使い、recursion は self-call を使います。表現できる力は同じですが、clarity と cost が異なります。
():
total =
i (, n + ):
total += i
total
():
n == :
n + sum_rec(n - )
| Aspect | Iteration | Recursion |
|---|---|---|
| Memory | O(1) extra | O(depth) stack |
| Readability | linear work に強い | trees / divide-and-conquer に強い |
| Risk | infinite loop | stack overflow |
| Speed | usually faster | call overhead per frame |
深い recursion は stack overflow の risk があります。depth が unbounded な hot recursive code は、explicit stack を使った iteration に変換します。
right style を選ぶと code は correct で readable になります。recursion は tree/graph code を elegant にしますが、memory cost を理解していないと deep input で crash します。この trade-off judgment は interview でもよく問われます。