mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-19 15:00:58 +00:00
Add multilingual exercise code (#1959)
Replace the exercise pages' Python-only snippets with source-backed implementations for the 13 visible programming languages, and localize reader-facing comments by site language. Zig remains out of scope. Approval bypass: repository protection requires one approval but does not enforce it for administrators. All 68 completed checks succeeded; four non-required Java jobs remained queued on the existing ubuntu-20.04 workflow, with no failed checks.
This commit is contained in:
@@ -25,23 +25,17 @@
|
||||
|
||||
次の再帰関数は、分割統治を使って $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
|
||||
```src
|
||||
[file]{fast_power}-[class]{}-[func]{fast_pow}
|
||||
```
|
||||
|
||||
この関数で `fast_pow(3, 5)` を計算します。
|
||||
`x = 3`、`n = 5` として、この関数で結果を計算します。
|
||||
|
||||
<!-- numbered-subquestions -->
|
||||
|
||||
1. 再帰呼び出しでは、引数 `n` はどのような値に順に変わりますか?
|
||||
2. 最も深い呼び出しから戻るとき、各呼び出しはどの値を順に返しますか?
|
||||
3. `fast_pow(x, n // 2)` を 2 回書くのではなく、先に `half` へ保存するのはなぜですか?
|
||||
3. 同じ部分問題を乗算の両側で 1 回ずつ呼び出すのではなく、再帰結果を先に `half` へ保存するのはなぜですか?
|
||||
|
||||
??? success "解答"
|
||||
|
||||
@@ -50,7 +44,7 @@ def fast_pow(x, n):
|
||||
2. `n = 0` のとき 1 を返します。`n = 1` のとき $1×1×3=3$、
|
||||
`n = 2` のとき $3×3=9$、`n = 5` のとき $9×9×3=243$ を返します。
|
||||
|
||||
3. 乗算の両側に `fast_pow(x, n // 2)` を 1 回ずつ書くと、2 つの再帰呼び出しがまったく同じ部分問題を計算します。
|
||||
3. 同じ部分問題を乗算の両側で 1 回ずつ呼び出すと、2 つの再帰呼び出しがまったく同じ計算を行います。
|
||||
結果を先に `half` へ保存すれば、各層で再帰するのは 1 回だけとなり、再帰の深さは約 $\log n$ です。
|
||||
2 回呼び出すと、大量の重複計算が発生します。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user