This commit is contained in:
krahets
2026-08-18 04:58:51 +08:00
parent ba5285949b
commit 70c2fec77a
10 changed files with 4415 additions and 220 deletions
@@ -11,33 +11,287 @@ comments: true
The two functions below both calculate $1 + 2 + \dots + n$ (assume $n \ge 1$). Set `n` to 4,
answer the questions by following the program's actual execution order, and then compare the efficiency of the two approaches.
```python
def sum_iter(n):
s = 0
for i in range(1, n + 1):
s += i
return s
=== "Python"
def sum_recur(n):
if n == 1:
return 1
return n + sum_recur(n - 1)
```
```python title="complexity_exercises.py"
def sum_iter(n: int) -> int:
"""Iterative summation"""
res = 0
for i in range(1, n + 1):
res += i
return res
def sum_recur(n: int) -> int:
"""Recursive summation"""
if n == 1:
return 1
return n + sum_recur(n - 1)
```
=== "C++"
```cpp title="complexity_exercises.cpp"
/* Iterative summation */
int sumIter(int n) {
int res = 0;
for (int i = 1; i <= n; ++i) {
res += i;
}
return res;
}
/* Recursive summation */
int sumRecur(int n) {
if (n == 1) {
return 1;
}
return n + sumRecur(n - 1);
}
```
=== "Java"
```java title="complexity_exercises.java"
/* Iterative summation */
int sumIter(int n) {
int res = 0;
for (int i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* Recursive summation */
int sumRecur(int n) {
if (n == 1) {
return 1;
}
return n + sumRecur(n - 1);
}
```
=== "C#"
```csharp title="complexity_exercises.cs"
/* Iterative summation */
int SumIter(int n) {
int res = 0;
for (int i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* Recursive summation */
int SumRecur(int n) {
if (n == 1) {
return 1;
}
return n + SumRecur(n - 1);
}
```
=== "Go"
```go title="complexity_exercises.go"
/* Iterative summation */
func sumIter(n int) int {
res := 0
for i := 1; i <= n; i++ {
res += i
}
return res
}
/* Recursive summation */
func sumRecur(n int) int {
if n == 1 {
return 1
}
return n + sumRecur(n-1)
}
```
=== "Swift"
```swift title="complexity_exercises.swift"
/* Iterative summation */
func sumIter(n: Int) -> Int {
var res = 0
for i in 1 ... n {
res += i
}
return res
}
/* Recursive summation */
func sumRecur(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumRecur(n: n - 1)
}
```
=== "JS"
```javascript title="complexity_exercises.js"
/* Iterative summation */
function sumIter(n) {
let res = 0;
for (let i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* Recursive summation */
function sumRecur(n) {
if (n === 1) {
return 1;
}
return n + sumRecur(n - 1);
}
```
=== "TS"
```typescript title="complexity_exercises.ts"
/* Iterative summation */
function sumIter(n: number): number {
let res = 0;
for (let i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* Recursive summation */
function sumRecur(n: number): number {
if (n === 1) {
return 1;
}
return n + sumRecur(n - 1);
}
```
=== "Dart"
```dart title="complexity_exercises.dart"
/* Iterative summation */
int sumIter(int n) {
int res = 0;
for (int i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* Recursive summation */
int sumRecur(int n) {
if (n == 1) {
return 1;
}
return n + sumRecur(n - 1);
}
```
=== "Rust"
```rust title="complexity_exercises.rs"
/* Iterative summation */
fn sum_iter(n: i32) -> i32 {
let mut res = 0;
for i in 1..=n {
res += i;
}
res
}
/* Recursive summation */
fn sum_recur(n: i32) -> i32 {
if n == 1 {
return 1;
}
n + sum_recur(n - 1)
}
```
=== "C"
```c title="complexity_exercises.c"
/* Iterative summation */
int sumIter(int n) {
int res = 0;
for (int i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* Recursive summation */
int sumRecur(int n) {
if (n == 1) {
return 1;
}
return n + sumRecur(n - 1);
}
```
=== "Kotlin"
```kotlin title="complexity_exercises.kt"
/* Iterative summation */
fun sumIter(n: Int): Int {
var res = 0
for (i in 1..n) {
res += i
}
return res
}
/* Recursive summation */
fun sumRecur(n: Int): Int {
if (n == 1) {
return 1
}
return n + sumRecur(n - 1)
}
```
=== "Ruby"
```ruby title="complexity_exercises.rb"
### Iterative summation ###
def sum_iter(n)
res = 0
for i in 1..n
res += i
end
res
end
### Recursive summation ###
def sum_recur(n)
return 1 if n == 1
n + sum_recur(n - 1)
end
```
<!-- numbered-subquestions -->
1. When `sum_iter(4)` runs, what is the value of `s` after each loop iteration?
2. When `sum_recur(4)` runs, which function calls occur in order? As the calls return from the deepest level, how is the result obtained?
1. When the iterative function runs with `n = 4`, what is the value of the accumulator `res` after each loop iteration?
2. When the recursive function runs with `n = 4`, which values does the argument `n` take in order? As the calls return from the deepest level, how is the result obtained?
3. What are the time and space complexities of the two approaches? Explain your reasoning using the execution processes from Questions 1 and 2.
??? success "Answer"
1. The loop variable `i` takes the values `1, 2, 3, 4`. After each iteration, `s` becomes
`1, 3, 6, 10`, respectively, so `sum_iter(4)` returns 10.
1. The loop variable `i` takes the values `1, 2, 3, 4`. After each iteration, `res` becomes
`1, 3, 6, 10`, respectively, so the iterative function returns 10.
2. The function calls occur in this order:
`sum_recur(4) → sum_recur(3) → sum_recur(2) → sum_recur(1)`.
`sum_recur(1)` returns 1. The remaining calls then obtain `2 + 1 = 3`, `3 + 3 = 6`, and `4 + 6 = 10`, in that order.
2. The argument `n` takes the values `4 → 3 → 2 → 1`.
The deepest call returns 1. The remaining calls then obtain `2 + 1 = 3`, `3 + 3 = 6`, and `4 + 6 = 10`, in that order.
At the deepest point, all four function calls are still unfinished.
3. Both functions perform a number of loop iterations or calls proportional to $n$, so both have a time complexity of $O(n)$.
@@ -51,22 +305,414 @@ def sum_recur(n):
Each of the following code fragments takes a positive integer $n$ as input. Order them from lowest to highest time complexity, and give the complexity of each one.
```python
# Fragment 1
s = 0
for i in range(n):
s += i
=== "Python"
# Fragment 2
s = 0
for i in range(n):
for j in range(i, n):
s += j
```python title="complexity_exercises.py"
def linear_loop(n: int) -> int:
"""Linear loop"""
res = 0
for i in range(n):
res += i
return res
# Fragment 3
while n > 1:
n = n // 2
```
def quadratic_loop(n: int) -> int:
"""Quadratic loop"""
res = 0
for i in range(n):
for j in range(i, n):
res += j
return res
def logarithmic_loop(n: int) -> int:
"""Logarithmic loop"""
while n > 1:
n //= 2
return n
```
=== "C++"
```cpp title="complexity_exercises.cpp"
/* Linear loop */
int linearLoop(int n) {
int res = 0;
for (int i = 0; i < n; ++i) {
res += i;
}
return res;
}
/* Quadratic loop */
int quadraticLoop(int n) {
int res = 0;
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
res += j;
}
}
return res;
}
/* Logarithmic loop */
int logarithmicLoop(int n) {
while (n > 1) {
n /= 2;
}
return n;
}
```
=== "Java"
```java title="complexity_exercises.java"
/* Linear loop */
int linearLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
res += i;
}
return res;
}
/* Quadratic loop */
int quadraticLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
res += j;
}
}
return res;
}
/* Logarithmic loop */
int logarithmicLoop(int n) {
while (n > 1) {
n /= 2;
}
return n;
}
```
=== "C#"
```csharp title="complexity_exercises.cs"
/* Linear loop */
int LinearLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
res += i;
}
return res;
}
/* Quadratic loop */
int QuadraticLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
res += j;
}
}
return res;
}
/* Logarithmic loop */
int LogarithmicLoop(int n) {
while (n > 1) {
n /= 2;
}
return n;
}
```
=== "Go"
```go title="complexity_exercises.go"
/* Linear loop */
func linearLoop(n int) int {
res := 0
for i := 0; i < n; i++ {
res += i
}
return res
}
/* Quadratic loop */
func quadraticLoop(n int) int {
res := 0
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
res += j
}
}
return res
}
/* Logarithmic loop */
func logarithmicLoop(n int) int {
for n > 1 {
n /= 2
}
return n
}
```
=== "Swift"
```swift title="complexity_exercises.swift"
/* Linear loop */
func linearLoop(n: Int) -> Int {
var res = 0
for i in 0 ..< n {
res += i
}
return res
}
/* Quadratic loop */
func quadraticLoop(n: Int) -> Int {
var res = 0
for i in 0 ..< n {
for j in i ..< n {
res += j
}
}
return res
}
/* Logarithmic loop */
func logarithmicLoop(n: Int) -> Int {
var n = n
while n > 1 {
n /= 2
}
return n
}
```
=== "JS"
```javascript title="complexity_exercises.js"
/* Linear loop */
function linearLoop(n) {
let res = 0;
for (let i = 0; i < n; i++) {
res += i;
}
return res;
}
/* Quadratic loop */
function quadraticLoop(n) {
let res = 0;
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
res += j;
}
}
return res;
}
/* Logarithmic loop */
function logarithmicLoop(n) {
while (n > 1) {
n = Math.floor(n / 2);
}
return n;
}
```
=== "TS"
```typescript title="complexity_exercises.ts"
/* Linear loop */
function linearLoop(n: number): number {
let res = 0;
for (let i = 0; i < n; i++) {
res += i;
}
return res;
}
/* Quadratic loop */
function quadraticLoop(n: number): number {
let res = 0;
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
res += j;
}
}
return res;
}
/* Logarithmic loop */
function logarithmicLoop(n: number): number {
while (n > 1) {
n = Math.floor(n / 2);
}
return n;
}
```
=== "Dart"
```dart title="complexity_exercises.dart"
/* Linear loop */
int linearLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
res += i;
}
return res;
}
/* Quadratic loop */
int quadraticLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
res += j;
}
}
return res;
}
/* Logarithmic loop */
int logarithmicLoop(int n) {
while (n > 1) {
n ~/= 2;
}
return n;
}
```
=== "Rust"
```rust title="complexity_exercises.rs"
/* Linear loop */
fn linear_loop(n: i32) -> i32 {
let mut res = 0;
for i in 0..n {
res += i;
}
res
}
/* Quadratic loop */
fn quadratic_loop(n: i32) -> i32 {
let mut res = 0;
for i in 0..n {
for j in i..n {
res += j;
}
}
res
}
/* Logarithmic loop */
fn logarithmic_loop(mut n: i32) -> i32 {
while n > 1 {
n /= 2;
}
n
}
```
=== "C"
```c title="complexity_exercises.c"
/* Linear loop */
int linearLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
res += i;
}
return res;
}
/* Quadratic loop */
int quadraticLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
res += j;
}
}
return res;
}
/* Logarithmic loop */
int logarithmicLoop(int n) {
while (n > 1) {
n /= 2;
}
return n;
}
```
=== "Kotlin"
```kotlin title="complexity_exercises.kt"
/* Linear loop */
fun linearLoop(n: Int): Int {
var res = 0
for (i in 0 until n) {
res += i
}
return res
}
/* Quadratic loop */
fun quadraticLoop(n: Int): Int {
var res = 0
for (i in 0 until n) {
for (j in i until n) {
res += j
}
}
return res
}
/* Logarithmic loop */
fun logarithmicLoop(n: Int): Int {
var value = n
while (value > 1) {
value /= 2
}
return value
}
```
=== "Ruby"
```ruby title="complexity_exercises.rb"
### Linear loop ###
def linear_loop(n)
res = 0
for i in 0...n
res += i
end
res
end
### Quadratic loop ###
def quadratic_loop(n)
res = 0
for i in 0...n
for j in i...n
res += j
end
end
res
end
### Logarithmic loop ###
def logarithmic_loop(n)
n /= 2 while n > 1
n
end
```
??? success "Answer"
+205 -12
View File
@@ -29,23 +29,216 @@ Classify each task as "suitable for divide and conquer," "can use divide and con
The recursive function below uses divide and conquer to calculate $x^n$:
```python
def fast_pow(x, n):
if n == 0:
return 1
half = fast_pow(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
```
=== "Python"
Use it to calculate `fast_pow(3, 5)`:
```python title="fast_power.py"
def fast_pow(x: int, n: int) -> int:
"""Exponentiation by squaring"""
if n == 0:
return 1
half = fast_pow(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
```
=== "C++"
```cpp title="fast_power.cpp"
/* Exponentiation by squaring */
int fastPow(int x, int n) {
if (n == 0) {
return 1;
}
int half = fastPow(x, n / 2);
if (n % 2 == 0) {
return half * half;
}
return half * half * x;
}
```
=== "Java"
```java title="fast_power.java"
/* Exponentiation by squaring */
int fastPow(int x, int n) {
if (n == 0) {
return 1;
}
int half = fastPow(x, n / 2);
if (n % 2 == 0) {
return half * half;
}
return half * half * x;
}
```
=== "C#"
```csharp title="fast_power.cs"
/* Exponentiation by squaring */
int FastPow(int x, int n) {
if (n == 0) {
return 1;
}
int half = FastPow(x, n / 2);
if (n % 2 == 0) {
return half * half;
}
return half * half * x;
}
```
=== "Go"
```go title="fast_power.go"
/* Exponentiation by squaring */
func fastPow(x, n int) int {
if n == 0 {
return 1
}
half := fastPow(x, n/2)
if n%2 == 0 {
return half * half
}
return half * half * x
}
```
=== "Swift"
```swift title="fast_power.swift"
/* Exponentiation by squaring */
func fastPow(x: Int, n: Int) -> Int {
if n == 0 {
return 1
}
let half = fastPow(x: x, n: n / 2)
if n % 2 == 0 {
return half * half
}
return half * half * x
}
```
=== "JS"
```javascript title="fast_power.js"
/* Exponentiation by squaring */
function fastPow(x, n) {
if (n === 0) {
return 1;
}
const half = fastPow(x, Math.floor(n / 2));
if (n % 2 === 0) {
return half * half;
}
return half * half * x;
}
```
=== "TS"
```typescript title="fast_power.ts"
/* Exponentiation by squaring */
function fastPow(x: number, n: number): number {
if (n === 0) {
return 1;
}
const half = fastPow(x, Math.floor(n / 2));
if (n % 2 === 0) {
return half * half;
}
return half * half * x;
}
```
=== "Dart"
```dart title="fast_power.dart"
/* Exponentiation by squaring */
int fastPow(int x, int n) {
if (n == 0) {
return 1;
}
int half = fastPow(x, n ~/ 2);
if (n % 2 == 0) {
return half * half;
}
return half * half * x;
}
```
=== "Rust"
```rust title="fast_power.rs"
/* Exponentiation by squaring */
fn fast_pow(x: i32, n: i32) -> i32 {
if n == 0 {
return 1;
}
let half = fast_pow(x, n / 2);
if n % 2 == 0 {
return half * half;
}
half * half * x
}
```
=== "C"
```c title="fast_power.c"
/* Exponentiation by squaring */
int fastPow(int x, int n) {
if (n == 0) {
return 1;
}
int half = fastPow(x, n / 2);
if (n % 2 == 0) {
return half * half;
}
return half * half * x;
}
```
=== "Kotlin"
```kotlin title="fast_power.kt"
/* Exponentiation by squaring */
fun fastPow(x: Int, n: Int): Int {
if (n == 0) {
return 1
}
val half = fastPow(x, n / 2)
if (n % 2 == 0) {
return half * half
}
return half * half * x
}
```
=== "Ruby"
```ruby title="fast_power.rb"
### Exponentiation by squaring ###
def fast_pow(x, n)
return 1 if n == 0
half = fast_pow(x, n / 2)
return half * half if n.even?
half * half * x
end
```
Set `x = 3` and `n = 5`, and use this function to calculate the result:
<!-- numbered-subquestions -->
1. As the recursive calls proceed, which values does the argument `n` take in order?
2. Starting from the deepest call, what value does each level return?
3. Why should the result be stored in `half` instead of writing `fast_pow(x, n // 2)` twice?
3. Why should the recursive result be stored in `half` instead of calling the same subproblem once on each side of the multiplication?
??? success "Answer"
@@ -54,7 +247,7 @@ Use it to calculate `fast_pow(3, 5)`:
2. When `n = 0`, the function returns 1. When `n = 1`, it returns $1×1×3=3$.
When `n = 2`, it returns $3×3=9$. When `n = 5`, it returns $9×9×3=243$.
3. If `fast_pow(x, n // 2)` were written once on each side of the multiplication, the two recursive calls would calculate exactly the same subproblem.
3. If the same subproblem were called once on each side of the multiplication, the two recursive calls would perform exactly the same calculation.
Storing the result in `half` means that each level makes only one recursive call, so the recursion depth is about $\log n$.
Making two calls would cause a great deal of repeated computation.