From 28c1e74c1d3594fca7cc41b78a6bd18b700c5ce9 Mon Sep 17 00:00:00 2001 From: Yudong Jin Date: Tue, 18 Aug 2026 04:57:57 +0800 Subject: [PATCH] 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. --- .../CMakeLists.txt | 1 + .../complexity_exercises.c | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 1 + .../c/chapter_divide_and_conquer/fast_power.c | 26 ++++++++ .../CMakeLists.txt | 3 +- .../complexity_exercises.cpp | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 3 +- .../chapter_divide_and_conquer/fast_power.cpp | 26 ++++++++ .../complexity_exercises.cs | 66 +++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.cs | 28 ++++++++ .../complexity_exercises.dart | 63 ++++++++++++++++++ .../fast_power.dart | 23 +++++++ .../complexity_exercises.go | 50 ++++++++++++++ .../complexity_exercises_test.go | 22 +++++++ .../chapter_divide_and_conquer/fast_power.go | 17 +++++ .../fast_power_test.go | 13 ++++ .../complexity_exercises.java | 62 +++++++++++++++++ .../fast_power.java | 27 ++++++++ .../complexity_exercises.js | 63 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.js | 21 ++++++ .../complexity_exercises.kt | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.kt | 25 +++++++ .../complexity_exercises.py | 52 +++++++++++++++ .../chapter_divide_and_conquer/fast_power.py | 21 ++++++ .../complexity_exercises.rb | 55 ++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rb | 21 ++++++ codes/rust/Cargo.toml | 10 +++ .../complexity_exercises.rs | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rs | 23 +++++++ codes/swift/Package.swift | 4 ++ .../complexity_exercises.swift | 62 +++++++++++++++++ .../fast_power.swift | 26 ++++++++ .../complexity_exercises.ts | 65 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.ts | 23 +++++++ .../exercises.md | 43 +++--------- docs/chapter_divide_and_conquer/exercises.md | 16 ++--- .../CMakeLists.txt | 1 + .../complexity_exercises.c | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 1 + .../c/chapter_divide_and_conquer/fast_power.c | 26 ++++++++ .../CMakeLists.txt | 3 +- .../complexity_exercises.cpp | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 3 +- .../chapter_divide_and_conquer/fast_power.cpp | 26 ++++++++ .../complexity_exercises.cs | 66 +++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.cs | 28 ++++++++ .../complexity_exercises.dart | 63 ++++++++++++++++++ .../fast_power.dart | 23 +++++++ .../complexity_exercises.go | 50 ++++++++++++++ .../complexity_exercises_test.go | 22 +++++++ .../chapter_divide_and_conquer/fast_power.go | 17 +++++ .../fast_power_test.go | 13 ++++ .../complexity_exercises.java | 62 +++++++++++++++++ .../fast_power.java | 27 ++++++++ .../complexity_exercises.js | 63 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.js | 21 ++++++ .../complexity_exercises.kt | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.kt | 25 +++++++ .../complexity_exercises.py | 52 +++++++++++++++ .../chapter_divide_and_conquer/fast_power.py | 21 ++++++ .../complexity_exercises.rb | 55 ++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rb | 21 ++++++ en/codes/rust/Cargo.toml | 10 +++ .../complexity_exercises.rs | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rs | 23 +++++++ en/codes/swift/Package.swift | 4 ++ .../complexity_exercises.swift | 62 +++++++++++++++++ .../fast_power.swift | 26 ++++++++ .../complexity_exercises.ts | 65 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.ts | 23 +++++++ .../exercises.md | 43 +++--------- .../chapter_divide_and_conquer/exercises.md | 16 ++--- .../CMakeLists.txt | 1 + .../complexity_exercises.c | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 1 + .../c/chapter_divide_and_conquer/fast_power.c | 26 ++++++++ .../CMakeLists.txt | 3 +- .../complexity_exercises.cpp | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 3 +- .../chapter_divide_and_conquer/fast_power.cpp | 26 ++++++++ .../complexity_exercises.cs | 66 +++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.cs | 28 ++++++++ .../complexity_exercises.dart | 63 ++++++++++++++++++ .../fast_power.dart | 23 +++++++ .../complexity_exercises.go | 50 ++++++++++++++ .../complexity_exercises_test.go | 22 +++++++ .../chapter_divide_and_conquer/fast_power.go | 17 +++++ .../fast_power_test.go | 13 ++++ .../complexity_exercises.java | 62 +++++++++++++++++ .../fast_power.java | 27 ++++++++ .../complexity_exercises.js | 63 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.js | 21 ++++++ .../complexity_exercises.kt | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.kt | 25 +++++++ .../complexity_exercises.py | 52 +++++++++++++++ .../chapter_divide_and_conquer/fast_power.py | 21 ++++++ .../complexity_exercises.rb | 55 ++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rb | 21 ++++++ ja/codes/rust/Cargo.toml | 10 +++ .../complexity_exercises.rs | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rs | 23 +++++++ ja/codes/swift/Package.swift | 4 ++ .../complexity_exercises.swift | 62 +++++++++++++++++ .../fast_power.swift | 26 ++++++++ .../complexity_exercises.ts | 65 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.ts | 23 +++++++ .../exercises.md | 43 +++--------- .../chapter_divide_and_conquer/exercises.md | 16 ++--- .../CMakeLists.txt | 1 + .../complexity_exercises.c | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 1 + .../c/chapter_divide_and_conquer/fast_power.c | 26 ++++++++ .../CMakeLists.txt | 3 +- .../complexity_exercises.cpp | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 3 +- .../chapter_divide_and_conquer/fast_power.cpp | 26 ++++++++ .../complexity_exercises.cs | 66 +++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.cs | 28 ++++++++ .../complexity_exercises.dart | 63 ++++++++++++++++++ .../fast_power.dart | 23 +++++++ .../complexity_exercises.go | 50 ++++++++++++++ .../complexity_exercises_test.go | 22 +++++++ .../chapter_divide_and_conquer/fast_power.go | 17 +++++ .../fast_power_test.go | 13 ++++ .../complexity_exercises.java | 62 +++++++++++++++++ .../fast_power.java | 27 ++++++++ .../complexity_exercises.js | 63 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.js | 21 ++++++ .../complexity_exercises.kt | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.kt | 25 +++++++ .../complexity_exercises.py | 52 +++++++++++++++ .../chapter_divide_and_conquer/fast_power.py | 21 ++++++ .../complexity_exercises.rb | 55 ++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rb | 21 ++++++ ru/codes/rust/Cargo.toml | 10 +++ .../complexity_exercises.rs | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rs | 23 +++++++ ru/codes/swift/Package.swift | 4 ++ .../complexity_exercises.swift | 62 +++++++++++++++++ .../fast_power.swift | 26 ++++++++ .../complexity_exercises.ts | 65 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.ts | 23 +++++++ .../exercises.md | 43 +++--------- .../chapter_divide_and_conquer/exercises.md | 16 ++--- .../CMakeLists.txt | 1 + .../complexity_exercises.c | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 1 + .../c/chapter_divide_and_conquer/fast_power.c | 26 ++++++++ .../CMakeLists.txt | 3 +- .../complexity_exercises.cpp | 61 +++++++++++++++++ .../chapter_divide_and_conquer/CMakeLists.txt | 3 +- .../chapter_divide_and_conquer/fast_power.cpp | 26 ++++++++ .../complexity_exercises.cs | 66 +++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.cs | 28 ++++++++ .../complexity_exercises.dart | 63 ++++++++++++++++++ .../fast_power.dart | 23 +++++++ .../complexity_exercises.go | 50 ++++++++++++++ .../complexity_exercises_test.go | 22 +++++++ .../chapter_divide_and_conquer/fast_power.go | 17 +++++ .../fast_power_test.go | 13 ++++ .../complexity_exercises.java | 62 +++++++++++++++++ .../fast_power.java | 27 ++++++++ .../complexity_exercises.js | 63 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.js | 21 ++++++ .../complexity_exercises.kt | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.kt | 25 +++++++ .../complexity_exercises.py | 52 +++++++++++++++ .../chapter_divide_and_conquer/fast_power.py | 21 ++++++ .../complexity_exercises.rb | 55 ++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rb | 21 ++++++ zh-hant/codes/rust/Cargo.toml | 10 +++ .../complexity_exercises.rs | 61 +++++++++++++++++ .../chapter_divide_and_conquer/fast_power.rs | 23 +++++++ zh-hant/codes/swift/Package.swift | 4 ++ .../complexity_exercises.swift | 62 +++++++++++++++++ .../fast_power.swift | 26 ++++++++ .../complexity_exercises.ts | 65 ++++++++++++++++++ .../chapter_divide_and_conquer/fast_power.ts | 23 +++++++ .../exercises.md | 43 +++--------- .../chapter_divide_and_conquer/exercises.md | 16 ++--- 180 files changed, 5795 insertions(+), 230 deletions(-) create mode 100644 codes/c/chapter_computational_complexity/complexity_exercises.c create mode 100644 codes/c/chapter_divide_and_conquer/fast_power.c create mode 100644 codes/cpp/chapter_computational_complexity/complexity_exercises.cpp create mode 100644 codes/cpp/chapter_divide_and_conquer/fast_power.cpp create mode 100644 codes/csharp/chapter_computational_complexity/complexity_exercises.cs create mode 100644 codes/csharp/chapter_divide_and_conquer/fast_power.cs create mode 100644 codes/dart/chapter_computational_complexity/complexity_exercises.dart create mode 100644 codes/dart/chapter_divide_and_conquer/fast_power.dart create mode 100644 codes/go/chapter_computational_complexity/complexity_exercises.go create mode 100644 codes/go/chapter_computational_complexity/complexity_exercises_test.go create mode 100644 codes/go/chapter_divide_and_conquer/fast_power.go create mode 100644 codes/go/chapter_divide_and_conquer/fast_power_test.go create mode 100644 codes/java/chapter_computational_complexity/complexity_exercises.java create mode 100644 codes/java/chapter_divide_and_conquer/fast_power.java create mode 100644 codes/javascript/chapter_computational_complexity/complexity_exercises.js create mode 100644 codes/javascript/chapter_divide_and_conquer/fast_power.js create mode 100644 codes/kotlin/chapter_computational_complexity/complexity_exercises.kt create mode 100644 codes/kotlin/chapter_divide_and_conquer/fast_power.kt create mode 100644 codes/python/chapter_computational_complexity/complexity_exercises.py create mode 100644 codes/python/chapter_divide_and_conquer/fast_power.py create mode 100644 codes/ruby/chapter_computational_complexity/complexity_exercises.rb create mode 100644 codes/ruby/chapter_divide_and_conquer/fast_power.rb create mode 100644 codes/rust/chapter_computational_complexity/complexity_exercises.rs create mode 100644 codes/rust/chapter_divide_and_conquer/fast_power.rs create mode 100644 codes/swift/chapter_computational_complexity/complexity_exercises.swift create mode 100644 codes/swift/chapter_divide_and_conquer/fast_power.swift create mode 100644 codes/typescript/chapter_computational_complexity/complexity_exercises.ts create mode 100644 codes/typescript/chapter_divide_and_conquer/fast_power.ts create mode 100644 en/codes/c/chapter_computational_complexity/complexity_exercises.c create mode 100644 en/codes/c/chapter_divide_and_conquer/fast_power.c create mode 100644 en/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp create mode 100644 en/codes/cpp/chapter_divide_and_conquer/fast_power.cpp create mode 100644 en/codes/csharp/chapter_computational_complexity/complexity_exercises.cs create mode 100644 en/codes/csharp/chapter_divide_and_conquer/fast_power.cs create mode 100644 en/codes/dart/chapter_computational_complexity/complexity_exercises.dart create mode 100644 en/codes/dart/chapter_divide_and_conquer/fast_power.dart create mode 100644 en/codes/go/chapter_computational_complexity/complexity_exercises.go create mode 100644 en/codes/go/chapter_computational_complexity/complexity_exercises_test.go create mode 100644 en/codes/go/chapter_divide_and_conquer/fast_power.go create mode 100644 en/codes/go/chapter_divide_and_conquer/fast_power_test.go create mode 100644 en/codes/java/chapter_computational_complexity/complexity_exercises.java create mode 100644 en/codes/java/chapter_divide_and_conquer/fast_power.java create mode 100644 en/codes/javascript/chapter_computational_complexity/complexity_exercises.js create mode 100644 en/codes/javascript/chapter_divide_and_conquer/fast_power.js create mode 100644 en/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt create mode 100644 en/codes/kotlin/chapter_divide_and_conquer/fast_power.kt create mode 100644 en/codes/python/chapter_computational_complexity/complexity_exercises.py create mode 100644 en/codes/python/chapter_divide_and_conquer/fast_power.py create mode 100644 en/codes/ruby/chapter_computational_complexity/complexity_exercises.rb create mode 100644 en/codes/ruby/chapter_divide_and_conquer/fast_power.rb create mode 100644 en/codes/rust/chapter_computational_complexity/complexity_exercises.rs create mode 100644 en/codes/rust/chapter_divide_and_conquer/fast_power.rs create mode 100644 en/codes/swift/chapter_computational_complexity/complexity_exercises.swift create mode 100644 en/codes/swift/chapter_divide_and_conquer/fast_power.swift create mode 100644 en/codes/typescript/chapter_computational_complexity/complexity_exercises.ts create mode 100644 en/codes/typescript/chapter_divide_and_conquer/fast_power.ts create mode 100644 ja/codes/c/chapter_computational_complexity/complexity_exercises.c create mode 100644 ja/codes/c/chapter_divide_and_conquer/fast_power.c create mode 100644 ja/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp create mode 100644 ja/codes/cpp/chapter_divide_and_conquer/fast_power.cpp create mode 100644 ja/codes/csharp/chapter_computational_complexity/complexity_exercises.cs create mode 100644 ja/codes/csharp/chapter_divide_and_conquer/fast_power.cs create mode 100644 ja/codes/dart/chapter_computational_complexity/complexity_exercises.dart create mode 100644 ja/codes/dart/chapter_divide_and_conquer/fast_power.dart create mode 100644 ja/codes/go/chapter_computational_complexity/complexity_exercises.go create mode 100644 ja/codes/go/chapter_computational_complexity/complexity_exercises_test.go create mode 100644 ja/codes/go/chapter_divide_and_conquer/fast_power.go create mode 100644 ja/codes/go/chapter_divide_and_conquer/fast_power_test.go create mode 100644 ja/codes/java/chapter_computational_complexity/complexity_exercises.java create mode 100644 ja/codes/java/chapter_divide_and_conquer/fast_power.java create mode 100644 ja/codes/javascript/chapter_computational_complexity/complexity_exercises.js create mode 100644 ja/codes/javascript/chapter_divide_and_conquer/fast_power.js create mode 100644 ja/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt create mode 100644 ja/codes/kotlin/chapter_divide_and_conquer/fast_power.kt create mode 100644 ja/codes/python/chapter_computational_complexity/complexity_exercises.py create mode 100644 ja/codes/python/chapter_divide_and_conquer/fast_power.py create mode 100644 ja/codes/ruby/chapter_computational_complexity/complexity_exercises.rb create mode 100644 ja/codes/ruby/chapter_divide_and_conquer/fast_power.rb create mode 100644 ja/codes/rust/chapter_computational_complexity/complexity_exercises.rs create mode 100644 ja/codes/rust/chapter_divide_and_conquer/fast_power.rs create mode 100644 ja/codes/swift/chapter_computational_complexity/complexity_exercises.swift create mode 100644 ja/codes/swift/chapter_divide_and_conquer/fast_power.swift create mode 100644 ja/codes/typescript/chapter_computational_complexity/complexity_exercises.ts create mode 100644 ja/codes/typescript/chapter_divide_and_conquer/fast_power.ts create mode 100644 ru/codes/c/chapter_computational_complexity/complexity_exercises.c create mode 100644 ru/codes/c/chapter_divide_and_conquer/fast_power.c create mode 100644 ru/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp create mode 100644 ru/codes/cpp/chapter_divide_and_conquer/fast_power.cpp create mode 100644 ru/codes/csharp/chapter_computational_complexity/complexity_exercises.cs create mode 100644 ru/codes/csharp/chapter_divide_and_conquer/fast_power.cs create mode 100644 ru/codes/dart/chapter_computational_complexity/complexity_exercises.dart create mode 100644 ru/codes/dart/chapter_divide_and_conquer/fast_power.dart create mode 100644 ru/codes/go/chapter_computational_complexity/complexity_exercises.go create mode 100644 ru/codes/go/chapter_computational_complexity/complexity_exercises_test.go create mode 100644 ru/codes/go/chapter_divide_and_conquer/fast_power.go create mode 100644 ru/codes/go/chapter_divide_and_conquer/fast_power_test.go create mode 100644 ru/codes/java/chapter_computational_complexity/complexity_exercises.java create mode 100644 ru/codes/java/chapter_divide_and_conquer/fast_power.java create mode 100644 ru/codes/javascript/chapter_computational_complexity/complexity_exercises.js create mode 100644 ru/codes/javascript/chapter_divide_and_conquer/fast_power.js create mode 100644 ru/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt create mode 100644 ru/codes/kotlin/chapter_divide_and_conquer/fast_power.kt create mode 100644 ru/codes/python/chapter_computational_complexity/complexity_exercises.py create mode 100644 ru/codes/python/chapter_divide_and_conquer/fast_power.py create mode 100644 ru/codes/ruby/chapter_computational_complexity/complexity_exercises.rb create mode 100644 ru/codes/ruby/chapter_divide_and_conquer/fast_power.rb create mode 100644 ru/codes/rust/chapter_computational_complexity/complexity_exercises.rs create mode 100644 ru/codes/rust/chapter_divide_and_conquer/fast_power.rs create mode 100644 ru/codes/swift/chapter_computational_complexity/complexity_exercises.swift create mode 100644 ru/codes/swift/chapter_divide_and_conquer/fast_power.swift create mode 100644 ru/codes/typescript/chapter_computational_complexity/complexity_exercises.ts create mode 100644 ru/codes/typescript/chapter_divide_and_conquer/fast_power.ts create mode 100644 zh-hant/codes/c/chapter_computational_complexity/complexity_exercises.c create mode 100644 zh-hant/codes/c/chapter_divide_and_conquer/fast_power.c create mode 100644 zh-hant/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp create mode 100644 zh-hant/codes/cpp/chapter_divide_and_conquer/fast_power.cpp create mode 100644 zh-hant/codes/csharp/chapter_computational_complexity/complexity_exercises.cs create mode 100644 zh-hant/codes/csharp/chapter_divide_and_conquer/fast_power.cs create mode 100644 zh-hant/codes/dart/chapter_computational_complexity/complexity_exercises.dart create mode 100644 zh-hant/codes/dart/chapter_divide_and_conquer/fast_power.dart create mode 100644 zh-hant/codes/go/chapter_computational_complexity/complexity_exercises.go create mode 100644 zh-hant/codes/go/chapter_computational_complexity/complexity_exercises_test.go create mode 100644 zh-hant/codes/go/chapter_divide_and_conquer/fast_power.go create mode 100644 zh-hant/codes/go/chapter_divide_and_conquer/fast_power_test.go create mode 100644 zh-hant/codes/java/chapter_computational_complexity/complexity_exercises.java create mode 100644 zh-hant/codes/java/chapter_divide_and_conquer/fast_power.java create mode 100644 zh-hant/codes/javascript/chapter_computational_complexity/complexity_exercises.js create mode 100644 zh-hant/codes/javascript/chapter_divide_and_conquer/fast_power.js create mode 100644 zh-hant/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt create mode 100644 zh-hant/codes/kotlin/chapter_divide_and_conquer/fast_power.kt create mode 100644 zh-hant/codes/python/chapter_computational_complexity/complexity_exercises.py create mode 100644 zh-hant/codes/python/chapter_divide_and_conquer/fast_power.py create mode 100644 zh-hant/codes/ruby/chapter_computational_complexity/complexity_exercises.rb create mode 100644 zh-hant/codes/ruby/chapter_divide_and_conquer/fast_power.rb create mode 100644 zh-hant/codes/rust/chapter_computational_complexity/complexity_exercises.rs create mode 100644 zh-hant/codes/rust/chapter_divide_and_conquer/fast_power.rs create mode 100644 zh-hant/codes/swift/chapter_computational_complexity/complexity_exercises.swift create mode 100644 zh-hant/codes/swift/chapter_divide_and_conquer/fast_power.swift create mode 100644 zh-hant/codes/typescript/chapter_computational_complexity/complexity_exercises.ts create mode 100644 zh-hant/codes/typescript/chapter_divide_and_conquer/fast_power.ts diff --git a/codes/c/chapter_computational_complexity/CMakeLists.txt b/codes/c/chapter_computational_complexity/CMakeLists.txt index dcfa063c3..3d2450c26 100644 --- a/codes/c/chapter_computational_complexity/CMakeLists.txt +++ b/codes/c/chapter_computational_complexity/CMakeLists.txt @@ -3,3 +3,4 @@ add_executable(recursion recursion.c) add_executable(time_complexity time_complexity.c) add_executable(worst_best_time_complexity worst_best_time_complexity.c) add_executable(space_complexity space_complexity.c) +add_executable(complexity_exercises complexity_exercises.c) diff --git a/codes/c/chapter_computational_complexity/complexity_exercises.c b/codes/c/chapter_computational_complexity/complexity_exercises.c new file mode 100644 index 000000000..b8ad4f37b --- /dev/null +++ b/codes/c/chapter_computational_complexity/complexity_exercises.c @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 迭代求和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 递归求和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 线性阶循环 */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 平方阶循环 */ +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; +} + +/* 对数阶循环 */ +int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; +} + +int main(void) { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/codes/c/chapter_divide_and_conquer/CMakeLists.txt b/codes/c/chapter_divide_and_conquer/CMakeLists.txt index e03b1c588..31352a138 100644 --- a/codes/c/chapter_divide_and_conquer/CMakeLists.txt +++ b/codes/c/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.c) add_executable(build_tree build_tree.c) add_executable(hanota hanota.c) +add_executable(fast_power fast_power.c) diff --git a/codes/c/chapter_divide_and_conquer/fast_power.c b/codes/c/chapter_divide_and_conquer/fast_power.c new file mode 100644 index 000000000..68338d33f --- /dev/null +++ b/codes/c/chapter_divide_and_conquer/fast_power.c @@ -0,0 +1,26 @@ +/** + * File: fast_power.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 快速幂 */ +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; +} + +int main(void) { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/codes/cpp/chapter_computational_complexity/CMakeLists.txt b/codes/cpp/chapter_computational_complexity/CMakeLists.txt index ea2845b75..536935b68 100644 --- a/codes/cpp/chapter_computational_complexity/CMakeLists.txt +++ b/codes/cpp/chapter_computational_complexity/CMakeLists.txt @@ -2,4 +2,5 @@ add_executable(iteration iteration.cpp) add_executable(recursion recursion.cpp) add_executable(space_complexity space_complexity.cpp) add_executable(time_complexity time_complexity.cpp) -add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) \ No newline at end of file +add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) +add_executable(complexity_exercises complexity_exercises.cpp) diff --git a/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp b/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp new file mode 100644 index 000000000..70307f001 --- /dev/null +++ b/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 迭代求和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; ++i) { + res += i; + } + return res; +} + +/* 递归求和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 线性阶循环 */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; ++i) { + res += i; + } + return res; +} + +/* 平方阶循环 */ +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; +} + +/* 对数阶循环 */ +int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; +} + +int main() { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt b/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt index 38dfff710..8e66f77b5 100644 --- a/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt +++ b/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.cpp) add_executable(build_tree build_tree.cpp) -add_executable(hanota hanota.cpp) \ No newline at end of file +add_executable(hanota hanota.cpp) +add_executable(fast_power fast_power.cpp) diff --git a/codes/cpp/chapter_divide_and_conquer/fast_power.cpp b/codes/cpp/chapter_divide_and_conquer/fast_power.cpp new file mode 100644 index 000000000..f00ac162c --- /dev/null +++ b/codes/cpp/chapter_divide_and_conquer/fast_power.cpp @@ -0,0 +1,26 @@ +/** + * File: fast_power.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 快速幂 */ +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; +} + +int main() { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/codes/csharp/chapter_computational_complexity/complexity_exercises.cs b/codes/csharp/chapter_computational_complexity/complexity_exercises.cs new file mode 100644 index 000000000..9dc14d7ad --- /dev/null +++ b/codes/csharp/chapter_computational_complexity/complexity_exercises.cs @@ -0,0 +1,66 @@ +/** + * File: complexity_exercises.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_computational_complexity; + +public class complexity_exercises { + /* 迭代求和 */ + int SumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* 递归求和 */ + int SumRecur(int n) { + if (n == 1) { + return 1; + } + return n + SumRecur(n - 1); + } + + /* 线性阶循环 */ + int LinearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* 平方阶循环 */ + 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; + } + + /* 对数阶循环 */ + int LogarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + [Test] + public void Test() { + Assert.That(SumIter(1), Is.EqualTo(1)); + Assert.That(SumRecur(1), Is.EqualTo(1)); + Assert.That(SumIter(4), Is.EqualTo(10)); + Assert.That(SumRecur(4), Is.EqualTo(10)); + Assert.That(LinearLoop(4), Is.EqualTo(6)); + Assert.That(QuadraticLoop(4), Is.EqualTo(20)); + Assert.That(LogarithmicLoop(4), Is.EqualTo(1)); + Assert.That(LogarithmicLoop(5), Is.EqualTo(1)); + } +} diff --git a/codes/csharp/chapter_divide_and_conquer/fast_power.cs b/codes/csharp/chapter_divide_and_conquer/fast_power.cs new file mode 100644 index 000000000..42eadeb01 --- /dev/null +++ b/codes/csharp/chapter_divide_and_conquer/fast_power.cs @@ -0,0 +1,28 @@ +/** + * File: fast_power.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_divide_and_conquer; + +public class fast_power { + /* 快速幂 */ + 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; + } + + [Test] + public void Test() { + Assert.That(FastPow(7, 0), Is.EqualTo(1)); + Assert.That(FastPow(3, 5), Is.EqualTo(243)); + Assert.That(FastPow(2, 6), Is.EqualTo(64)); + } +} diff --git a/codes/dart/chapter_computational_complexity/complexity_exercises.dart b/codes/dart/chapter_computational_complexity/complexity_exercises.dart new file mode 100644 index 000000000..8363f297d --- /dev/null +++ b/codes/dart/chapter_computational_complexity/complexity_exercises.dart @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 迭代求和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 递归求和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 线性阶循环 */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 平方阶循环 */ +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; +} + +/* 对数阶循环 */ +int logarithmicLoop(int n) { + while (n > 1) { + n ~/= 2; + } + return n; +} + +void main() { + if (sumIter(1) != 1 || + sumRecur(1) != 1 || + sumIter(4) != 10 || + sumRecur(4) != 10 || + linearLoop(4) != 6 || + quadraticLoop(4) != 20 || + logarithmicLoop(4) != 1 || + logarithmicLoop(5) != 1) { + throw StateError('complexity exercise check failed'); + } +} diff --git a/codes/dart/chapter_divide_and_conquer/fast_power.dart b/codes/dart/chapter_divide_and_conquer/fast_power.dart new file mode 100644 index 000000000..806f73ecf --- /dev/null +++ b/codes/dart/chapter_divide_and_conquer/fast_power.dart @@ -0,0 +1,23 @@ +/** + * File: fast_power.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 快速幂 */ +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; +} + +void main() { + if (fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64) { + throw StateError('fast power check failed'); + } +} diff --git a/codes/go/chapter_computational_complexity/complexity_exercises.go b/codes/go/chapter_computational_complexity/complexity_exercises.go new file mode 100644 index 000000000..3ea50a835 --- /dev/null +++ b/codes/go/chapter_computational_complexity/complexity_exercises.go @@ -0,0 +1,50 @@ +// File: complexity_exercises.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +/* 迭代求和 */ +func sumIter(n int) int { + res := 0 + for i := 1; i <= n; i++ { + res += i + } + return res +} + +/* 递归求和 */ +func sumRecur(n int) int { + if n == 1 { + return 1 + } + return n + sumRecur(n-1) +} + +/* 线性阶循环 */ +func linearLoop(n int) int { + res := 0 + for i := 0; i < n; i++ { + res += i + } + return res +} + +/* 平方阶循环 */ +func quadraticLoop(n int) int { + res := 0 + for i := 0; i < n; i++ { + for j := i; j < n; j++ { + res += j + } + } + return res +} + +/* 对数阶循环 */ +func logarithmicLoop(n int) int { + for n > 1 { + n /= 2 + } + return n +} diff --git a/codes/go/chapter_computational_complexity/complexity_exercises_test.go b/codes/go/chapter_computational_complexity/complexity_exercises_test.go new file mode 100644 index 000000000..5e07da9bc --- /dev/null +++ b/codes/go/chapter_computational_complexity/complexity_exercises_test.go @@ -0,0 +1,22 @@ +// File: complexity_exercises_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +import "testing" + +func TestComplexityExercises(t *testing.T) { + if sumIter(1) != 1 || sumRecur(1) != 1 { + t.Fatal("sum functions failed for n = 1") + } + if sumIter(4) != 10 || sumRecur(4) != 10 { + t.Fatal("sum functions failed for n = 4") + } + if linearLoop(4) != 6 || quadraticLoop(4) != 20 { + t.Fatal("complexity loops returned an unexpected value") + } + if logarithmicLoop(4) != 1 || logarithmicLoop(5) != 1 { + t.Fatal("logarithmic loop returned an unexpected value") + } +} diff --git a/codes/go/chapter_divide_and_conquer/fast_power.go b/codes/go/chapter_divide_and_conquer/fast_power.go new file mode 100644 index 000000000..5c4aa5bfd --- /dev/null +++ b/codes/go/chapter_divide_and_conquer/fast_power.go @@ -0,0 +1,17 @@ +// File: fast_power.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +/* 快速幂 */ +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 +} diff --git a/codes/go/chapter_divide_and_conquer/fast_power_test.go b/codes/go/chapter_divide_and_conquer/fast_power_test.go new file mode 100644 index 000000000..38318718b --- /dev/null +++ b/codes/go/chapter_divide_and_conquer/fast_power_test.go @@ -0,0 +1,13 @@ +// File: fast_power_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +import "testing" + +func TestFastPower(t *testing.T) { + if fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64 { + t.Fatal("fast power returned an unexpected value") + } +} diff --git a/codes/java/chapter_computational_complexity/complexity_exercises.java b/codes/java/chapter_computational_complexity/complexity_exercises.java new file mode 100644 index 000000000..cf104561d --- /dev/null +++ b/codes/java/chapter_computational_complexity/complexity_exercises.java @@ -0,0 +1,62 @@ +/** + * File: complexity_exercises.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity; + +public class complexity_exercises { + /* 迭代求和 */ + static int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* 递归求和 */ + static int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); + } + + /* 线性阶循环 */ + static int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* 平方阶循环 */ + static 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; + } + + /* 对数阶循环 */ + static int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + public static void main(String[] args) { + assert sumIter(1) == 1 && sumRecur(1) == 1; + assert sumIter(4) == 10 && sumRecur(4) == 10; + assert linearLoop(4) == 6; + assert quadraticLoop(4) == 20; + assert logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1; + } +} diff --git a/codes/java/chapter_divide_and_conquer/fast_power.java b/codes/java/chapter_divide_and_conquer/fast_power.java new file mode 100644 index 000000000..b8e4e82be --- /dev/null +++ b/codes/java/chapter_divide_and_conquer/fast_power.java @@ -0,0 +1,27 @@ +/** + * File: fast_power.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer; + +public class fast_power { + /* 快速幂 */ + static 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; + } + + public static void main(String[] args) { + assert fastPow(7, 0) == 1; + assert fastPow(3, 5) == 243; + assert fastPow(2, 6) == 64; + } +} diff --git a/codes/javascript/chapter_computational_complexity/complexity_exercises.js b/codes/javascript/chapter_computational_complexity/complexity_exercises.js new file mode 100644 index 000000000..e95797c7a --- /dev/null +++ b/codes/javascript/chapter_computational_complexity/complexity_exercises.js @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 迭代求和 */ +function sumIter(n) { + let res = 0; + for (let i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 递归求和 */ +function sumRecur(n) { + if (n === 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 线性阶循环 */ +function linearLoop(n) { + let res = 0; + for (let i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 平方阶循环 */ +function quadraticLoop(n) { + let res = 0; + for (let i = 0; i < n; i++) { + for (let j = i; j < n; j++) { + res += j; + } + } + return res; +} + +/* 对数阶循环 */ +function logarithmicLoop(n) { + while (n > 1) { + n = Math.floor(n / 2); + } + return n; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} diff --git a/codes/javascript/chapter_divide_and_conquer/fast_power.js b/codes/javascript/chapter_divide_and_conquer/fast_power.js new file mode 100644 index 000000000..19bed9332 --- /dev/null +++ b/codes/javascript/chapter_divide_and_conquer/fast_power.js @@ -0,0 +1,21 @@ +/** + * File: fast_power.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 快速幂 */ +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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} diff --git a/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt b/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt new file mode 100644 index 000000000..ffcf05bc8 --- /dev/null +++ b/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity.complexity_exercises + +/* 迭代求和 */ +fun sumIter(n: Int): Int { + var res = 0 + for (i in 1..n) { + res += i + } + return res +} + +/* 递归求和 */ +fun sumRecur(n: Int): Int { + if (n == 1) { + return 1 + } + return n + sumRecur(n - 1) +} + +/* 线性阶循环 */ +fun linearLoop(n: Int): Int { + var res = 0 + for (i in 0 until n) { + res += i + } + return res +} + +/* 平方阶循环 */ +fun quadraticLoop(n: Int): Int { + var res = 0 + for (i in 0 until n) { + for (j in i until n) { + res += j + } + } + return res +} + +/* 对数阶循环 */ +fun logarithmicLoop(n: Int): Int { + var value = n + while (value > 1) { + value /= 2 + } + return value +} + +fun main() { + check(sumIter(1) == 1 && sumRecur(1) == 1) + check(sumIter(4) == 10 && sumRecur(4) == 10) + check(linearLoop(4) == 6) + check(quadraticLoop(4) == 20) + check(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1) +} diff --git a/codes/kotlin/chapter_divide_and_conquer/fast_power.kt b/codes/kotlin/chapter_divide_and_conquer/fast_power.kt new file mode 100644 index 000000000..81a89116b --- /dev/null +++ b/codes/kotlin/chapter_divide_and_conquer/fast_power.kt @@ -0,0 +1,25 @@ +/** + * File: fast_power.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer.fast_power + +/* 快速幂 */ +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 +} + +fun main() { + check(fastPow(7, 0) == 1) + check(fastPow(3, 5) == 243) + check(fastPow(2, 6) == 64) +} diff --git a/codes/python/chapter_computational_complexity/complexity_exercises.py b/codes/python/chapter_computational_complexity/complexity_exercises.py new file mode 100644 index 000000000..c2d0d1cb7 --- /dev/null +++ b/codes/python/chapter_computational_complexity/complexity_exercises.py @@ -0,0 +1,52 @@ +""" +File: complexity_exercises.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +def sum_iter(n: int) -> int: + """迭代求和""" + res = 0 + for i in range(1, n + 1): + res += i + return res + + +def sum_recur(n: int) -> int: + """递归求和""" + if n == 1: + return 1 + return n + sum_recur(n - 1) + + +def linear_loop(n: int) -> int: + """线性阶循环""" + res = 0 + for i in range(n): + res += i + return res + + +def quadratic_loop(n: int) -> int: + """平方阶循环""" + res = 0 + for i in range(n): + for j in range(i, n): + res += j + return res + + +def logarithmic_loop(n: int) -> int: + """对数阶循环""" + while n > 1: + n //= 2 + return n + + +if __name__ == "__main__": + assert sum_iter(1) == sum_recur(1) == 1 + assert sum_iter(4) == sum_recur(4) == 10 + assert linear_loop(4) == 6 + assert quadratic_loop(4) == 20 + assert logarithmic_loop(4) == logarithmic_loop(5) == 1 diff --git a/codes/python/chapter_divide_and_conquer/fast_power.py b/codes/python/chapter_divide_and_conquer/fast_power.py new file mode 100644 index 000000000..c983a15c1 --- /dev/null +++ b/codes/python/chapter_divide_and_conquer/fast_power.py @@ -0,0 +1,21 @@ +""" +File: fast_power.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +def fast_pow(x: int, n: int) -> int: + """快速幂""" + if n == 0: + return 1 + half = fast_pow(x, n // 2) + if n % 2 == 0: + return half * half + return half * half * x + + +if __name__ == "__main__": + assert fast_pow(7, 0) == 1 + assert fast_pow(3, 5) == 243 + assert fast_pow(2, 6) == 64 diff --git a/codes/ruby/chapter_computational_complexity/complexity_exercises.rb b/codes/ruby/chapter_computational_complexity/complexity_exercises.rb new file mode 100644 index 000000000..69e66c5f2 --- /dev/null +++ b/codes/ruby/chapter_computational_complexity/complexity_exercises.rb @@ -0,0 +1,55 @@ +=begin +File: complexity_exercises.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### 迭代求和 ### +def sum_iter(n) + res = 0 + for i in 1..n + res += i + end + res +end + +### 递归求和 ### +def sum_recur(n) + return 1 if n == 1 + + n + sum_recur(n - 1) +end + +### 线性阶循环 ### +def linear_loop(n) + res = 0 + for i in 0...n + res += i + end + res +end + +### 平方阶循环 ### +def quadratic_loop(n) + res = 0 + for i in 0...n + for j in i...n + res += j + end + end + res +end + +### 对数阶循环 ### +def logarithmic_loop(n) + n /= 2 while n > 1 + n +end + +if __FILE__ == $0 + raise 'sum check failed' unless sum_iter(1) == 1 && sum_recur(1) == 1 + raise 'sum check failed' unless sum_iter(4) == 10 && sum_recur(4) == 10 + raise 'linear check failed' unless linear_loop(4) == 6 + raise 'quadratic check failed' unless quadratic_loop(4) == 20 + raise 'logarithmic check failed' unless logarithmic_loop(4) == 1 && logarithmic_loop(5) == 1 +end diff --git a/codes/ruby/chapter_divide_and_conquer/fast_power.rb b/codes/ruby/chapter_divide_and_conquer/fast_power.rb new file mode 100644 index 000000000..0b5d63a05 --- /dev/null +++ b/codes/ruby/chapter_divide_and_conquer/fast_power.rb @@ -0,0 +1,21 @@ +=begin +File: fast_power.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### 快速幂 ### +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 + +if __FILE__ == $0 + raise 'fast power check failed' unless fast_pow(7, 0) == 1 + raise 'fast power check failed' unless fast_pow(3, 5) == 243 + raise 'fast power check failed' unless fast_pow(2, 6) == 64 +end diff --git a/codes/rust/Cargo.toml b/codes/rust/Cargo.toml index 160f9134c..147947168 100644 --- a/codes/rust/Cargo.toml +++ b/codes/rust/Cargo.toml @@ -4,6 +4,16 @@ version = "0.1.0" edition = "2021" publish = false +# Run Command: cargo run --bin complexity_exercises +[[bin]] +name = "complexity_exercises" +path = "chapter_computational_complexity/complexity_exercises.rs" + +# Run Command: cargo run --bin fast_power +[[bin]] +name = "fast_power" +path = "chapter_divide_and_conquer/fast_power.rs" + # Run Command: cargo run --bin time_complexity [[bin]] name = "time_complexity" diff --git a/codes/rust/chapter_computational_complexity/complexity_exercises.rs b/codes/rust/chapter_computational_complexity/complexity_exercises.rs new file mode 100644 index 000000000..e62bfa288 --- /dev/null +++ b/codes/rust/chapter_computational_complexity/complexity_exercises.rs @@ -0,0 +1,61 @@ +/* + * File: complexity_exercises.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 迭代求和 */ +fn sum_iter(n: i32) -> i32 { + let mut res = 0; + for i in 1..=n { + res += i; + } + res +} + +/* 递归求和 */ +fn sum_recur(n: i32) -> i32 { + if n == 1 { + return 1; + } + n + sum_recur(n - 1) +} + +/* 线性阶循环 */ +fn linear_loop(n: i32) -> i32 { + let mut res = 0; + for i in 0..n { + res += i; + } + res +} + +/* 平方阶循环 */ +fn quadratic_loop(n: i32) -> i32 { + let mut res = 0; + for i in 0..n { + for j in i..n { + res += j; + } + } + res +} + +/* 对数阶循环 */ +fn logarithmic_loop(mut n: i32) -> i32 { + while n > 1 { + n /= 2; + } + n +} + +fn main() { + assert_eq!(sum_iter(1), 1); + assert_eq!(sum_recur(1), 1); + assert_eq!(sum_iter(4), 10); + assert_eq!(sum_recur(4), 10); + assert_eq!(linear_loop(4), 6); + assert_eq!(quadratic_loop(4), 20); + assert_eq!(logarithmic_loop(4), 1); + assert_eq!(logarithmic_loop(5), 1); +} diff --git a/codes/rust/chapter_divide_and_conquer/fast_power.rs b/codes/rust/chapter_divide_and_conquer/fast_power.rs new file mode 100644 index 000000000..7181e28bd --- /dev/null +++ b/codes/rust/chapter_divide_and_conquer/fast_power.rs @@ -0,0 +1,23 @@ +/* + * File: fast_power.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 快速幂 */ +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 +} + +fn main() { + assert_eq!(fast_pow(7, 0), 1); + assert_eq!(fast_pow(3, 5), 243); + assert_eq!(fast_pow(2, 6), 64); +} diff --git a/codes/swift/Package.swift b/codes/swift/Package.swift index 5326dc138..8ccb78ab8 100644 --- a/codes/swift/Package.swift +++ b/codes/swift/Package.swift @@ -11,6 +11,7 @@ let package = Package( .executable(name: "time_complexity", targets: ["time_complexity"]), .executable(name: "worst_best_time_complexity", targets: ["worst_best_time_complexity"]), .executable(name: "space_complexity", targets: ["space_complexity"]), + .executable(name: "complexity_exercises", targets: ["complexity_exercises"]), // chapter_array_and_linkedlist .executable(name: "array", targets: ["array"]), .executable(name: "linked_list", targets: ["linked_list"]), @@ -70,6 +71,7 @@ let package = Package( .executable(name: "binary_search_recur", targets: ["binary_search_recur"]), .executable(name: "build_tree", targets: ["build_tree"]), .executable(name: "hanota", targets: ["hanota"]), + .executable(name: "fast_power", targets: ["fast_power"]), // chapter_backtracking .executable(name: "preorder_traversal_i_compact", targets: ["preorder_traversal_i_compact"]), .executable(name: "preorder_traversal_ii_compact", targets: ["preorder_traversal_ii_compact"]), @@ -114,6 +116,7 @@ let package = Package( .executableTarget(name: "time_complexity", path: "chapter_computational_complexity", sources: ["time_complexity.swift"]), .executableTarget(name: "worst_best_time_complexity", path: "chapter_computational_complexity", sources: ["worst_best_time_complexity.swift"]), .executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]), + .executableTarget(name: "complexity_exercises", path: "chapter_computational_complexity", sources: ["complexity_exercises.swift"]), // chapter_array_and_linkedlist .executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]), .executableTarget(name: "linked_list", dependencies: ["utils"], path: "chapter_array_and_linkedlist", sources: ["linked_list.swift"]), @@ -173,6 +176,7 @@ let package = Package( .executableTarget(name: "binary_search_recur", path: "chapter_divide_and_conquer", sources: ["binary_search_recur.swift"]), .executableTarget(name: "build_tree", dependencies: ["utils"], path: "chapter_divide_and_conquer", sources: ["build_tree.swift"]), .executableTarget(name: "hanota", path: "chapter_divide_and_conquer", sources: ["hanota.swift"]), + .executableTarget(name: "fast_power", path: "chapter_divide_and_conquer", sources: ["fast_power.swift"]), // chapter_backtracking .executableTarget(name: "preorder_traversal_i_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_i_compact.swift"]), .executableTarget(name: "preorder_traversal_ii_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_ii_compact.swift"]), diff --git a/codes/swift/chapter_computational_complexity/complexity_exercises.swift b/codes/swift/chapter_computational_complexity/complexity_exercises.swift new file mode 100644 index 000000000..cdee7cc3b --- /dev/null +++ b/codes/swift/chapter_computational_complexity/complexity_exercises.swift @@ -0,0 +1,62 @@ +/** + File: complexity_exercises.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* 迭代求和 */ +func sumIter(n: Int) -> Int { + var res = 0 + for i in 1 ... n { + res += i + } + return res +} + +/* 递归求和 */ +func sumRecur(n: Int) -> Int { + if n == 1 { + return 1 + } + return n + sumRecur(n: n - 1) +} + +/* 线性阶循环 */ +func linearLoop(n: Int) -> Int { + var res = 0 + for i in 0 ..< n { + res += i + } + return res +} + +/* 平方阶循环 */ +func quadraticLoop(n: Int) -> Int { + var res = 0 + for i in 0 ..< n { + for j in i ..< n { + res += j + } + } + return res +} + +/* 对数阶循环 */ +func logarithmicLoop(n: Int) -> Int { + var n = n + while n > 1 { + n /= 2 + } + return n +} + +@main +enum ComplexityExercises { + static func main() { + assert(sumIter(n: 1) == 1 && sumRecur(n: 1) == 1) + assert(sumIter(n: 4) == 10 && sumRecur(n: 4) == 10) + assert(linearLoop(n: 4) == 6) + assert(quadraticLoop(n: 4) == 20) + assert(logarithmicLoop(n: 4) == 1 && logarithmicLoop(n: 5) == 1) + } +} diff --git a/codes/swift/chapter_divide_and_conquer/fast_power.swift b/codes/swift/chapter_divide_and_conquer/fast_power.swift new file mode 100644 index 000000000..1aa3eb737 --- /dev/null +++ b/codes/swift/chapter_divide_and_conquer/fast_power.swift @@ -0,0 +1,26 @@ +/** + File: fast_power.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* 快速幂 */ +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 +} + +@main +enum FastPower { + static func main() { + assert(fastPow(x: 7, n: 0) == 1) + assert(fastPow(x: 3, n: 5) == 243) + assert(fastPow(x: 2, n: 6) == 64) + } +} diff --git a/codes/typescript/chapter_computational_complexity/complexity_exercises.ts b/codes/typescript/chapter_computational_complexity/complexity_exercises.ts new file mode 100644 index 000000000..8cce6d2fb --- /dev/null +++ b/codes/typescript/chapter_computational_complexity/complexity_exercises.ts @@ -0,0 +1,65 @@ +/** + * File: complexity_exercises.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 迭代求和 */ +function sumIter(n: number): number { + let res = 0; + for (let i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 递归求和 */ +function sumRecur(n: number): number { + if (n === 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 线性阶循环 */ +function linearLoop(n: number): number { + let res = 0; + for (let i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 平方阶循环 */ +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; +} + +/* 对数阶循环 */ +function logarithmicLoop(n: number): number { + while (n > 1) { + n = Math.floor(n / 2); + } + return n; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} + +export {}; diff --git a/codes/typescript/chapter_divide_and_conquer/fast_power.ts b/codes/typescript/chapter_divide_and_conquer/fast_power.ts new file mode 100644 index 000000000..cff2d59d6 --- /dev/null +++ b/codes/typescript/chapter_divide_and_conquer/fast_power.ts @@ -0,0 +1,23 @@ +/** + * File: fast_power.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 快速幂 */ +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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} + +export {}; diff --git a/docs/chapter_computational_complexity/exercises.md b/docs/chapter_computational_complexity/exercises.md index d51e8f531..dbf6cccdf 100644 --- a/docs/chapter_computational_complexity/exercises.md +++ b/docs/chapter_computational_complexity/exercises.md @@ -7,33 +7,23 @@ 下面两段代码都计算 $1 + 2 + \dots + n$(设 $n \ge 1$)。请把 `n` 设为 4, 按照程序实际执行的顺序回答问题,然后比较两种写法的效率。 -```python -def sum_iter(n): - s = 0 - for i in range(1, n + 1): - s += i - return s - -def sum_recur(n): - if n == 1: - return 1 - return n + sum_recur(n - 1) +```src +[file]{complexity_exercises}-[class]{}-[func]{sum_iter} ``` -1. 执行 `sum_iter(4)` 时,每轮循环结束后,变量 `s` 的值分别是多少? -2. 执行 `sum_recur(4)` 时,会依次调用哪些函数?从最深的一层开始返回时,结果怎样得到? +1. 输入 `n = 4` 执行迭代函数时,每轮循环结束后,累加变量 `res` 的值分别是多少? +2. 输入 `n = 4` 执行递归函数时,参数 `n` 会依次取哪些值?从最深的一层开始返回时,结果怎样得到? 3. 两种写法的时间复杂度和空间复杂度分别是多少?结合第 1、2 问的执行过程说明理由。 ??? success "参考答案" - 1. 循环变量 `i` 依次为 `1、2、3、4`,每轮结束后,`s` 依次变为 - `1、3、6、10`,所以 `sum_iter(4)` 返回 10。 + 1. 循环变量 `i` 依次为 `1、2、3、4`,每轮结束后,`res` 依次变为 + `1、3、6、10`,所以迭代函数返回 10。 - 2. 函数依次调用 - `sum_recur(4) → sum_recur(3) → sum_recur(2) → sum_recur(1)`。 - `sum_recur(1)` 返回 1,随后各层依次得到 `2 + 1 = 3`、`3 + 3 = 6`、`4 + 6 = 10`。 + 2. 参数 `n` 依次为 `4 → 3 → 2 → 1`。 + 最深一层返回 1,随后各层依次得到 `2 + 1 = 3`、`3 + 3 = 6`、`4 + 6 = 10`。 在最深处,4 次函数调用都尚未结束。 3. 两段代码都进行与 $n$ 成正比的循环或调用,因此时间复杂度均为 $O(n)$ 。 @@ -47,21 +37,8 @@ def sum_recur(n): 以下三个代码片段的输入均为正整数 $n$ 。请按时间复杂度从低到高排序,并写出各自的复杂度。 -```python -# 片段一 -s = 0 -for i in range(n): - s += i - -# 片段二 -s = 0 -for i in range(n): - for j in range(i, n): - s += j - -# 片段三 -while n > 1: - n = n // 2 +```src +[file]{complexity_exercises}-[class]{}-[func]{linear_loop} ``` ??? success "参考答案" diff --git a/docs/chapter_divide_and_conquer/exercises.md b/docs/chapter_divide_and_conquer/exercises.md index a65691dc2..00ef40154 100644 --- a/docs/chapter_divide_and_conquer/exercises.md +++ b/docs/chapter_divide_and_conquer/exercises.md @@ -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`,用这个函数计算: 1. 递归调用时,参数 `n` 依次变成哪些值? 2. 从最深层开始返回时,各层依次返回什么值? -3. 为什么要先保存 `half`,而不是把 `fast_pow(x, n // 2)` 写两遍? +3. 为什么要先把递归结果保存为 `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)` 在乘法两边各写一次,两次递归会计算完全相同的子问题。 + 3. 如果在乘法两边各调用一次相同的子问题,两次递归会进行完全相同的计算。 先把结果保存为 `half`,每层就只递归一次,递归深度约为 $\log n$; 调用两次会造成大量重复计算。 diff --git a/en/codes/c/chapter_computational_complexity/CMakeLists.txt b/en/codes/c/chapter_computational_complexity/CMakeLists.txt index dcfa063c3..3d2450c26 100644 --- a/en/codes/c/chapter_computational_complexity/CMakeLists.txt +++ b/en/codes/c/chapter_computational_complexity/CMakeLists.txt @@ -3,3 +3,4 @@ add_executable(recursion recursion.c) add_executable(time_complexity time_complexity.c) add_executable(worst_best_time_complexity worst_best_time_complexity.c) add_executable(space_complexity space_complexity.c) +add_executable(complexity_exercises complexity_exercises.c) diff --git a/en/codes/c/chapter_computational_complexity/complexity_exercises.c b/en/codes/c/chapter_computational_complexity/complexity_exercises.c new file mode 100644 index 000000000..fbdb69329 --- /dev/null +++ b/en/codes/c/chapter_computational_complexity/complexity_exercises.c @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 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); +} + +/* 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; +} + +int main(void) { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/en/codes/c/chapter_divide_and_conquer/CMakeLists.txt b/en/codes/c/chapter_divide_and_conquer/CMakeLists.txt index e03b1c588..31352a138 100644 --- a/en/codes/c/chapter_divide_and_conquer/CMakeLists.txt +++ b/en/codes/c/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.c) add_executable(build_tree build_tree.c) add_executable(hanota hanota.c) +add_executable(fast_power fast_power.c) diff --git a/en/codes/c/chapter_divide_and_conquer/fast_power.c b/en/codes/c/chapter_divide_and_conquer/fast_power.c new file mode 100644 index 000000000..4ed78e867 --- /dev/null +++ b/en/codes/c/chapter_divide_and_conquer/fast_power.c @@ -0,0 +1,26 @@ +/** + * File: fast_power.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 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; +} + +int main(void) { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/en/codes/cpp/chapter_computational_complexity/CMakeLists.txt b/en/codes/cpp/chapter_computational_complexity/CMakeLists.txt index ea2845b75..536935b68 100644 --- a/en/codes/cpp/chapter_computational_complexity/CMakeLists.txt +++ b/en/codes/cpp/chapter_computational_complexity/CMakeLists.txt @@ -2,4 +2,5 @@ add_executable(iteration iteration.cpp) add_executable(recursion recursion.cpp) add_executable(space_complexity space_complexity.cpp) add_executable(time_complexity time_complexity.cpp) -add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) \ No newline at end of file +add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) +add_executable(complexity_exercises complexity_exercises.cpp) diff --git a/en/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp b/en/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp new file mode 100644 index 000000000..f05f0939e --- /dev/null +++ b/en/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 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); +} + +/* 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; +} + +int main() { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/en/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt b/en/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt index 38dfff710..8e66f77b5 100644 --- a/en/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt +++ b/en/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.cpp) add_executable(build_tree build_tree.cpp) -add_executable(hanota hanota.cpp) \ No newline at end of file +add_executable(hanota hanota.cpp) +add_executable(fast_power fast_power.cpp) diff --git a/en/codes/cpp/chapter_divide_and_conquer/fast_power.cpp b/en/codes/cpp/chapter_divide_and_conquer/fast_power.cpp new file mode 100644 index 000000000..942c0dc6d --- /dev/null +++ b/en/codes/cpp/chapter_divide_and_conquer/fast_power.cpp @@ -0,0 +1,26 @@ +/** + * File: fast_power.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 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; +} + +int main() { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/en/codes/csharp/chapter_computational_complexity/complexity_exercises.cs b/en/codes/csharp/chapter_computational_complexity/complexity_exercises.cs new file mode 100644 index 000000000..051088bd4 --- /dev/null +++ b/en/codes/csharp/chapter_computational_complexity/complexity_exercises.cs @@ -0,0 +1,66 @@ +/** + * File: complexity_exercises.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_computational_complexity; + +public class complexity_exercises { + /* 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); + } + + /* 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; + } + + [Test] + public void Test() { + Assert.That(SumIter(1), Is.EqualTo(1)); + Assert.That(SumRecur(1), Is.EqualTo(1)); + Assert.That(SumIter(4), Is.EqualTo(10)); + Assert.That(SumRecur(4), Is.EqualTo(10)); + Assert.That(LinearLoop(4), Is.EqualTo(6)); + Assert.That(QuadraticLoop(4), Is.EqualTo(20)); + Assert.That(LogarithmicLoop(4), Is.EqualTo(1)); + Assert.That(LogarithmicLoop(5), Is.EqualTo(1)); + } +} diff --git a/en/codes/csharp/chapter_divide_and_conquer/fast_power.cs b/en/codes/csharp/chapter_divide_and_conquer/fast_power.cs new file mode 100644 index 000000000..0f7361152 --- /dev/null +++ b/en/codes/csharp/chapter_divide_and_conquer/fast_power.cs @@ -0,0 +1,28 @@ +/** + * File: fast_power.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_divide_and_conquer; + +public class fast_power { + /* 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; + } + + [Test] + public void Test() { + Assert.That(FastPow(7, 0), Is.EqualTo(1)); + Assert.That(FastPow(3, 5), Is.EqualTo(243)); + Assert.That(FastPow(2, 6), Is.EqualTo(64)); + } +} diff --git a/en/codes/dart/chapter_computational_complexity/complexity_exercises.dart b/en/codes/dart/chapter_computational_complexity/complexity_exercises.dart new file mode 100644 index 000000000..f577c19cc --- /dev/null +++ b/en/codes/dart/chapter_computational_complexity/complexity_exercises.dart @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 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); +} + +/* 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; +} + +void main() { + if (sumIter(1) != 1 || + sumRecur(1) != 1 || + sumIter(4) != 10 || + sumRecur(4) != 10 || + linearLoop(4) != 6 || + quadraticLoop(4) != 20 || + logarithmicLoop(4) != 1 || + logarithmicLoop(5) != 1) { + throw StateError('complexity exercise check failed'); + } +} diff --git a/en/codes/dart/chapter_divide_and_conquer/fast_power.dart b/en/codes/dart/chapter_divide_and_conquer/fast_power.dart new file mode 100644 index 000000000..8610ab675 --- /dev/null +++ b/en/codes/dart/chapter_divide_and_conquer/fast_power.dart @@ -0,0 +1,23 @@ +/** + * File: fast_power.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 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; +} + +void main() { + if (fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64) { + throw StateError('fast power check failed'); + } +} diff --git a/en/codes/go/chapter_computational_complexity/complexity_exercises.go b/en/codes/go/chapter_computational_complexity/complexity_exercises.go new file mode 100644 index 000000000..d96a2563f --- /dev/null +++ b/en/codes/go/chapter_computational_complexity/complexity_exercises.go @@ -0,0 +1,50 @@ +// File: complexity_exercises.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +/* 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) +} + +/* 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 +} diff --git a/en/codes/go/chapter_computational_complexity/complexity_exercises_test.go b/en/codes/go/chapter_computational_complexity/complexity_exercises_test.go new file mode 100644 index 000000000..5e07da9bc --- /dev/null +++ b/en/codes/go/chapter_computational_complexity/complexity_exercises_test.go @@ -0,0 +1,22 @@ +// File: complexity_exercises_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +import "testing" + +func TestComplexityExercises(t *testing.T) { + if sumIter(1) != 1 || sumRecur(1) != 1 { + t.Fatal("sum functions failed for n = 1") + } + if sumIter(4) != 10 || sumRecur(4) != 10 { + t.Fatal("sum functions failed for n = 4") + } + if linearLoop(4) != 6 || quadraticLoop(4) != 20 { + t.Fatal("complexity loops returned an unexpected value") + } + if logarithmicLoop(4) != 1 || logarithmicLoop(5) != 1 { + t.Fatal("logarithmic loop returned an unexpected value") + } +} diff --git a/en/codes/go/chapter_divide_and_conquer/fast_power.go b/en/codes/go/chapter_divide_and_conquer/fast_power.go new file mode 100644 index 000000000..c5fc9ce85 --- /dev/null +++ b/en/codes/go/chapter_divide_and_conquer/fast_power.go @@ -0,0 +1,17 @@ +// File: fast_power.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +/* 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 +} diff --git a/en/codes/go/chapter_divide_and_conquer/fast_power_test.go b/en/codes/go/chapter_divide_and_conquer/fast_power_test.go new file mode 100644 index 000000000..38318718b --- /dev/null +++ b/en/codes/go/chapter_divide_and_conquer/fast_power_test.go @@ -0,0 +1,13 @@ +// File: fast_power_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +import "testing" + +func TestFastPower(t *testing.T) { + if fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64 { + t.Fatal("fast power returned an unexpected value") + } +} diff --git a/en/codes/java/chapter_computational_complexity/complexity_exercises.java b/en/codes/java/chapter_computational_complexity/complexity_exercises.java new file mode 100644 index 000000000..9ccd21c39 --- /dev/null +++ b/en/codes/java/chapter_computational_complexity/complexity_exercises.java @@ -0,0 +1,62 @@ +/** + * File: complexity_exercises.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity; + +public class complexity_exercises { + /* Iterative summation */ + static int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* Recursive summation */ + static int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); + } + + /* Linear loop */ + static int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* Quadratic loop */ + static 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 */ + static int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + public static void main(String[] args) { + assert sumIter(1) == 1 && sumRecur(1) == 1; + assert sumIter(4) == 10 && sumRecur(4) == 10; + assert linearLoop(4) == 6; + assert quadraticLoop(4) == 20; + assert logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1; + } +} diff --git a/en/codes/java/chapter_divide_and_conquer/fast_power.java b/en/codes/java/chapter_divide_and_conquer/fast_power.java new file mode 100644 index 000000000..e0533592d --- /dev/null +++ b/en/codes/java/chapter_divide_and_conquer/fast_power.java @@ -0,0 +1,27 @@ +/** + * File: fast_power.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer; + +public class fast_power { + /* Exponentiation by squaring */ + static 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; + } + + public static void main(String[] args) { + assert fastPow(7, 0) == 1; + assert fastPow(3, 5) == 243; + assert fastPow(2, 6) == 64; + } +} diff --git a/en/codes/javascript/chapter_computational_complexity/complexity_exercises.js b/en/codes/javascript/chapter_computational_complexity/complexity_exercises.js new file mode 100644 index 000000000..7418687c2 --- /dev/null +++ b/en/codes/javascript/chapter_computational_complexity/complexity_exercises.js @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 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); +} + +/* 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; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} diff --git a/en/codes/javascript/chapter_divide_and_conquer/fast_power.js b/en/codes/javascript/chapter_divide_and_conquer/fast_power.js new file mode 100644 index 000000000..d13a0ee13 --- /dev/null +++ b/en/codes/javascript/chapter_divide_and_conquer/fast_power.js @@ -0,0 +1,21 @@ +/** + * File: fast_power.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} diff --git a/en/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt b/en/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt new file mode 100644 index 000000000..f23c48c8f --- /dev/null +++ b/en/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity.complexity_exercises + +/* 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) +} + +/* 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 +} + +fun main() { + check(sumIter(1) == 1 && sumRecur(1) == 1) + check(sumIter(4) == 10 && sumRecur(4) == 10) + check(linearLoop(4) == 6) + check(quadraticLoop(4) == 20) + check(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1) +} diff --git a/en/codes/kotlin/chapter_divide_and_conquer/fast_power.kt b/en/codes/kotlin/chapter_divide_and_conquer/fast_power.kt new file mode 100644 index 000000000..65c2e38bf --- /dev/null +++ b/en/codes/kotlin/chapter_divide_and_conquer/fast_power.kt @@ -0,0 +1,25 @@ +/** + * File: fast_power.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer.fast_power + +/* 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 +} + +fun main() { + check(fastPow(7, 0) == 1) + check(fastPow(3, 5) == 243) + check(fastPow(2, 6) == 64) +} diff --git a/en/codes/python/chapter_computational_complexity/complexity_exercises.py b/en/codes/python/chapter_computational_complexity/complexity_exercises.py new file mode 100644 index 000000000..56db8a540 --- /dev/null +++ b/en/codes/python/chapter_computational_complexity/complexity_exercises.py @@ -0,0 +1,52 @@ +""" +File: complexity_exercises.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +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) + + +def linear_loop(n: int) -> int: + """Linear loop""" + res = 0 + for i in range(n): + res += i + return res + + +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 + + +if __name__ == "__main__": + assert sum_iter(1) == sum_recur(1) == 1 + assert sum_iter(4) == sum_recur(4) == 10 + assert linear_loop(4) == 6 + assert quadratic_loop(4) == 20 + assert logarithmic_loop(4) == logarithmic_loop(5) == 1 diff --git a/en/codes/python/chapter_divide_and_conquer/fast_power.py b/en/codes/python/chapter_divide_and_conquer/fast_power.py new file mode 100644 index 000000000..eb768affa --- /dev/null +++ b/en/codes/python/chapter_divide_and_conquer/fast_power.py @@ -0,0 +1,21 @@ +""" +File: fast_power.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +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 + + +if __name__ == "__main__": + assert fast_pow(7, 0) == 1 + assert fast_pow(3, 5) == 243 + assert fast_pow(2, 6) == 64 diff --git a/en/codes/ruby/chapter_computational_complexity/complexity_exercises.rb b/en/codes/ruby/chapter_computational_complexity/complexity_exercises.rb new file mode 100644 index 000000000..f1593d354 --- /dev/null +++ b/en/codes/ruby/chapter_computational_complexity/complexity_exercises.rb @@ -0,0 +1,55 @@ +=begin +File: complexity_exercises.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### 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 + +### 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 + +if __FILE__ == $0 + raise 'sum check failed' unless sum_iter(1) == 1 && sum_recur(1) == 1 + raise 'sum check failed' unless sum_iter(4) == 10 && sum_recur(4) == 10 + raise 'linear check failed' unless linear_loop(4) == 6 + raise 'quadratic check failed' unless quadratic_loop(4) == 20 + raise 'logarithmic check failed' unless logarithmic_loop(4) == 1 && logarithmic_loop(5) == 1 +end diff --git a/en/codes/ruby/chapter_divide_and_conquer/fast_power.rb b/en/codes/ruby/chapter_divide_and_conquer/fast_power.rb new file mode 100644 index 000000000..062dd0fa7 --- /dev/null +++ b/en/codes/ruby/chapter_divide_and_conquer/fast_power.rb @@ -0,0 +1,21 @@ +=begin +File: fast_power.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### 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 + +if __FILE__ == $0 + raise 'fast power check failed' unless fast_pow(7, 0) == 1 + raise 'fast power check failed' unless fast_pow(3, 5) == 243 + raise 'fast power check failed' unless fast_pow(2, 6) == 64 +end diff --git a/en/codes/rust/Cargo.toml b/en/codes/rust/Cargo.toml index 160f9134c..147947168 100644 --- a/en/codes/rust/Cargo.toml +++ b/en/codes/rust/Cargo.toml @@ -4,6 +4,16 @@ version = "0.1.0" edition = "2021" publish = false +# Run Command: cargo run --bin complexity_exercises +[[bin]] +name = "complexity_exercises" +path = "chapter_computational_complexity/complexity_exercises.rs" + +# Run Command: cargo run --bin fast_power +[[bin]] +name = "fast_power" +path = "chapter_divide_and_conquer/fast_power.rs" + # Run Command: cargo run --bin time_complexity [[bin]] name = "time_complexity" diff --git a/en/codes/rust/chapter_computational_complexity/complexity_exercises.rs b/en/codes/rust/chapter_computational_complexity/complexity_exercises.rs new file mode 100644 index 000000000..6366936c2 --- /dev/null +++ b/en/codes/rust/chapter_computational_complexity/complexity_exercises.rs @@ -0,0 +1,61 @@ +/* + * File: complexity_exercises.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 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) +} + +/* 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 +} + +fn main() { + assert_eq!(sum_iter(1), 1); + assert_eq!(sum_recur(1), 1); + assert_eq!(sum_iter(4), 10); + assert_eq!(sum_recur(4), 10); + assert_eq!(linear_loop(4), 6); + assert_eq!(quadratic_loop(4), 20); + assert_eq!(logarithmic_loop(4), 1); + assert_eq!(logarithmic_loop(5), 1); +} diff --git a/en/codes/rust/chapter_divide_and_conquer/fast_power.rs b/en/codes/rust/chapter_divide_and_conquer/fast_power.rs new file mode 100644 index 000000000..659116a54 --- /dev/null +++ b/en/codes/rust/chapter_divide_and_conquer/fast_power.rs @@ -0,0 +1,23 @@ +/* + * File: fast_power.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 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 +} + +fn main() { + assert_eq!(fast_pow(7, 0), 1); + assert_eq!(fast_pow(3, 5), 243); + assert_eq!(fast_pow(2, 6), 64); +} diff --git a/en/codes/swift/Package.swift b/en/codes/swift/Package.swift index 5326dc138..8ccb78ab8 100644 --- a/en/codes/swift/Package.swift +++ b/en/codes/swift/Package.swift @@ -11,6 +11,7 @@ let package = Package( .executable(name: "time_complexity", targets: ["time_complexity"]), .executable(name: "worst_best_time_complexity", targets: ["worst_best_time_complexity"]), .executable(name: "space_complexity", targets: ["space_complexity"]), + .executable(name: "complexity_exercises", targets: ["complexity_exercises"]), // chapter_array_and_linkedlist .executable(name: "array", targets: ["array"]), .executable(name: "linked_list", targets: ["linked_list"]), @@ -70,6 +71,7 @@ let package = Package( .executable(name: "binary_search_recur", targets: ["binary_search_recur"]), .executable(name: "build_tree", targets: ["build_tree"]), .executable(name: "hanota", targets: ["hanota"]), + .executable(name: "fast_power", targets: ["fast_power"]), // chapter_backtracking .executable(name: "preorder_traversal_i_compact", targets: ["preorder_traversal_i_compact"]), .executable(name: "preorder_traversal_ii_compact", targets: ["preorder_traversal_ii_compact"]), @@ -114,6 +116,7 @@ let package = Package( .executableTarget(name: "time_complexity", path: "chapter_computational_complexity", sources: ["time_complexity.swift"]), .executableTarget(name: "worst_best_time_complexity", path: "chapter_computational_complexity", sources: ["worst_best_time_complexity.swift"]), .executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]), + .executableTarget(name: "complexity_exercises", path: "chapter_computational_complexity", sources: ["complexity_exercises.swift"]), // chapter_array_and_linkedlist .executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]), .executableTarget(name: "linked_list", dependencies: ["utils"], path: "chapter_array_and_linkedlist", sources: ["linked_list.swift"]), @@ -173,6 +176,7 @@ let package = Package( .executableTarget(name: "binary_search_recur", path: "chapter_divide_and_conquer", sources: ["binary_search_recur.swift"]), .executableTarget(name: "build_tree", dependencies: ["utils"], path: "chapter_divide_and_conquer", sources: ["build_tree.swift"]), .executableTarget(name: "hanota", path: "chapter_divide_and_conquer", sources: ["hanota.swift"]), + .executableTarget(name: "fast_power", path: "chapter_divide_and_conquer", sources: ["fast_power.swift"]), // chapter_backtracking .executableTarget(name: "preorder_traversal_i_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_i_compact.swift"]), .executableTarget(name: "preorder_traversal_ii_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_ii_compact.swift"]), diff --git a/en/codes/swift/chapter_computational_complexity/complexity_exercises.swift b/en/codes/swift/chapter_computational_complexity/complexity_exercises.swift new file mode 100644 index 000000000..ed70497d1 --- /dev/null +++ b/en/codes/swift/chapter_computational_complexity/complexity_exercises.swift @@ -0,0 +1,62 @@ +/** + File: complexity_exercises.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* 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) +} + +/* 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 +} + +@main +enum ComplexityExercises { + static func main() { + assert(sumIter(n: 1) == 1 && sumRecur(n: 1) == 1) + assert(sumIter(n: 4) == 10 && sumRecur(n: 4) == 10) + assert(linearLoop(n: 4) == 6) + assert(quadraticLoop(n: 4) == 20) + assert(logarithmicLoop(n: 4) == 1 && logarithmicLoop(n: 5) == 1) + } +} diff --git a/en/codes/swift/chapter_divide_and_conquer/fast_power.swift b/en/codes/swift/chapter_divide_and_conquer/fast_power.swift new file mode 100644 index 000000000..131bd88e7 --- /dev/null +++ b/en/codes/swift/chapter_divide_and_conquer/fast_power.swift @@ -0,0 +1,26 @@ +/** + File: fast_power.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* 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 +} + +@main +enum FastPower { + static func main() { + assert(fastPow(x: 7, n: 0) == 1) + assert(fastPow(x: 3, n: 5) == 243) + assert(fastPow(x: 2, n: 6) == 64) + } +} diff --git a/en/codes/typescript/chapter_computational_complexity/complexity_exercises.ts b/en/codes/typescript/chapter_computational_complexity/complexity_exercises.ts new file mode 100644 index 000000000..72ced4a3d --- /dev/null +++ b/en/codes/typescript/chapter_computational_complexity/complexity_exercises.ts @@ -0,0 +1,65 @@ +/** + * File: complexity_exercises.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 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); +} + +/* 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; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} + +export {}; diff --git a/en/codes/typescript/chapter_divide_and_conquer/fast_power.ts b/en/codes/typescript/chapter_divide_and_conquer/fast_power.ts new file mode 100644 index 000000000..15693d4dc --- /dev/null +++ b/en/codes/typescript/chapter_divide_and_conquer/fast_power.ts @@ -0,0 +1,23 @@ +/** + * File: fast_power.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} + +export {}; diff --git a/en/docs/chapter_computational_complexity/exercises.md b/en/docs/chapter_computational_complexity/exercises.md index ff6c9f08d..19af4e5c3 100644 --- a/en/docs/chapter_computational_complexity/exercises.md +++ b/en/docs/chapter_computational_complexity/exercises.md @@ -7,33 +7,23 @@ 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 - -def sum_recur(n): - if n == 1: - return 1 - return n + sum_recur(n - 1) +```src +[file]{complexity_exercises}-[class]{}-[func]{sum_iter} ``` -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)$. @@ -47,21 +37,8 @@ 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 - -# Fragment 2 -s = 0 -for i in range(n): - for j in range(i, n): - s += j - -# Fragment 3 -while n > 1: - n = n // 2 +```src +[file]{complexity_exercises}-[class]{}-[func]{linear_loop} ``` ??? success "Answer" diff --git a/en/docs/chapter_divide_and_conquer/exercises.md b/en/docs/chapter_divide_and_conquer/exercises.md index 2ca23045f..1cdab1fa5 100644 --- a/en/docs/chapter_divide_and_conquer/exercises.md +++ b/en/docs/chapter_divide_and_conquer/exercises.md @@ -25,23 +25,17 @@ 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 +```src +[file]{fast_power}-[class]{}-[func]{fast_pow} ``` -Use it to calculate `fast_pow(3, 5)`: +Set `x = 3` and `n = 5`, and use this function to calculate the result: 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" @@ -50,7 +44,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. diff --git a/ja/codes/c/chapter_computational_complexity/CMakeLists.txt b/ja/codes/c/chapter_computational_complexity/CMakeLists.txt index dcfa063c3..3d2450c26 100644 --- a/ja/codes/c/chapter_computational_complexity/CMakeLists.txt +++ b/ja/codes/c/chapter_computational_complexity/CMakeLists.txt @@ -3,3 +3,4 @@ add_executable(recursion recursion.c) add_executable(time_complexity time_complexity.c) add_executable(worst_best_time_complexity worst_best_time_complexity.c) add_executable(space_complexity space_complexity.c) +add_executable(complexity_exercises complexity_exercises.c) diff --git a/ja/codes/c/chapter_computational_complexity/complexity_exercises.c b/ja/codes/c/chapter_computational_complexity/complexity_exercises.c new file mode 100644 index 000000000..4a04e83da --- /dev/null +++ b/ja/codes/c/chapter_computational_complexity/complexity_exercises.c @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 反復による総和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 再帰による総和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線形時間のループ */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 二次時間のループ */ +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; +} + +/* 対数時間のループ */ +int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; +} + +int main(void) { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/ja/codes/c/chapter_divide_and_conquer/CMakeLists.txt b/ja/codes/c/chapter_divide_and_conquer/CMakeLists.txt index e03b1c588..31352a138 100644 --- a/ja/codes/c/chapter_divide_and_conquer/CMakeLists.txt +++ b/ja/codes/c/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.c) add_executable(build_tree build_tree.c) add_executable(hanota hanota.c) +add_executable(fast_power fast_power.c) diff --git a/ja/codes/c/chapter_divide_and_conquer/fast_power.c b/ja/codes/c/chapter_divide_and_conquer/fast_power.c new file mode 100644 index 000000000..211ff67cf --- /dev/null +++ b/ja/codes/c/chapter_divide_and_conquer/fast_power.c @@ -0,0 +1,26 @@ +/** + * File: fast_power.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 高速べき乗 */ +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; +} + +int main(void) { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/ja/codes/cpp/chapter_computational_complexity/CMakeLists.txt b/ja/codes/cpp/chapter_computational_complexity/CMakeLists.txt index ea2845b75..536935b68 100644 --- a/ja/codes/cpp/chapter_computational_complexity/CMakeLists.txt +++ b/ja/codes/cpp/chapter_computational_complexity/CMakeLists.txt @@ -2,4 +2,5 @@ add_executable(iteration iteration.cpp) add_executable(recursion recursion.cpp) add_executable(space_complexity space_complexity.cpp) add_executable(time_complexity time_complexity.cpp) -add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) \ No newline at end of file +add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) +add_executable(complexity_exercises complexity_exercises.cpp) diff --git a/ja/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp b/ja/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp new file mode 100644 index 000000000..0875804ee --- /dev/null +++ b/ja/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 反復による総和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; ++i) { + res += i; + } + return res; +} + +/* 再帰による総和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線形時間のループ */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; ++i) { + res += i; + } + return res; +} + +/* 二次時間のループ */ +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; +} + +/* 対数時間のループ */ +int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; +} + +int main() { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/ja/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt b/ja/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt index 38dfff710..8e66f77b5 100644 --- a/ja/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt +++ b/ja/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.cpp) add_executable(build_tree build_tree.cpp) -add_executable(hanota hanota.cpp) \ No newline at end of file +add_executable(hanota hanota.cpp) +add_executable(fast_power fast_power.cpp) diff --git a/ja/codes/cpp/chapter_divide_and_conquer/fast_power.cpp b/ja/codes/cpp/chapter_divide_and_conquer/fast_power.cpp new file mode 100644 index 000000000..74782d822 --- /dev/null +++ b/ja/codes/cpp/chapter_divide_and_conquer/fast_power.cpp @@ -0,0 +1,26 @@ +/** + * File: fast_power.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 高速べき乗 */ +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; +} + +int main() { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/ja/codes/csharp/chapter_computational_complexity/complexity_exercises.cs b/ja/codes/csharp/chapter_computational_complexity/complexity_exercises.cs new file mode 100644 index 000000000..3492bbe74 --- /dev/null +++ b/ja/codes/csharp/chapter_computational_complexity/complexity_exercises.cs @@ -0,0 +1,66 @@ +/** + * File: complexity_exercises.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_computational_complexity; + +public class complexity_exercises { + /* 反復による総和 */ + int SumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* 再帰による総和 */ + int SumRecur(int n) { + if (n == 1) { + return 1; + } + return n + SumRecur(n - 1); + } + + /* 線形時間のループ */ + int LinearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* 二次時間のループ */ + 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; + } + + /* 対数時間のループ */ + int LogarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + [Test] + public void Test() { + Assert.That(SumIter(1), Is.EqualTo(1)); + Assert.That(SumRecur(1), Is.EqualTo(1)); + Assert.That(SumIter(4), Is.EqualTo(10)); + Assert.That(SumRecur(4), Is.EqualTo(10)); + Assert.That(LinearLoop(4), Is.EqualTo(6)); + Assert.That(QuadraticLoop(4), Is.EqualTo(20)); + Assert.That(LogarithmicLoop(4), Is.EqualTo(1)); + Assert.That(LogarithmicLoop(5), Is.EqualTo(1)); + } +} diff --git a/ja/codes/csharp/chapter_divide_and_conquer/fast_power.cs b/ja/codes/csharp/chapter_divide_and_conquer/fast_power.cs new file mode 100644 index 000000000..82226290a --- /dev/null +++ b/ja/codes/csharp/chapter_divide_and_conquer/fast_power.cs @@ -0,0 +1,28 @@ +/** + * File: fast_power.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_divide_and_conquer; + +public class fast_power { + /* 高速べき乗 */ + 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; + } + + [Test] + public void Test() { + Assert.That(FastPow(7, 0), Is.EqualTo(1)); + Assert.That(FastPow(3, 5), Is.EqualTo(243)); + Assert.That(FastPow(2, 6), Is.EqualTo(64)); + } +} diff --git a/ja/codes/dart/chapter_computational_complexity/complexity_exercises.dart b/ja/codes/dart/chapter_computational_complexity/complexity_exercises.dart new file mode 100644 index 000000000..d4c353846 --- /dev/null +++ b/ja/codes/dart/chapter_computational_complexity/complexity_exercises.dart @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 反復による総和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 再帰による総和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線形時間のループ */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 二次時間のループ */ +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; +} + +/* 対数時間のループ */ +int logarithmicLoop(int n) { + while (n > 1) { + n ~/= 2; + } + return n; +} + +void main() { + if (sumIter(1) != 1 || + sumRecur(1) != 1 || + sumIter(4) != 10 || + sumRecur(4) != 10 || + linearLoop(4) != 6 || + quadraticLoop(4) != 20 || + logarithmicLoop(4) != 1 || + logarithmicLoop(5) != 1) { + throw StateError('complexity exercise check failed'); + } +} diff --git a/ja/codes/dart/chapter_divide_and_conquer/fast_power.dart b/ja/codes/dart/chapter_divide_and_conquer/fast_power.dart new file mode 100644 index 000000000..1b13d2a1a --- /dev/null +++ b/ja/codes/dart/chapter_divide_and_conquer/fast_power.dart @@ -0,0 +1,23 @@ +/** + * File: fast_power.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 高速べき乗 */ +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; +} + +void main() { + if (fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64) { + throw StateError('fast power check failed'); + } +} diff --git a/ja/codes/go/chapter_computational_complexity/complexity_exercises.go b/ja/codes/go/chapter_computational_complexity/complexity_exercises.go new file mode 100644 index 000000000..2b8adf2c1 --- /dev/null +++ b/ja/codes/go/chapter_computational_complexity/complexity_exercises.go @@ -0,0 +1,50 @@ +// File: complexity_exercises.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +/* 反復による総和 */ +func sumIter(n int) int { + res := 0 + for i := 1; i <= n; i++ { + res += i + } + return res +} + +/* 再帰による総和 */ +func sumRecur(n int) int { + if n == 1 { + return 1 + } + return n + sumRecur(n-1) +} + +/* 線形時間のループ */ +func linearLoop(n int) int { + res := 0 + for i := 0; i < n; i++ { + res += i + } + return res +} + +/* 二次時間のループ */ +func quadraticLoop(n int) int { + res := 0 + for i := 0; i < n; i++ { + for j := i; j < n; j++ { + res += j + } + } + return res +} + +/* 対数時間のループ */ +func logarithmicLoop(n int) int { + for n > 1 { + n /= 2 + } + return n +} diff --git a/ja/codes/go/chapter_computational_complexity/complexity_exercises_test.go b/ja/codes/go/chapter_computational_complexity/complexity_exercises_test.go new file mode 100644 index 000000000..5e07da9bc --- /dev/null +++ b/ja/codes/go/chapter_computational_complexity/complexity_exercises_test.go @@ -0,0 +1,22 @@ +// File: complexity_exercises_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +import "testing" + +func TestComplexityExercises(t *testing.T) { + if sumIter(1) != 1 || sumRecur(1) != 1 { + t.Fatal("sum functions failed for n = 1") + } + if sumIter(4) != 10 || sumRecur(4) != 10 { + t.Fatal("sum functions failed for n = 4") + } + if linearLoop(4) != 6 || quadraticLoop(4) != 20 { + t.Fatal("complexity loops returned an unexpected value") + } + if logarithmicLoop(4) != 1 || logarithmicLoop(5) != 1 { + t.Fatal("logarithmic loop returned an unexpected value") + } +} diff --git a/ja/codes/go/chapter_divide_and_conquer/fast_power.go b/ja/codes/go/chapter_divide_and_conquer/fast_power.go new file mode 100644 index 000000000..9d4735049 --- /dev/null +++ b/ja/codes/go/chapter_divide_and_conquer/fast_power.go @@ -0,0 +1,17 @@ +// File: fast_power.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +/* 高速べき乗 */ +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 +} diff --git a/ja/codes/go/chapter_divide_and_conquer/fast_power_test.go b/ja/codes/go/chapter_divide_and_conquer/fast_power_test.go new file mode 100644 index 000000000..38318718b --- /dev/null +++ b/ja/codes/go/chapter_divide_and_conquer/fast_power_test.go @@ -0,0 +1,13 @@ +// File: fast_power_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +import "testing" + +func TestFastPower(t *testing.T) { + if fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64 { + t.Fatal("fast power returned an unexpected value") + } +} diff --git a/ja/codes/java/chapter_computational_complexity/complexity_exercises.java b/ja/codes/java/chapter_computational_complexity/complexity_exercises.java new file mode 100644 index 000000000..f6bee8df9 --- /dev/null +++ b/ja/codes/java/chapter_computational_complexity/complexity_exercises.java @@ -0,0 +1,62 @@ +/** + * File: complexity_exercises.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity; + +public class complexity_exercises { + /* 反復による総和 */ + static int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* 再帰による総和 */ + static int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); + } + + /* 線形時間のループ */ + static int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* 二次時間のループ */ + static 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; + } + + /* 対数時間のループ */ + static int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + public static void main(String[] args) { + assert sumIter(1) == 1 && sumRecur(1) == 1; + assert sumIter(4) == 10 && sumRecur(4) == 10; + assert linearLoop(4) == 6; + assert quadraticLoop(4) == 20; + assert logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1; + } +} diff --git a/ja/codes/java/chapter_divide_and_conquer/fast_power.java b/ja/codes/java/chapter_divide_and_conquer/fast_power.java new file mode 100644 index 000000000..065946855 --- /dev/null +++ b/ja/codes/java/chapter_divide_and_conquer/fast_power.java @@ -0,0 +1,27 @@ +/** + * File: fast_power.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer; + +public class fast_power { + /* 高速べき乗 */ + static 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; + } + + public static void main(String[] args) { + assert fastPow(7, 0) == 1; + assert fastPow(3, 5) == 243; + assert fastPow(2, 6) == 64; + } +} diff --git a/ja/codes/javascript/chapter_computational_complexity/complexity_exercises.js b/ja/codes/javascript/chapter_computational_complexity/complexity_exercises.js new file mode 100644 index 000000000..5868e0479 --- /dev/null +++ b/ja/codes/javascript/chapter_computational_complexity/complexity_exercises.js @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 反復による総和 */ +function sumIter(n) { + let res = 0; + for (let i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 再帰による総和 */ +function sumRecur(n) { + if (n === 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線形時間のループ */ +function linearLoop(n) { + let res = 0; + for (let i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 二次時間のループ */ +function quadraticLoop(n) { + let res = 0; + for (let i = 0; i < n; i++) { + for (let j = i; j < n; j++) { + res += j; + } + } + return res; +} + +/* 対数時間のループ */ +function logarithmicLoop(n) { + while (n > 1) { + n = Math.floor(n / 2); + } + return n; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} diff --git a/ja/codes/javascript/chapter_divide_and_conquer/fast_power.js b/ja/codes/javascript/chapter_divide_and_conquer/fast_power.js new file mode 100644 index 000000000..9348d4dc6 --- /dev/null +++ b/ja/codes/javascript/chapter_divide_and_conquer/fast_power.js @@ -0,0 +1,21 @@ +/** + * File: fast_power.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 高速べき乗 */ +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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} diff --git a/ja/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt b/ja/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt new file mode 100644 index 000000000..ab9b33bc8 --- /dev/null +++ b/ja/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity.complexity_exercises + +/* 反復による総和 */ +fun sumIter(n: Int): Int { + var res = 0 + for (i in 1..n) { + res += i + } + return res +} + +/* 再帰による総和 */ +fun sumRecur(n: Int): Int { + if (n == 1) { + return 1 + } + return n + sumRecur(n - 1) +} + +/* 線形時間のループ */ +fun linearLoop(n: Int): Int { + var res = 0 + for (i in 0 until n) { + res += i + } + return res +} + +/* 二次時間のループ */ +fun quadraticLoop(n: Int): Int { + var res = 0 + for (i in 0 until n) { + for (j in i until n) { + res += j + } + } + return res +} + +/* 対数時間のループ */ +fun logarithmicLoop(n: Int): Int { + var value = n + while (value > 1) { + value /= 2 + } + return value +} + +fun main() { + check(sumIter(1) == 1 && sumRecur(1) == 1) + check(sumIter(4) == 10 && sumRecur(4) == 10) + check(linearLoop(4) == 6) + check(quadraticLoop(4) == 20) + check(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1) +} diff --git a/ja/codes/kotlin/chapter_divide_and_conquer/fast_power.kt b/ja/codes/kotlin/chapter_divide_and_conquer/fast_power.kt new file mode 100644 index 000000000..6a8115f73 --- /dev/null +++ b/ja/codes/kotlin/chapter_divide_and_conquer/fast_power.kt @@ -0,0 +1,25 @@ +/** + * File: fast_power.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer.fast_power + +/* 高速べき乗 */ +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 +} + +fun main() { + check(fastPow(7, 0) == 1) + check(fastPow(3, 5) == 243) + check(fastPow(2, 6) == 64) +} diff --git a/ja/codes/python/chapter_computational_complexity/complexity_exercises.py b/ja/codes/python/chapter_computational_complexity/complexity_exercises.py new file mode 100644 index 000000000..48cb0c5d4 --- /dev/null +++ b/ja/codes/python/chapter_computational_complexity/complexity_exercises.py @@ -0,0 +1,52 @@ +""" +File: complexity_exercises.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +def sum_iter(n: int) -> int: + """反復による総和""" + res = 0 + for i in range(1, n + 1): + res += i + return res + + +def sum_recur(n: int) -> int: + """再帰による総和""" + if n == 1: + return 1 + return n + sum_recur(n - 1) + + +def linear_loop(n: int) -> int: + """線形時間のループ""" + res = 0 + for i in range(n): + res += i + return res + + +def quadratic_loop(n: int) -> int: + """二次時間のループ""" + res = 0 + for i in range(n): + for j in range(i, n): + res += j + return res + + +def logarithmic_loop(n: int) -> int: + """対数時間のループ""" + while n > 1: + n //= 2 + return n + + +if __name__ == "__main__": + assert sum_iter(1) == sum_recur(1) == 1 + assert sum_iter(4) == sum_recur(4) == 10 + assert linear_loop(4) == 6 + assert quadratic_loop(4) == 20 + assert logarithmic_loop(4) == logarithmic_loop(5) == 1 diff --git a/ja/codes/python/chapter_divide_and_conquer/fast_power.py b/ja/codes/python/chapter_divide_and_conquer/fast_power.py new file mode 100644 index 000000000..ef309271a --- /dev/null +++ b/ja/codes/python/chapter_divide_and_conquer/fast_power.py @@ -0,0 +1,21 @@ +""" +File: fast_power.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +def fast_pow(x: int, n: int) -> int: + """高速べき乗""" + if n == 0: + return 1 + half = fast_pow(x, n // 2) + if n % 2 == 0: + return half * half + return half * half * x + + +if __name__ == "__main__": + assert fast_pow(7, 0) == 1 + assert fast_pow(3, 5) == 243 + assert fast_pow(2, 6) == 64 diff --git a/ja/codes/ruby/chapter_computational_complexity/complexity_exercises.rb b/ja/codes/ruby/chapter_computational_complexity/complexity_exercises.rb new file mode 100644 index 000000000..fb6a957b3 --- /dev/null +++ b/ja/codes/ruby/chapter_computational_complexity/complexity_exercises.rb @@ -0,0 +1,55 @@ +=begin +File: complexity_exercises.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### 反復による総和 ### +def sum_iter(n) + res = 0 + for i in 1..n + res += i + end + res +end + +### 再帰による総和 ### +def sum_recur(n) + return 1 if n == 1 + + n + sum_recur(n - 1) +end + +### 線形時間のループ ### +def linear_loop(n) + res = 0 + for i in 0...n + res += i + end + res +end + +### 二次時間のループ ### +def quadratic_loop(n) + res = 0 + for i in 0...n + for j in i...n + res += j + end + end + res +end + +### 対数時間のループ ### +def logarithmic_loop(n) + n /= 2 while n > 1 + n +end + +if __FILE__ == $0 + raise 'sum check failed' unless sum_iter(1) == 1 && sum_recur(1) == 1 + raise 'sum check failed' unless sum_iter(4) == 10 && sum_recur(4) == 10 + raise 'linear check failed' unless linear_loop(4) == 6 + raise 'quadratic check failed' unless quadratic_loop(4) == 20 + raise 'logarithmic check failed' unless logarithmic_loop(4) == 1 && logarithmic_loop(5) == 1 +end diff --git a/ja/codes/ruby/chapter_divide_and_conquer/fast_power.rb b/ja/codes/ruby/chapter_divide_and_conquer/fast_power.rb new file mode 100644 index 000000000..67bb730fb --- /dev/null +++ b/ja/codes/ruby/chapter_divide_and_conquer/fast_power.rb @@ -0,0 +1,21 @@ +=begin +File: fast_power.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### 高速べき乗 ### +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 + +if __FILE__ == $0 + raise 'fast power check failed' unless fast_pow(7, 0) == 1 + raise 'fast power check failed' unless fast_pow(3, 5) == 243 + raise 'fast power check failed' unless fast_pow(2, 6) == 64 +end diff --git a/ja/codes/rust/Cargo.toml b/ja/codes/rust/Cargo.toml index 160f9134c..147947168 100644 --- a/ja/codes/rust/Cargo.toml +++ b/ja/codes/rust/Cargo.toml @@ -4,6 +4,16 @@ version = "0.1.0" edition = "2021" publish = false +# Run Command: cargo run --bin complexity_exercises +[[bin]] +name = "complexity_exercises" +path = "chapter_computational_complexity/complexity_exercises.rs" + +# Run Command: cargo run --bin fast_power +[[bin]] +name = "fast_power" +path = "chapter_divide_and_conquer/fast_power.rs" + # Run Command: cargo run --bin time_complexity [[bin]] name = "time_complexity" diff --git a/ja/codes/rust/chapter_computational_complexity/complexity_exercises.rs b/ja/codes/rust/chapter_computational_complexity/complexity_exercises.rs new file mode 100644 index 000000000..8932baac1 --- /dev/null +++ b/ja/codes/rust/chapter_computational_complexity/complexity_exercises.rs @@ -0,0 +1,61 @@ +/* + * File: complexity_exercises.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 反復による総和 */ +fn sum_iter(n: i32) -> i32 { + let mut res = 0; + for i in 1..=n { + res += i; + } + res +} + +/* 再帰による総和 */ +fn sum_recur(n: i32) -> i32 { + if n == 1 { + return 1; + } + n + sum_recur(n - 1) +} + +/* 線形時間のループ */ +fn linear_loop(n: i32) -> i32 { + let mut res = 0; + for i in 0..n { + res += i; + } + res +} + +/* 二次時間のループ */ +fn quadratic_loop(n: i32) -> i32 { + let mut res = 0; + for i in 0..n { + for j in i..n { + res += j; + } + } + res +} + +/* 対数時間のループ */ +fn logarithmic_loop(mut n: i32) -> i32 { + while n > 1 { + n /= 2; + } + n +} + +fn main() { + assert_eq!(sum_iter(1), 1); + assert_eq!(sum_recur(1), 1); + assert_eq!(sum_iter(4), 10); + assert_eq!(sum_recur(4), 10); + assert_eq!(linear_loop(4), 6); + assert_eq!(quadratic_loop(4), 20); + assert_eq!(logarithmic_loop(4), 1); + assert_eq!(logarithmic_loop(5), 1); +} diff --git a/ja/codes/rust/chapter_divide_and_conquer/fast_power.rs b/ja/codes/rust/chapter_divide_and_conquer/fast_power.rs new file mode 100644 index 000000000..8cc0366d8 --- /dev/null +++ b/ja/codes/rust/chapter_divide_and_conquer/fast_power.rs @@ -0,0 +1,23 @@ +/* + * File: fast_power.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 高速べき乗 */ +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 +} + +fn main() { + assert_eq!(fast_pow(7, 0), 1); + assert_eq!(fast_pow(3, 5), 243); + assert_eq!(fast_pow(2, 6), 64); +} diff --git a/ja/codes/swift/Package.swift b/ja/codes/swift/Package.swift index 5326dc138..8ccb78ab8 100644 --- a/ja/codes/swift/Package.swift +++ b/ja/codes/swift/Package.swift @@ -11,6 +11,7 @@ let package = Package( .executable(name: "time_complexity", targets: ["time_complexity"]), .executable(name: "worst_best_time_complexity", targets: ["worst_best_time_complexity"]), .executable(name: "space_complexity", targets: ["space_complexity"]), + .executable(name: "complexity_exercises", targets: ["complexity_exercises"]), // chapter_array_and_linkedlist .executable(name: "array", targets: ["array"]), .executable(name: "linked_list", targets: ["linked_list"]), @@ -70,6 +71,7 @@ let package = Package( .executable(name: "binary_search_recur", targets: ["binary_search_recur"]), .executable(name: "build_tree", targets: ["build_tree"]), .executable(name: "hanota", targets: ["hanota"]), + .executable(name: "fast_power", targets: ["fast_power"]), // chapter_backtracking .executable(name: "preorder_traversal_i_compact", targets: ["preorder_traversal_i_compact"]), .executable(name: "preorder_traversal_ii_compact", targets: ["preorder_traversal_ii_compact"]), @@ -114,6 +116,7 @@ let package = Package( .executableTarget(name: "time_complexity", path: "chapter_computational_complexity", sources: ["time_complexity.swift"]), .executableTarget(name: "worst_best_time_complexity", path: "chapter_computational_complexity", sources: ["worst_best_time_complexity.swift"]), .executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]), + .executableTarget(name: "complexity_exercises", path: "chapter_computational_complexity", sources: ["complexity_exercises.swift"]), // chapter_array_and_linkedlist .executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]), .executableTarget(name: "linked_list", dependencies: ["utils"], path: "chapter_array_and_linkedlist", sources: ["linked_list.swift"]), @@ -173,6 +176,7 @@ let package = Package( .executableTarget(name: "binary_search_recur", path: "chapter_divide_and_conquer", sources: ["binary_search_recur.swift"]), .executableTarget(name: "build_tree", dependencies: ["utils"], path: "chapter_divide_and_conquer", sources: ["build_tree.swift"]), .executableTarget(name: "hanota", path: "chapter_divide_and_conquer", sources: ["hanota.swift"]), + .executableTarget(name: "fast_power", path: "chapter_divide_and_conquer", sources: ["fast_power.swift"]), // chapter_backtracking .executableTarget(name: "preorder_traversal_i_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_i_compact.swift"]), .executableTarget(name: "preorder_traversal_ii_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_ii_compact.swift"]), diff --git a/ja/codes/swift/chapter_computational_complexity/complexity_exercises.swift b/ja/codes/swift/chapter_computational_complexity/complexity_exercises.swift new file mode 100644 index 000000000..7708bac5d --- /dev/null +++ b/ja/codes/swift/chapter_computational_complexity/complexity_exercises.swift @@ -0,0 +1,62 @@ +/** + File: complexity_exercises.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* 反復による総和 */ +func sumIter(n: Int) -> Int { + var res = 0 + for i in 1 ... n { + res += i + } + return res +} + +/* 再帰による総和 */ +func sumRecur(n: Int) -> Int { + if n == 1 { + return 1 + } + return n + sumRecur(n: n - 1) +} + +/* 線形時間のループ */ +func linearLoop(n: Int) -> Int { + var res = 0 + for i in 0 ..< n { + res += i + } + return res +} + +/* 二次時間のループ */ +func quadraticLoop(n: Int) -> Int { + var res = 0 + for i in 0 ..< n { + for j in i ..< n { + res += j + } + } + return res +} + +/* 対数時間のループ */ +func logarithmicLoop(n: Int) -> Int { + var n = n + while n > 1 { + n /= 2 + } + return n +} + +@main +enum ComplexityExercises { + static func main() { + assert(sumIter(n: 1) == 1 && sumRecur(n: 1) == 1) + assert(sumIter(n: 4) == 10 && sumRecur(n: 4) == 10) + assert(linearLoop(n: 4) == 6) + assert(quadraticLoop(n: 4) == 20) + assert(logarithmicLoop(n: 4) == 1 && logarithmicLoop(n: 5) == 1) + } +} diff --git a/ja/codes/swift/chapter_divide_and_conquer/fast_power.swift b/ja/codes/swift/chapter_divide_and_conquer/fast_power.swift new file mode 100644 index 000000000..503f6e1d5 --- /dev/null +++ b/ja/codes/swift/chapter_divide_and_conquer/fast_power.swift @@ -0,0 +1,26 @@ +/** + File: fast_power.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* 高速べき乗 */ +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 +} + +@main +enum FastPower { + static func main() { + assert(fastPow(x: 7, n: 0) == 1) + assert(fastPow(x: 3, n: 5) == 243) + assert(fastPow(x: 2, n: 6) == 64) + } +} diff --git a/ja/codes/typescript/chapter_computational_complexity/complexity_exercises.ts b/ja/codes/typescript/chapter_computational_complexity/complexity_exercises.ts new file mode 100644 index 000000000..97dcceb76 --- /dev/null +++ b/ja/codes/typescript/chapter_computational_complexity/complexity_exercises.ts @@ -0,0 +1,65 @@ +/** + * File: complexity_exercises.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 反復による総和 */ +function sumIter(n: number): number { + let res = 0; + for (let i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 再帰による総和 */ +function sumRecur(n: number): number { + if (n === 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線形時間のループ */ +function linearLoop(n: number): number { + let res = 0; + for (let i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 二次時間のループ */ +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; +} + +/* 対数時間のループ */ +function logarithmicLoop(n: number): number { + while (n > 1) { + n = Math.floor(n / 2); + } + return n; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} + +export {}; diff --git a/ja/codes/typescript/chapter_divide_and_conquer/fast_power.ts b/ja/codes/typescript/chapter_divide_and_conquer/fast_power.ts new file mode 100644 index 000000000..28cd56f53 --- /dev/null +++ b/ja/codes/typescript/chapter_divide_and_conquer/fast_power.ts @@ -0,0 +1,23 @@ +/** + * File: fast_power.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 高速べき乗 */ +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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} + +export {}; diff --git a/ja/docs/chapter_computational_complexity/exercises.md b/ja/docs/chapter_computational_complexity/exercises.md index 968f757fc..dce703804 100644 --- a/ja/docs/chapter_computational_complexity/exercises.md +++ b/ja/docs/chapter_computational_complexity/exercises.md @@ -7,33 +7,23 @@ 次の 2 つのコードは、どちらも $1 + 2 + \dots + n$ を計算します($n \ge 1$ とします)。`n` を 4 として、 プログラムが実際に実行される順序に沿って次の問いに答え、2 つの書き方の効率を比較してください。 -```python -def sum_iter(n): - s = 0 - for i in range(1, n + 1): - s += i - return s - -def sum_recur(n): - if n == 1: - return 1 - return n + sum_recur(n - 1) +```src +[file]{complexity_exercises}-[class]{}-[func]{sum_iter} ``` -1. `sum_iter(4)` を実行すると、各ループの終了時に変数 `s` はそれぞれいくつになりますか? -2. `sum_recur(4)` を実行すると、どの関数が順に呼び出されますか?最も深い呼び出しから戻るとき、結果はどのように求められますか? +1. `n = 4` を入力して反復関数を実行すると、各ループの終了時に累積変数 `res` はそれぞれいくつになりますか? +2. `n = 4` を入力して再帰関数を実行すると、引数 `n` はどの値を順に取りますか?最も深い呼び出しから戻るとき、結果はどのように求められますか? 3. 2 つの書き方の時間計算量と空間計算量は、それぞれいくつですか?問い 1、2 の実行過程と結び付けて理由を説明してください。 ??? success "解答" - 1. ループ変数 `i` は `1、2、3、4` の順に変化し、各ループの終了時に `s` は - `1、3、6、10` となります。したがって、`sum_iter(4)` は 10 を返します。 + 1. ループ変数 `i` は `1、2、3、4` の順に変化し、各ループの終了時に `res` は + `1、3、6、10` となります。したがって、反復関数は 10 を返します。 - 2. 関数は - `sum_recur(4) → sum_recur(3) → sum_recur(2) → sum_recur(1)` の順に呼び出されます。 - `sum_recur(1)` が 1 を返した後、各呼び出しは順に `2 + 1 = 3`、`3 + 3 = 6`、`4 + 6 = 10` を得ます。 + 2. 引数 `n` は `4 → 3 → 2 → 1` の順に変化します。 + 最も深い呼び出しが 1 を返した後、各呼び出しは順に `2 + 1 = 3`、`3 + 3 = 6`、`4 + 6 = 10` を得ます。 最も深い呼び出しに到達した時点では、4 回の関数呼び出しはどれもまだ終了していません。 3. どちらのコードも、$n$ に比例する回数のループまたは呼び出しを行うため、時間計算量はともに $O(n)$ です。 @@ -47,21 +37,8 @@ def sum_recur(n): 次の 3 つのコード片はいずれも、正の整数 $n$ を入力とします。時間計算量が小さい順に並べ、それぞれの計算量を書いてください。 -```python -# コード片 1 -s = 0 -for i in range(n): - s += i - -# コード片 2 -s = 0 -for i in range(n): - for j in range(i, n): - s += j - -# コード片 3 -while n > 1: - n = n // 2 +```src +[file]{complexity_exercises}-[class]{}-[func]{linear_loop} ``` ??? success "解答" diff --git a/ja/docs/chapter_divide_and_conquer/exercises.md b/ja/docs/chapter_divide_and_conquer/exercises.md index e7b469539..af45a70f0 100644 --- a/ja/docs/chapter_divide_and_conquer/exercises.md +++ b/ja/docs/chapter_divide_and_conquer/exercises.md @@ -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` として、この関数で結果を計算します。 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 回呼び出すと、大量の重複計算が発生します。 diff --git a/ru/codes/c/chapter_computational_complexity/CMakeLists.txt b/ru/codes/c/chapter_computational_complexity/CMakeLists.txt index dcfa063c3..3d2450c26 100644 --- a/ru/codes/c/chapter_computational_complexity/CMakeLists.txt +++ b/ru/codes/c/chapter_computational_complexity/CMakeLists.txt @@ -3,3 +3,4 @@ add_executable(recursion recursion.c) add_executable(time_complexity time_complexity.c) add_executable(worst_best_time_complexity worst_best_time_complexity.c) add_executable(space_complexity space_complexity.c) +add_executable(complexity_exercises complexity_exercises.c) diff --git a/ru/codes/c/chapter_computational_complexity/complexity_exercises.c b/ru/codes/c/chapter_computational_complexity/complexity_exercises.c new file mode 100644 index 000000000..0cfb33c39 --- /dev/null +++ b/ru/codes/c/chapter_computational_complexity/complexity_exercises.c @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* Итеративное суммирование */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* Рекурсивное суммирование */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* Цикл линейной сложности */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* Цикл квадратичной сложности */ +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; +} + +/* Цикл логарифмической сложности */ +int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; +} + +int main(void) { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/ru/codes/c/chapter_divide_and_conquer/CMakeLists.txt b/ru/codes/c/chapter_divide_and_conquer/CMakeLists.txt index e03b1c588..31352a138 100644 --- a/ru/codes/c/chapter_divide_and_conquer/CMakeLists.txt +++ b/ru/codes/c/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.c) add_executable(build_tree build_tree.c) add_executable(hanota hanota.c) +add_executable(fast_power fast_power.c) diff --git a/ru/codes/c/chapter_divide_and_conquer/fast_power.c b/ru/codes/c/chapter_divide_and_conquer/fast_power.c new file mode 100644 index 000000000..712deee43 --- /dev/null +++ b/ru/codes/c/chapter_divide_and_conquer/fast_power.c @@ -0,0 +1,26 @@ +/** + * File: fast_power.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* Быстрое возведение в степень */ +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; +} + +int main(void) { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/ru/codes/cpp/chapter_computational_complexity/CMakeLists.txt b/ru/codes/cpp/chapter_computational_complexity/CMakeLists.txt index ea2845b75..536935b68 100644 --- a/ru/codes/cpp/chapter_computational_complexity/CMakeLists.txt +++ b/ru/codes/cpp/chapter_computational_complexity/CMakeLists.txt @@ -2,4 +2,5 @@ add_executable(iteration iteration.cpp) add_executable(recursion recursion.cpp) add_executable(space_complexity space_complexity.cpp) add_executable(time_complexity time_complexity.cpp) -add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) \ No newline at end of file +add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) +add_executable(complexity_exercises complexity_exercises.cpp) diff --git a/ru/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp b/ru/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp new file mode 100644 index 000000000..dca3d0eb5 --- /dev/null +++ b/ru/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* Итеративное суммирование */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; ++i) { + res += i; + } + return res; +} + +/* Рекурсивное суммирование */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* Цикл линейной сложности */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; ++i) { + res += i; + } + return res; +} + +/* Цикл квадратичной сложности */ +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; +} + +/* Цикл логарифмической сложности */ +int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; +} + +int main() { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/ru/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt b/ru/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt index 38dfff710..8e66f77b5 100644 --- a/ru/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt +++ b/ru/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.cpp) add_executable(build_tree build_tree.cpp) -add_executable(hanota hanota.cpp) \ No newline at end of file +add_executable(hanota hanota.cpp) +add_executable(fast_power fast_power.cpp) diff --git a/ru/codes/cpp/chapter_divide_and_conquer/fast_power.cpp b/ru/codes/cpp/chapter_divide_and_conquer/fast_power.cpp new file mode 100644 index 000000000..427b8de9f --- /dev/null +++ b/ru/codes/cpp/chapter_divide_and_conquer/fast_power.cpp @@ -0,0 +1,26 @@ +/** + * File: fast_power.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* Быстрое возведение в степень */ +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; +} + +int main() { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/ru/codes/csharp/chapter_computational_complexity/complexity_exercises.cs b/ru/codes/csharp/chapter_computational_complexity/complexity_exercises.cs new file mode 100644 index 000000000..81b6bc591 --- /dev/null +++ b/ru/codes/csharp/chapter_computational_complexity/complexity_exercises.cs @@ -0,0 +1,66 @@ +/** + * File: complexity_exercises.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_computational_complexity; + +public class complexity_exercises { + /* Итеративное суммирование */ + int SumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* Рекурсивное суммирование */ + int SumRecur(int n) { + if (n == 1) { + return 1; + } + return n + SumRecur(n - 1); + } + + /* Цикл линейной сложности */ + int LinearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* Цикл квадратичной сложности */ + 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; + } + + /* Цикл логарифмической сложности */ + int LogarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + [Test] + public void Test() { + Assert.That(SumIter(1), Is.EqualTo(1)); + Assert.That(SumRecur(1), Is.EqualTo(1)); + Assert.That(SumIter(4), Is.EqualTo(10)); + Assert.That(SumRecur(4), Is.EqualTo(10)); + Assert.That(LinearLoop(4), Is.EqualTo(6)); + Assert.That(QuadraticLoop(4), Is.EqualTo(20)); + Assert.That(LogarithmicLoop(4), Is.EqualTo(1)); + Assert.That(LogarithmicLoop(5), Is.EqualTo(1)); + } +} diff --git a/ru/codes/csharp/chapter_divide_and_conquer/fast_power.cs b/ru/codes/csharp/chapter_divide_and_conquer/fast_power.cs new file mode 100644 index 000000000..2b47d9303 --- /dev/null +++ b/ru/codes/csharp/chapter_divide_and_conquer/fast_power.cs @@ -0,0 +1,28 @@ +/** + * File: fast_power.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_divide_and_conquer; + +public class fast_power { + /* Быстрое возведение в степень */ + 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; + } + + [Test] + public void Test() { + Assert.That(FastPow(7, 0), Is.EqualTo(1)); + Assert.That(FastPow(3, 5), Is.EqualTo(243)); + Assert.That(FastPow(2, 6), Is.EqualTo(64)); + } +} diff --git a/ru/codes/dart/chapter_computational_complexity/complexity_exercises.dart b/ru/codes/dart/chapter_computational_complexity/complexity_exercises.dart new file mode 100644 index 000000000..4ad26807a --- /dev/null +++ b/ru/codes/dart/chapter_computational_complexity/complexity_exercises.dart @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* Итеративное суммирование */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* Рекурсивное суммирование */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* Цикл линейной сложности */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* Цикл квадратичной сложности */ +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; +} + +/* Цикл логарифмической сложности */ +int logarithmicLoop(int n) { + while (n > 1) { + n ~/= 2; + } + return n; +} + +void main() { + if (sumIter(1) != 1 || + sumRecur(1) != 1 || + sumIter(4) != 10 || + sumRecur(4) != 10 || + linearLoop(4) != 6 || + quadraticLoop(4) != 20 || + logarithmicLoop(4) != 1 || + logarithmicLoop(5) != 1) { + throw StateError('complexity exercise check failed'); + } +} diff --git a/ru/codes/dart/chapter_divide_and_conquer/fast_power.dart b/ru/codes/dart/chapter_divide_and_conquer/fast_power.dart new file mode 100644 index 000000000..8e3666eba --- /dev/null +++ b/ru/codes/dart/chapter_divide_and_conquer/fast_power.dart @@ -0,0 +1,23 @@ +/** + * File: fast_power.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* Быстрое возведение в степень */ +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; +} + +void main() { + if (fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64) { + throw StateError('fast power check failed'); + } +} diff --git a/ru/codes/go/chapter_computational_complexity/complexity_exercises.go b/ru/codes/go/chapter_computational_complexity/complexity_exercises.go new file mode 100644 index 000000000..8324d63ee --- /dev/null +++ b/ru/codes/go/chapter_computational_complexity/complexity_exercises.go @@ -0,0 +1,50 @@ +// File: complexity_exercises.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +/* Итеративное суммирование */ +func sumIter(n int) int { + res := 0 + for i := 1; i <= n; i++ { + res += i + } + return res +} + +/* Рекурсивное суммирование */ +func sumRecur(n int) int { + if n == 1 { + return 1 + } + return n + sumRecur(n-1) +} + +/* Цикл линейной сложности */ +func linearLoop(n int) int { + res := 0 + for i := 0; i < n; i++ { + res += i + } + return res +} + +/* Цикл квадратичной сложности */ +func quadraticLoop(n int) int { + res := 0 + for i := 0; i < n; i++ { + for j := i; j < n; j++ { + res += j + } + } + return res +} + +/* Цикл логарифмической сложности */ +func logarithmicLoop(n int) int { + for n > 1 { + n /= 2 + } + return n +} diff --git a/ru/codes/go/chapter_computational_complexity/complexity_exercises_test.go b/ru/codes/go/chapter_computational_complexity/complexity_exercises_test.go new file mode 100644 index 000000000..5e07da9bc --- /dev/null +++ b/ru/codes/go/chapter_computational_complexity/complexity_exercises_test.go @@ -0,0 +1,22 @@ +// File: complexity_exercises_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +import "testing" + +func TestComplexityExercises(t *testing.T) { + if sumIter(1) != 1 || sumRecur(1) != 1 { + t.Fatal("sum functions failed for n = 1") + } + if sumIter(4) != 10 || sumRecur(4) != 10 { + t.Fatal("sum functions failed for n = 4") + } + if linearLoop(4) != 6 || quadraticLoop(4) != 20 { + t.Fatal("complexity loops returned an unexpected value") + } + if logarithmicLoop(4) != 1 || logarithmicLoop(5) != 1 { + t.Fatal("logarithmic loop returned an unexpected value") + } +} diff --git a/ru/codes/go/chapter_divide_and_conquer/fast_power.go b/ru/codes/go/chapter_divide_and_conquer/fast_power.go new file mode 100644 index 000000000..4dc6eb17f --- /dev/null +++ b/ru/codes/go/chapter_divide_and_conquer/fast_power.go @@ -0,0 +1,17 @@ +// File: fast_power.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +/* Быстрое возведение в степень */ +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 +} diff --git a/ru/codes/go/chapter_divide_and_conquer/fast_power_test.go b/ru/codes/go/chapter_divide_and_conquer/fast_power_test.go new file mode 100644 index 000000000..38318718b --- /dev/null +++ b/ru/codes/go/chapter_divide_and_conquer/fast_power_test.go @@ -0,0 +1,13 @@ +// File: fast_power_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +import "testing" + +func TestFastPower(t *testing.T) { + if fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64 { + t.Fatal("fast power returned an unexpected value") + } +} diff --git a/ru/codes/java/chapter_computational_complexity/complexity_exercises.java b/ru/codes/java/chapter_computational_complexity/complexity_exercises.java new file mode 100644 index 000000000..dd8649a3b --- /dev/null +++ b/ru/codes/java/chapter_computational_complexity/complexity_exercises.java @@ -0,0 +1,62 @@ +/** + * File: complexity_exercises.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity; + +public class complexity_exercises { + /* Итеративное суммирование */ + static int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* Рекурсивное суммирование */ + static int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); + } + + /* Цикл линейной сложности */ + static int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* Цикл квадратичной сложности */ + static 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; + } + + /* Цикл логарифмической сложности */ + static int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + public static void main(String[] args) { + assert sumIter(1) == 1 && sumRecur(1) == 1; + assert sumIter(4) == 10 && sumRecur(4) == 10; + assert linearLoop(4) == 6; + assert quadraticLoop(4) == 20; + assert logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1; + } +} diff --git a/ru/codes/java/chapter_divide_and_conquer/fast_power.java b/ru/codes/java/chapter_divide_and_conquer/fast_power.java new file mode 100644 index 000000000..c51066804 --- /dev/null +++ b/ru/codes/java/chapter_divide_and_conquer/fast_power.java @@ -0,0 +1,27 @@ +/** + * File: fast_power.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer; + +public class fast_power { + /* Быстрое возведение в степень */ + static 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; + } + + public static void main(String[] args) { + assert fastPow(7, 0) == 1; + assert fastPow(3, 5) == 243; + assert fastPow(2, 6) == 64; + } +} diff --git a/ru/codes/javascript/chapter_computational_complexity/complexity_exercises.js b/ru/codes/javascript/chapter_computational_complexity/complexity_exercises.js new file mode 100644 index 000000000..d1f60dc5b --- /dev/null +++ b/ru/codes/javascript/chapter_computational_complexity/complexity_exercises.js @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* Итеративное суммирование */ +function sumIter(n) { + let res = 0; + for (let i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* Рекурсивное суммирование */ +function sumRecur(n) { + if (n === 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* Цикл линейной сложности */ +function linearLoop(n) { + let res = 0; + for (let i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* Цикл квадратичной сложности */ +function quadraticLoop(n) { + let res = 0; + for (let i = 0; i < n; i++) { + for (let j = i; j < n; j++) { + res += j; + } + } + return res; +} + +/* Цикл логарифмической сложности */ +function logarithmicLoop(n) { + while (n > 1) { + n = Math.floor(n / 2); + } + return n; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} diff --git a/ru/codes/javascript/chapter_divide_and_conquer/fast_power.js b/ru/codes/javascript/chapter_divide_and_conquer/fast_power.js new file mode 100644 index 000000000..0d4a61cad --- /dev/null +++ b/ru/codes/javascript/chapter_divide_and_conquer/fast_power.js @@ -0,0 +1,21 @@ +/** + * File: fast_power.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* Быстрое возведение в степень */ +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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} diff --git a/ru/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt b/ru/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt new file mode 100644 index 000000000..cdcbe4b5f --- /dev/null +++ b/ru/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity.complexity_exercises + +/* Итеративное суммирование */ +fun sumIter(n: Int): Int { + var res = 0 + for (i in 1..n) { + res += i + } + return res +} + +/* Рекурсивное суммирование */ +fun sumRecur(n: Int): Int { + if (n == 1) { + return 1 + } + return n + sumRecur(n - 1) +} + +/* Цикл линейной сложности */ +fun linearLoop(n: Int): Int { + var res = 0 + for (i in 0 until n) { + res += i + } + return res +} + +/* Цикл квадратичной сложности */ +fun quadraticLoop(n: Int): Int { + var res = 0 + for (i in 0 until n) { + for (j in i until n) { + res += j + } + } + return res +} + +/* Цикл логарифмической сложности */ +fun logarithmicLoop(n: Int): Int { + var value = n + while (value > 1) { + value /= 2 + } + return value +} + +fun main() { + check(sumIter(1) == 1 && sumRecur(1) == 1) + check(sumIter(4) == 10 && sumRecur(4) == 10) + check(linearLoop(4) == 6) + check(quadraticLoop(4) == 20) + check(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1) +} diff --git a/ru/codes/kotlin/chapter_divide_and_conquer/fast_power.kt b/ru/codes/kotlin/chapter_divide_and_conquer/fast_power.kt new file mode 100644 index 000000000..8c261e523 --- /dev/null +++ b/ru/codes/kotlin/chapter_divide_and_conquer/fast_power.kt @@ -0,0 +1,25 @@ +/** + * File: fast_power.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer.fast_power + +/* Быстрое возведение в степень */ +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 +} + +fun main() { + check(fastPow(7, 0) == 1) + check(fastPow(3, 5) == 243) + check(fastPow(2, 6) == 64) +} diff --git a/ru/codes/python/chapter_computational_complexity/complexity_exercises.py b/ru/codes/python/chapter_computational_complexity/complexity_exercises.py new file mode 100644 index 000000000..228decc1a --- /dev/null +++ b/ru/codes/python/chapter_computational_complexity/complexity_exercises.py @@ -0,0 +1,52 @@ +""" +File: complexity_exercises.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +def sum_iter(n: int) -> int: + """Итеративное суммирование""" + res = 0 + for i in range(1, n + 1): + res += i + return res + + +def sum_recur(n: int) -> int: + """Рекурсивное суммирование""" + if n == 1: + return 1 + return n + sum_recur(n - 1) + + +def linear_loop(n: int) -> int: + """Цикл линейной сложности""" + res = 0 + for i in range(n): + res += i + return res + + +def quadratic_loop(n: int) -> int: + """Цикл квадратичной сложности""" + res = 0 + for i in range(n): + for j in range(i, n): + res += j + return res + + +def logarithmic_loop(n: int) -> int: + """Цикл логарифмической сложности""" + while n > 1: + n //= 2 + return n + + +if __name__ == "__main__": + assert sum_iter(1) == sum_recur(1) == 1 + assert sum_iter(4) == sum_recur(4) == 10 + assert linear_loop(4) == 6 + assert quadratic_loop(4) == 20 + assert logarithmic_loop(4) == logarithmic_loop(5) == 1 diff --git a/ru/codes/python/chapter_divide_and_conquer/fast_power.py b/ru/codes/python/chapter_divide_and_conquer/fast_power.py new file mode 100644 index 000000000..2c961fbeb --- /dev/null +++ b/ru/codes/python/chapter_divide_and_conquer/fast_power.py @@ -0,0 +1,21 @@ +""" +File: fast_power.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +def fast_pow(x: int, n: int) -> int: + """Быстрое возведение в степень""" + if n == 0: + return 1 + half = fast_pow(x, n // 2) + if n % 2 == 0: + return half * half + return half * half * x + + +if __name__ == "__main__": + assert fast_pow(7, 0) == 1 + assert fast_pow(3, 5) == 243 + assert fast_pow(2, 6) == 64 diff --git a/ru/codes/ruby/chapter_computational_complexity/complexity_exercises.rb b/ru/codes/ruby/chapter_computational_complexity/complexity_exercises.rb new file mode 100644 index 000000000..b0bb95b77 --- /dev/null +++ b/ru/codes/ruby/chapter_computational_complexity/complexity_exercises.rb @@ -0,0 +1,55 @@ +=begin +File: complexity_exercises.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### Итеративное суммирование ### +def sum_iter(n) + res = 0 + for i in 1..n + res += i + end + res +end + +### Рекурсивное суммирование ### +def sum_recur(n) + return 1 if n == 1 + + n + sum_recur(n - 1) +end + +### Цикл линейной сложности ### +def linear_loop(n) + res = 0 + for i in 0...n + res += i + end + res +end + +### Цикл квадратичной сложности ### +def quadratic_loop(n) + res = 0 + for i in 0...n + for j in i...n + res += j + end + end + res +end + +### Цикл логарифмической сложности ### +def logarithmic_loop(n) + n /= 2 while n > 1 + n +end + +if __FILE__ == $0 + raise 'sum check failed' unless sum_iter(1) == 1 && sum_recur(1) == 1 + raise 'sum check failed' unless sum_iter(4) == 10 && sum_recur(4) == 10 + raise 'linear check failed' unless linear_loop(4) == 6 + raise 'quadratic check failed' unless quadratic_loop(4) == 20 + raise 'logarithmic check failed' unless logarithmic_loop(4) == 1 && logarithmic_loop(5) == 1 +end diff --git a/ru/codes/ruby/chapter_divide_and_conquer/fast_power.rb b/ru/codes/ruby/chapter_divide_and_conquer/fast_power.rb new file mode 100644 index 000000000..cc6b13a2a --- /dev/null +++ b/ru/codes/ruby/chapter_divide_and_conquer/fast_power.rb @@ -0,0 +1,21 @@ +=begin +File: fast_power.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### Быстрое возведение в степень ### +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 + +if __FILE__ == $0 + raise 'fast power check failed' unless fast_pow(7, 0) == 1 + raise 'fast power check failed' unless fast_pow(3, 5) == 243 + raise 'fast power check failed' unless fast_pow(2, 6) == 64 +end diff --git a/ru/codes/rust/Cargo.toml b/ru/codes/rust/Cargo.toml index 160f9134c..147947168 100644 --- a/ru/codes/rust/Cargo.toml +++ b/ru/codes/rust/Cargo.toml @@ -4,6 +4,16 @@ version = "0.1.0" edition = "2021" publish = false +# Run Command: cargo run --bin complexity_exercises +[[bin]] +name = "complexity_exercises" +path = "chapter_computational_complexity/complexity_exercises.rs" + +# Run Command: cargo run --bin fast_power +[[bin]] +name = "fast_power" +path = "chapter_divide_and_conquer/fast_power.rs" + # Run Command: cargo run --bin time_complexity [[bin]] name = "time_complexity" diff --git a/ru/codes/rust/chapter_computational_complexity/complexity_exercises.rs b/ru/codes/rust/chapter_computational_complexity/complexity_exercises.rs new file mode 100644 index 000000000..14449920b --- /dev/null +++ b/ru/codes/rust/chapter_computational_complexity/complexity_exercises.rs @@ -0,0 +1,61 @@ +/* + * File: complexity_exercises.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* Итеративное суммирование */ +fn sum_iter(n: i32) -> i32 { + let mut res = 0; + for i in 1..=n { + res += i; + } + res +} + +/* Рекурсивное суммирование */ +fn sum_recur(n: i32) -> i32 { + if n == 1 { + return 1; + } + n + sum_recur(n - 1) +} + +/* Цикл линейной сложности */ +fn linear_loop(n: i32) -> i32 { + let mut res = 0; + for i in 0..n { + res += i; + } + res +} + +/* Цикл квадратичной сложности */ +fn quadratic_loop(n: i32) -> i32 { + let mut res = 0; + for i in 0..n { + for j in i..n { + res += j; + } + } + res +} + +/* Цикл логарифмической сложности */ +fn logarithmic_loop(mut n: i32) -> i32 { + while n > 1 { + n /= 2; + } + n +} + +fn main() { + assert_eq!(sum_iter(1), 1); + assert_eq!(sum_recur(1), 1); + assert_eq!(sum_iter(4), 10); + assert_eq!(sum_recur(4), 10); + assert_eq!(linear_loop(4), 6); + assert_eq!(quadratic_loop(4), 20); + assert_eq!(logarithmic_loop(4), 1); + assert_eq!(logarithmic_loop(5), 1); +} diff --git a/ru/codes/rust/chapter_divide_and_conquer/fast_power.rs b/ru/codes/rust/chapter_divide_and_conquer/fast_power.rs new file mode 100644 index 000000000..e550504b9 --- /dev/null +++ b/ru/codes/rust/chapter_divide_and_conquer/fast_power.rs @@ -0,0 +1,23 @@ +/* + * File: fast_power.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* Быстрое возведение в степень */ +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 +} + +fn main() { + assert_eq!(fast_pow(7, 0), 1); + assert_eq!(fast_pow(3, 5), 243); + assert_eq!(fast_pow(2, 6), 64); +} diff --git a/ru/codes/swift/Package.swift b/ru/codes/swift/Package.swift index 5326dc138..8ccb78ab8 100644 --- a/ru/codes/swift/Package.swift +++ b/ru/codes/swift/Package.swift @@ -11,6 +11,7 @@ let package = Package( .executable(name: "time_complexity", targets: ["time_complexity"]), .executable(name: "worst_best_time_complexity", targets: ["worst_best_time_complexity"]), .executable(name: "space_complexity", targets: ["space_complexity"]), + .executable(name: "complexity_exercises", targets: ["complexity_exercises"]), // chapter_array_and_linkedlist .executable(name: "array", targets: ["array"]), .executable(name: "linked_list", targets: ["linked_list"]), @@ -70,6 +71,7 @@ let package = Package( .executable(name: "binary_search_recur", targets: ["binary_search_recur"]), .executable(name: "build_tree", targets: ["build_tree"]), .executable(name: "hanota", targets: ["hanota"]), + .executable(name: "fast_power", targets: ["fast_power"]), // chapter_backtracking .executable(name: "preorder_traversal_i_compact", targets: ["preorder_traversal_i_compact"]), .executable(name: "preorder_traversal_ii_compact", targets: ["preorder_traversal_ii_compact"]), @@ -114,6 +116,7 @@ let package = Package( .executableTarget(name: "time_complexity", path: "chapter_computational_complexity", sources: ["time_complexity.swift"]), .executableTarget(name: "worst_best_time_complexity", path: "chapter_computational_complexity", sources: ["worst_best_time_complexity.swift"]), .executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]), + .executableTarget(name: "complexity_exercises", path: "chapter_computational_complexity", sources: ["complexity_exercises.swift"]), // chapter_array_and_linkedlist .executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]), .executableTarget(name: "linked_list", dependencies: ["utils"], path: "chapter_array_and_linkedlist", sources: ["linked_list.swift"]), @@ -173,6 +176,7 @@ let package = Package( .executableTarget(name: "binary_search_recur", path: "chapter_divide_and_conquer", sources: ["binary_search_recur.swift"]), .executableTarget(name: "build_tree", dependencies: ["utils"], path: "chapter_divide_and_conquer", sources: ["build_tree.swift"]), .executableTarget(name: "hanota", path: "chapter_divide_and_conquer", sources: ["hanota.swift"]), + .executableTarget(name: "fast_power", path: "chapter_divide_and_conquer", sources: ["fast_power.swift"]), // chapter_backtracking .executableTarget(name: "preorder_traversal_i_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_i_compact.swift"]), .executableTarget(name: "preorder_traversal_ii_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_ii_compact.swift"]), diff --git a/ru/codes/swift/chapter_computational_complexity/complexity_exercises.swift b/ru/codes/swift/chapter_computational_complexity/complexity_exercises.swift new file mode 100644 index 000000000..6daa2bd8f --- /dev/null +++ b/ru/codes/swift/chapter_computational_complexity/complexity_exercises.swift @@ -0,0 +1,62 @@ +/** + File: complexity_exercises.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* Итеративное суммирование */ +func sumIter(n: Int) -> Int { + var res = 0 + for i in 1 ... n { + res += i + } + return res +} + +/* Рекурсивное суммирование */ +func sumRecur(n: Int) -> Int { + if n == 1 { + return 1 + } + return n + sumRecur(n: n - 1) +} + +/* Цикл линейной сложности */ +func linearLoop(n: Int) -> Int { + var res = 0 + for i in 0 ..< n { + res += i + } + return res +} + +/* Цикл квадратичной сложности */ +func quadraticLoop(n: Int) -> Int { + var res = 0 + for i in 0 ..< n { + for j in i ..< n { + res += j + } + } + return res +} + +/* Цикл логарифмической сложности */ +func logarithmicLoop(n: Int) -> Int { + var n = n + while n > 1 { + n /= 2 + } + return n +} + +@main +enum ComplexityExercises { + static func main() { + assert(sumIter(n: 1) == 1 && sumRecur(n: 1) == 1) + assert(sumIter(n: 4) == 10 && sumRecur(n: 4) == 10) + assert(linearLoop(n: 4) == 6) + assert(quadraticLoop(n: 4) == 20) + assert(logarithmicLoop(n: 4) == 1 && logarithmicLoop(n: 5) == 1) + } +} diff --git a/ru/codes/swift/chapter_divide_and_conquer/fast_power.swift b/ru/codes/swift/chapter_divide_and_conquer/fast_power.swift new file mode 100644 index 000000000..f7a552a92 --- /dev/null +++ b/ru/codes/swift/chapter_divide_and_conquer/fast_power.swift @@ -0,0 +1,26 @@ +/** + File: fast_power.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* Быстрое возведение в степень */ +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 +} + +@main +enum FastPower { + static func main() { + assert(fastPow(x: 7, n: 0) == 1) + assert(fastPow(x: 3, n: 5) == 243) + assert(fastPow(x: 2, n: 6) == 64) + } +} diff --git a/ru/codes/typescript/chapter_computational_complexity/complexity_exercises.ts b/ru/codes/typescript/chapter_computational_complexity/complexity_exercises.ts new file mode 100644 index 000000000..5f2506382 --- /dev/null +++ b/ru/codes/typescript/chapter_computational_complexity/complexity_exercises.ts @@ -0,0 +1,65 @@ +/** + * File: complexity_exercises.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* Итеративное суммирование */ +function sumIter(n: number): number { + let res = 0; + for (let i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* Рекурсивное суммирование */ +function sumRecur(n: number): number { + if (n === 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* Цикл линейной сложности */ +function linearLoop(n: number): number { + let res = 0; + for (let i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* Цикл квадратичной сложности */ +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; +} + +/* Цикл логарифмической сложности */ +function logarithmicLoop(n: number): number { + while (n > 1) { + n = Math.floor(n / 2); + } + return n; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} + +export {}; diff --git a/ru/codes/typescript/chapter_divide_and_conquer/fast_power.ts b/ru/codes/typescript/chapter_divide_and_conquer/fast_power.ts new file mode 100644 index 000000000..1aea497f3 --- /dev/null +++ b/ru/codes/typescript/chapter_divide_and_conquer/fast_power.ts @@ -0,0 +1,23 @@ +/** + * File: fast_power.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* Быстрое возведение в степень */ +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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} + +export {}; diff --git a/ru/docs/chapter_computational_complexity/exercises.md b/ru/docs/chapter_computational_complexity/exercises.md index a88f2f9d8..53cf2ea51 100644 --- a/ru/docs/chapter_computational_complexity/exercises.md +++ b/ru/docs/chapter_computational_complexity/exercises.md @@ -7,33 +7,23 @@ Обе функции ниже вычисляют $1 + 2 + \dots + n$ (считайте, что $n \ge 1$). Присвойте `n` значение 4, ответьте на вопросы в порядке фактического выполнения программы, а затем сравните эффективность двух вариантов. -```python -def sum_iter(n): - s = 0 - for i in range(1, n + 1): - s += i - return s - -def sum_recur(n): - if n == 1: - return 1 - return n + sum_recur(n - 1) +```src +[file]{complexity_exercises}-[class]{}-[func]{sum_iter} ``` -1. Какие значения принимает переменная `s` после каждой итерации при выполнении `sum_iter(4)`? -2. Какие функции поочередно вызываются при выполнении `sum_recur(4)`? Как формируется результат при возврате, начиная с самого глубокого вызова? +1. Какие значения принимает переменная-аккумулятор `res` после каждой итерации при выполнении итеративной функции с `n = 4`? +2. Какие значения поочередно принимает параметр `n` при выполнении рекурсивной функции с `n = 4`? Как формируется результат при возврате, начиная с самого глубокого вызова? 3. Каковы временная и пространственная сложности каждого варианта? Обоснуйте ответ, опираясь на процессы выполнения из вопросов 1 и 2. ??? success "Ответ" - 1. Переменная цикла `i` поочередно принимает значения `1, 2, 3, 4`, а `s` после каждой итерации становится равной - `1, 3, 6, 10`. Поэтому `sum_iter(4)` возвращает 10. + 1. Переменная цикла `i` поочередно принимает значения `1, 2, 3, 4`, а `res` после каждой итерации становится равной + `1, 3, 6, 10`. Поэтому итеративная функция возвращает 10. - 2. Функции вызываются в следующем порядке: - `sum_recur(4) → sum_recur(3) → sum_recur(2) → sum_recur(1)`. - `sum_recur(1)` возвращает 1, после чего следующие уровни поочередно получают `2 + 1 = 3`, `3 + 3 = 6` и `4 + 6 = 10`. + 2. Параметр `n` принимает значения `4 → 3 → 2 → 1`. + Самый глубокий вызов возвращает 1, после чего следующие уровни поочередно получают `2 + 1 = 3`, `3 + 3 = 6` и `4 + 6 = 10`. В самой глубокой точке все 4 вызова функции еще не завершены. 3. В обеих функциях число итераций или вызовов пропорционально $n$, поэтому их временная сложность равна $O(n)$. @@ -47,21 +37,8 @@ def sum_recur(n): Во всех трех фрагментах кода входные данные — положительное целое число $n$. Расположите фрагменты в порядке возрастания временной сложности и укажите сложность каждого из них. -```python -# Фрагмент 1 -s = 0 -for i in range(n): - s += i - -# Фрагмент 2 -s = 0 -for i in range(n): - for j in range(i, n): - s += j - -# Фрагмент 3 -while n > 1: - n = n // 2 +```src +[file]{complexity_exercises}-[class]{}-[func]{linear_loop} ``` ??? success "Ответ" diff --git a/ru/docs/chapter_divide_and_conquer/exercises.md b/ru/docs/chapter_divide_and_conquer/exercises.md index 9b6c7efa5..37f74593b 100644 --- a/ru/docs/chapter_divide_and_conquer/exercises.md +++ b/ru/docs/chapter_divide_and_conquer/exercises.md @@ -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`, затем вычислите результат с помощью этой функции. 1. Какие значения последовательно принимает параметр `n` при рекурсивных вызовах? 2. Какие значения поочередно возвращаются на каждом уровне, начиная с самого глубокого? -3. Почему результат нужно сначала сохранить в `half`, а не дважды записывать `fast_pow(x, n // 2)`? +3. Почему результат рекурсии нужно сначала сохранить в `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)` по обе стороны умножения, два рекурсивных вызова будут решать одну и ту же подзадачу. + 3. Если вызвать одну и ту же подзадачу по одному разу с каждой стороны умножения, два рекурсивных вызова выполнят одинаковые вычисления. Когда результат сохраняется в `half`, на каждом уровне выполняется только один рекурсивный вызов, а глубина рекурсии составляет примерно $\log n$; два вызова привели бы к множеству повторных вычислений. diff --git a/zh-hant/codes/c/chapter_computational_complexity/CMakeLists.txt b/zh-hant/codes/c/chapter_computational_complexity/CMakeLists.txt index dcfa063c3..3d2450c26 100644 --- a/zh-hant/codes/c/chapter_computational_complexity/CMakeLists.txt +++ b/zh-hant/codes/c/chapter_computational_complexity/CMakeLists.txt @@ -3,3 +3,4 @@ add_executable(recursion recursion.c) add_executable(time_complexity time_complexity.c) add_executable(worst_best_time_complexity worst_best_time_complexity.c) add_executable(space_complexity space_complexity.c) +add_executable(complexity_exercises complexity_exercises.c) diff --git a/zh-hant/codes/c/chapter_computational_complexity/complexity_exercises.c b/zh-hant/codes/c/chapter_computational_complexity/complexity_exercises.c new file mode 100644 index 000000000..15664b995 --- /dev/null +++ b/zh-hant/codes/c/chapter_computational_complexity/complexity_exercises.c @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 迭代求和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 遞迴求和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線性階迴圈 */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 平方階迴圈 */ +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; +} + +/* 對數階迴圈 */ +int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; +} + +int main(void) { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/zh-hant/codes/c/chapter_divide_and_conquer/CMakeLists.txt b/zh-hant/codes/c/chapter_divide_and_conquer/CMakeLists.txt index e03b1c588..31352a138 100644 --- a/zh-hant/codes/c/chapter_divide_and_conquer/CMakeLists.txt +++ b/zh-hant/codes/c/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.c) add_executable(build_tree build_tree.c) add_executable(hanota hanota.c) +add_executable(fast_power fast_power.c) diff --git a/zh-hant/codes/c/chapter_divide_and_conquer/fast_power.c b/zh-hant/codes/c/chapter_divide_and_conquer/fast_power.c new file mode 100644 index 000000000..167539380 --- /dev/null +++ b/zh-hant/codes/c/chapter_divide_and_conquer/fast_power.c @@ -0,0 +1,26 @@ +/** + * File: fast_power.c + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 快速冪 */ +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; +} + +int main(void) { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/zh-hant/codes/cpp/chapter_computational_complexity/CMakeLists.txt b/zh-hant/codes/cpp/chapter_computational_complexity/CMakeLists.txt index ea2845b75..536935b68 100644 --- a/zh-hant/codes/cpp/chapter_computational_complexity/CMakeLists.txt +++ b/zh-hant/codes/cpp/chapter_computational_complexity/CMakeLists.txt @@ -2,4 +2,5 @@ add_executable(iteration iteration.cpp) add_executable(recursion recursion.cpp) add_executable(space_complexity space_complexity.cpp) add_executable(time_complexity time_complexity.cpp) -add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) \ No newline at end of file +add_executable(worst_best_time_complexity worst_best_time_complexity.cpp) +add_executable(complexity_exercises complexity_exercises.cpp) diff --git a/zh-hant/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp b/zh-hant/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp new file mode 100644 index 000000000..0b33517f8 --- /dev/null +++ b/zh-hant/codes/cpp/chapter_computational_complexity/complexity_exercises.cpp @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 迭代求和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; ++i) { + res += i; + } + return res; +} + +/* 遞迴求和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線性階迴圈 */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; ++i) { + res += i; + } + return res; +} + +/* 平方階迴圈 */ +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; +} + +/* 對數階迴圈 */ +int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; +} + +int main() { + assert(sumIter(1) == 1 && sumRecur(1) == 1); + assert(sumIter(4) == 10 && sumRecur(4) == 10); + assert(linearLoop(4) == 6); + assert(quadraticLoop(4) == 20); + assert(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1); + return 0; +} diff --git a/zh-hant/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt b/zh-hant/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt index 38dfff710..8e66f77b5 100644 --- a/zh-hant/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt +++ b/zh-hant/codes/cpp/chapter_divide_and_conquer/CMakeLists.txt @@ -1,3 +1,4 @@ add_executable(binary_search_recur binary_search_recur.cpp) add_executable(build_tree build_tree.cpp) -add_executable(hanota hanota.cpp) \ No newline at end of file +add_executable(hanota hanota.cpp) +add_executable(fast_power fast_power.cpp) diff --git a/zh-hant/codes/cpp/chapter_divide_and_conquer/fast_power.cpp b/zh-hant/codes/cpp/chapter_divide_and_conquer/fast_power.cpp new file mode 100644 index 000000000..3fbf0b5fa --- /dev/null +++ b/zh-hant/codes/cpp/chapter_divide_and_conquer/fast_power.cpp @@ -0,0 +1,26 @@ +/** + * File: fast_power.cpp + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +#include + +/* 快速冪 */ +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; +} + +int main() { + assert(fastPow(7, 0) == 1); + assert(fastPow(3, 5) == 243); + assert(fastPow(2, 6) == 64); + return 0; +} diff --git a/zh-hant/codes/csharp/chapter_computational_complexity/complexity_exercises.cs b/zh-hant/codes/csharp/chapter_computational_complexity/complexity_exercises.cs new file mode 100644 index 000000000..6a8d4eac4 --- /dev/null +++ b/zh-hant/codes/csharp/chapter_computational_complexity/complexity_exercises.cs @@ -0,0 +1,66 @@ +/** + * File: complexity_exercises.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_computational_complexity; + +public class complexity_exercises { + /* 迭代求和 */ + int SumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* 遞迴求和 */ + int SumRecur(int n) { + if (n == 1) { + return 1; + } + return n + SumRecur(n - 1); + } + + /* 線性階迴圈 */ + int LinearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* 平方階迴圈 */ + 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; + } + + /* 對數階迴圈 */ + int LogarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + [Test] + public void Test() { + Assert.That(SumIter(1), Is.EqualTo(1)); + Assert.That(SumRecur(1), Is.EqualTo(1)); + Assert.That(SumIter(4), Is.EqualTo(10)); + Assert.That(SumRecur(4), Is.EqualTo(10)); + Assert.That(LinearLoop(4), Is.EqualTo(6)); + Assert.That(QuadraticLoop(4), Is.EqualTo(20)); + Assert.That(LogarithmicLoop(4), Is.EqualTo(1)); + Assert.That(LogarithmicLoop(5), Is.EqualTo(1)); + } +} diff --git a/zh-hant/codes/csharp/chapter_divide_and_conquer/fast_power.cs b/zh-hant/codes/csharp/chapter_divide_and_conquer/fast_power.cs new file mode 100644 index 000000000..39731731b --- /dev/null +++ b/zh-hant/codes/csharp/chapter_divide_and_conquer/fast_power.cs @@ -0,0 +1,28 @@ +/** + * File: fast_power.cs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +namespace hello_algo.chapter_divide_and_conquer; + +public class fast_power { + /* 快速冪 */ + 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; + } + + [Test] + public void Test() { + Assert.That(FastPow(7, 0), Is.EqualTo(1)); + Assert.That(FastPow(3, 5), Is.EqualTo(243)); + Assert.That(FastPow(2, 6), Is.EqualTo(64)); + } +} diff --git a/zh-hant/codes/dart/chapter_computational_complexity/complexity_exercises.dart b/zh-hant/codes/dart/chapter_computational_complexity/complexity_exercises.dart new file mode 100644 index 000000000..7f1dff9f4 --- /dev/null +++ b/zh-hant/codes/dart/chapter_computational_complexity/complexity_exercises.dart @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 迭代求和 */ +int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 遞迴求和 */ +int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線性階迴圈 */ +int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 平方階迴圈 */ +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; +} + +/* 對數階迴圈 */ +int logarithmicLoop(int n) { + while (n > 1) { + n ~/= 2; + } + return n; +} + +void main() { + if (sumIter(1) != 1 || + sumRecur(1) != 1 || + sumIter(4) != 10 || + sumRecur(4) != 10 || + linearLoop(4) != 6 || + quadraticLoop(4) != 20 || + logarithmicLoop(4) != 1 || + logarithmicLoop(5) != 1) { + throw StateError('complexity exercise check failed'); + } +} diff --git a/zh-hant/codes/dart/chapter_divide_and_conquer/fast_power.dart b/zh-hant/codes/dart/chapter_divide_and_conquer/fast_power.dart new file mode 100644 index 000000000..3568e30ea --- /dev/null +++ b/zh-hant/codes/dart/chapter_divide_and_conquer/fast_power.dart @@ -0,0 +1,23 @@ +/** + * File: fast_power.dart + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 快速冪 */ +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; +} + +void main() { + if (fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64) { + throw StateError('fast power check failed'); + } +} diff --git a/zh-hant/codes/go/chapter_computational_complexity/complexity_exercises.go b/zh-hant/codes/go/chapter_computational_complexity/complexity_exercises.go new file mode 100644 index 000000000..d4f81221b --- /dev/null +++ b/zh-hant/codes/go/chapter_computational_complexity/complexity_exercises.go @@ -0,0 +1,50 @@ +// File: complexity_exercises.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +/* 迭代求和 */ +func sumIter(n int) int { + res := 0 + for i := 1; i <= n; i++ { + res += i + } + return res +} + +/* 遞迴求和 */ +func sumRecur(n int) int { + if n == 1 { + return 1 + } + return n + sumRecur(n-1) +} + +/* 線性階迴圈 */ +func linearLoop(n int) int { + res := 0 + for i := 0; i < n; i++ { + res += i + } + return res +} + +/* 平方階迴圈 */ +func quadraticLoop(n int) int { + res := 0 + for i := 0; i < n; i++ { + for j := i; j < n; j++ { + res += j + } + } + return res +} + +/* 對數階迴圈 */ +func logarithmicLoop(n int) int { + for n > 1 { + n /= 2 + } + return n +} diff --git a/zh-hant/codes/go/chapter_computational_complexity/complexity_exercises_test.go b/zh-hant/codes/go/chapter_computational_complexity/complexity_exercises_test.go new file mode 100644 index 000000000..5e07da9bc --- /dev/null +++ b/zh-hant/codes/go/chapter_computational_complexity/complexity_exercises_test.go @@ -0,0 +1,22 @@ +// File: complexity_exercises_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_computational_complexity + +import "testing" + +func TestComplexityExercises(t *testing.T) { + if sumIter(1) != 1 || sumRecur(1) != 1 { + t.Fatal("sum functions failed for n = 1") + } + if sumIter(4) != 10 || sumRecur(4) != 10 { + t.Fatal("sum functions failed for n = 4") + } + if linearLoop(4) != 6 || quadraticLoop(4) != 20 { + t.Fatal("complexity loops returned an unexpected value") + } + if logarithmicLoop(4) != 1 || logarithmicLoop(5) != 1 { + t.Fatal("logarithmic loop returned an unexpected value") + } +} diff --git a/zh-hant/codes/go/chapter_divide_and_conquer/fast_power.go b/zh-hant/codes/go/chapter_divide_and_conquer/fast_power.go new file mode 100644 index 000000000..e2d4d6a5a --- /dev/null +++ b/zh-hant/codes/go/chapter_divide_and_conquer/fast_power.go @@ -0,0 +1,17 @@ +// File: fast_power.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +/* 快速冪 */ +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 +} diff --git a/zh-hant/codes/go/chapter_divide_and_conquer/fast_power_test.go b/zh-hant/codes/go/chapter_divide_and_conquer/fast_power_test.go new file mode 100644 index 000000000..38318718b --- /dev/null +++ b/zh-hant/codes/go/chapter_divide_and_conquer/fast_power_test.go @@ -0,0 +1,13 @@ +// File: fast_power_test.go +// Created Time: 2026-08-18 +// Author: Hello Algo Team + +package chapter_divide_and_conquer + +import "testing" + +func TestFastPower(t *testing.T) { + if fastPow(7, 0) != 1 || fastPow(3, 5) != 243 || fastPow(2, 6) != 64 { + t.Fatal("fast power returned an unexpected value") + } +} diff --git a/zh-hant/codes/java/chapter_computational_complexity/complexity_exercises.java b/zh-hant/codes/java/chapter_computational_complexity/complexity_exercises.java new file mode 100644 index 000000000..14aefd101 --- /dev/null +++ b/zh-hant/codes/java/chapter_computational_complexity/complexity_exercises.java @@ -0,0 +1,62 @@ +/** + * File: complexity_exercises.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity; + +public class complexity_exercises { + /* 迭代求和 */ + static int sumIter(int n) { + int res = 0; + for (int i = 1; i <= n; i++) { + res += i; + } + return res; + } + + /* 遞迴求和 */ + static int sumRecur(int n) { + if (n == 1) { + return 1; + } + return n + sumRecur(n - 1); + } + + /* 線性階迴圈 */ + static int linearLoop(int n) { + int res = 0; + for (int i = 0; i < n; i++) { + res += i; + } + return res; + } + + /* 平方階迴圈 */ + static 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; + } + + /* 對數階迴圈 */ + static int logarithmicLoop(int n) { + while (n > 1) { + n /= 2; + } + return n; + } + + public static void main(String[] args) { + assert sumIter(1) == 1 && sumRecur(1) == 1; + assert sumIter(4) == 10 && sumRecur(4) == 10; + assert linearLoop(4) == 6; + assert quadraticLoop(4) == 20; + assert logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1; + } +} diff --git a/zh-hant/codes/java/chapter_divide_and_conquer/fast_power.java b/zh-hant/codes/java/chapter_divide_and_conquer/fast_power.java new file mode 100644 index 000000000..2288b7aa2 --- /dev/null +++ b/zh-hant/codes/java/chapter_divide_and_conquer/fast_power.java @@ -0,0 +1,27 @@ +/** + * File: fast_power.java + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer; + +public class fast_power { + /* 快速冪 */ + static 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; + } + + public static void main(String[] args) { + assert fastPow(7, 0) == 1; + assert fastPow(3, 5) == 243; + assert fastPow(2, 6) == 64; + } +} diff --git a/zh-hant/codes/javascript/chapter_computational_complexity/complexity_exercises.js b/zh-hant/codes/javascript/chapter_computational_complexity/complexity_exercises.js new file mode 100644 index 000000000..16336f314 --- /dev/null +++ b/zh-hant/codes/javascript/chapter_computational_complexity/complexity_exercises.js @@ -0,0 +1,63 @@ +/** + * File: complexity_exercises.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 迭代求和 */ +function sumIter(n) { + let res = 0; + for (let i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 遞迴求和 */ +function sumRecur(n) { + if (n === 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線性階迴圈 */ +function linearLoop(n) { + let res = 0; + for (let i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 平方階迴圈 */ +function quadraticLoop(n) { + let res = 0; + for (let i = 0; i < n; i++) { + for (let j = i; j < n; j++) { + res += j; + } + } + return res; +} + +/* 對數階迴圈 */ +function logarithmicLoop(n) { + while (n > 1) { + n = Math.floor(n / 2); + } + return n; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} diff --git a/zh-hant/codes/javascript/chapter_divide_and_conquer/fast_power.js b/zh-hant/codes/javascript/chapter_divide_and_conquer/fast_power.js new file mode 100644 index 000000000..cf55b6cfa --- /dev/null +++ b/zh-hant/codes/javascript/chapter_divide_and_conquer/fast_power.js @@ -0,0 +1,21 @@ +/** + * File: fast_power.js + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 快速冪 */ +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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} diff --git a/zh-hant/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt b/zh-hant/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt new file mode 100644 index 000000000..de93eb035 --- /dev/null +++ b/zh-hant/codes/kotlin/chapter_computational_complexity/complexity_exercises.kt @@ -0,0 +1,61 @@ +/** + * File: complexity_exercises.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_computational_complexity.complexity_exercises + +/* 迭代求和 */ +fun sumIter(n: Int): Int { + var res = 0 + for (i in 1..n) { + res += i + } + return res +} + +/* 遞迴求和 */ +fun sumRecur(n: Int): Int { + if (n == 1) { + return 1 + } + return n + sumRecur(n - 1) +} + +/* 線性階迴圈 */ +fun linearLoop(n: Int): Int { + var res = 0 + for (i in 0 until n) { + res += i + } + return res +} + +/* 平方階迴圈 */ +fun quadraticLoop(n: Int): Int { + var res = 0 + for (i in 0 until n) { + for (j in i until n) { + res += j + } + } + return res +} + +/* 對數階迴圈 */ +fun logarithmicLoop(n: Int): Int { + var value = n + while (value > 1) { + value /= 2 + } + return value +} + +fun main() { + check(sumIter(1) == 1 && sumRecur(1) == 1) + check(sumIter(4) == 10 && sumRecur(4) == 10) + check(linearLoop(4) == 6) + check(quadraticLoop(4) == 20) + check(logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1) +} diff --git a/zh-hant/codes/kotlin/chapter_divide_and_conquer/fast_power.kt b/zh-hant/codes/kotlin/chapter_divide_and_conquer/fast_power.kt new file mode 100644 index 000000000..666837c53 --- /dev/null +++ b/zh-hant/codes/kotlin/chapter_divide_and_conquer/fast_power.kt @@ -0,0 +1,25 @@ +/** + * File: fast_power.kt + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +package chapter_divide_and_conquer.fast_power + +/* 快速冪 */ +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 +} + +fun main() { + check(fastPow(7, 0) == 1) + check(fastPow(3, 5) == 243) + check(fastPow(2, 6) == 64) +} diff --git a/zh-hant/codes/python/chapter_computational_complexity/complexity_exercises.py b/zh-hant/codes/python/chapter_computational_complexity/complexity_exercises.py new file mode 100644 index 000000000..c19fb4ef4 --- /dev/null +++ b/zh-hant/codes/python/chapter_computational_complexity/complexity_exercises.py @@ -0,0 +1,52 @@ +""" +File: complexity_exercises.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +def sum_iter(n: int) -> int: + """迭代求和""" + res = 0 + for i in range(1, n + 1): + res += i + return res + + +def sum_recur(n: int) -> int: + """遞迴求和""" + if n == 1: + return 1 + return n + sum_recur(n - 1) + + +def linear_loop(n: int) -> int: + """線性階迴圈""" + res = 0 + for i in range(n): + res += i + return res + + +def quadratic_loop(n: int) -> int: + """平方階迴圈""" + res = 0 + for i in range(n): + for j in range(i, n): + res += j + return res + + +def logarithmic_loop(n: int) -> int: + """對數階迴圈""" + while n > 1: + n //= 2 + return n + + +if __name__ == "__main__": + assert sum_iter(1) == sum_recur(1) == 1 + assert sum_iter(4) == sum_recur(4) == 10 + assert linear_loop(4) == 6 + assert quadratic_loop(4) == 20 + assert logarithmic_loop(4) == logarithmic_loop(5) == 1 diff --git a/zh-hant/codes/python/chapter_divide_and_conquer/fast_power.py b/zh-hant/codes/python/chapter_divide_and_conquer/fast_power.py new file mode 100644 index 000000000..ad5f214b0 --- /dev/null +++ b/zh-hant/codes/python/chapter_divide_and_conquer/fast_power.py @@ -0,0 +1,21 @@ +""" +File: fast_power.py +Created Time: 2026-08-18 +Author: Hello Algo Team +""" + + +def fast_pow(x: int, n: int) -> int: + """快速冪""" + if n == 0: + return 1 + half = fast_pow(x, n // 2) + if n % 2 == 0: + return half * half + return half * half * x + + +if __name__ == "__main__": + assert fast_pow(7, 0) == 1 + assert fast_pow(3, 5) == 243 + assert fast_pow(2, 6) == 64 diff --git a/zh-hant/codes/ruby/chapter_computational_complexity/complexity_exercises.rb b/zh-hant/codes/ruby/chapter_computational_complexity/complexity_exercises.rb new file mode 100644 index 000000000..8ba441359 --- /dev/null +++ b/zh-hant/codes/ruby/chapter_computational_complexity/complexity_exercises.rb @@ -0,0 +1,55 @@ +=begin +File: complexity_exercises.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### 迭代求和 ### +def sum_iter(n) + res = 0 + for i in 1..n + res += i + end + res +end + +### 遞迴求和 ### +def sum_recur(n) + return 1 if n == 1 + + n + sum_recur(n - 1) +end + +### 線性階迴圈 ### +def linear_loop(n) + res = 0 + for i in 0...n + res += i + end + res +end + +### 平方階迴圈 ### +def quadratic_loop(n) + res = 0 + for i in 0...n + for j in i...n + res += j + end + end + res +end + +### 對數階迴圈 ### +def logarithmic_loop(n) + n /= 2 while n > 1 + n +end + +if __FILE__ == $0 + raise 'sum check failed' unless sum_iter(1) == 1 && sum_recur(1) == 1 + raise 'sum check failed' unless sum_iter(4) == 10 && sum_recur(4) == 10 + raise 'linear check failed' unless linear_loop(4) == 6 + raise 'quadratic check failed' unless quadratic_loop(4) == 20 + raise 'logarithmic check failed' unless logarithmic_loop(4) == 1 && logarithmic_loop(5) == 1 +end diff --git a/zh-hant/codes/ruby/chapter_divide_and_conquer/fast_power.rb b/zh-hant/codes/ruby/chapter_divide_and_conquer/fast_power.rb new file mode 100644 index 000000000..d8f067e11 --- /dev/null +++ b/zh-hant/codes/ruby/chapter_divide_and_conquer/fast_power.rb @@ -0,0 +1,21 @@ +=begin +File: fast_power.rb +Created Time: 2026-08-18 +Author: Hello Algo Team +=end + +### 快速冪 ### +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 + +if __FILE__ == $0 + raise 'fast power check failed' unless fast_pow(7, 0) == 1 + raise 'fast power check failed' unless fast_pow(3, 5) == 243 + raise 'fast power check failed' unless fast_pow(2, 6) == 64 +end diff --git a/zh-hant/codes/rust/Cargo.toml b/zh-hant/codes/rust/Cargo.toml index 160f9134c..147947168 100644 --- a/zh-hant/codes/rust/Cargo.toml +++ b/zh-hant/codes/rust/Cargo.toml @@ -4,6 +4,16 @@ version = "0.1.0" edition = "2021" publish = false +# Run Command: cargo run --bin complexity_exercises +[[bin]] +name = "complexity_exercises" +path = "chapter_computational_complexity/complexity_exercises.rs" + +# Run Command: cargo run --bin fast_power +[[bin]] +name = "fast_power" +path = "chapter_divide_and_conquer/fast_power.rs" + # Run Command: cargo run --bin time_complexity [[bin]] name = "time_complexity" diff --git a/zh-hant/codes/rust/chapter_computational_complexity/complexity_exercises.rs b/zh-hant/codes/rust/chapter_computational_complexity/complexity_exercises.rs new file mode 100644 index 000000000..1c5701168 --- /dev/null +++ b/zh-hant/codes/rust/chapter_computational_complexity/complexity_exercises.rs @@ -0,0 +1,61 @@ +/* + * File: complexity_exercises.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 迭代求和 */ +fn sum_iter(n: i32) -> i32 { + let mut res = 0; + for i in 1..=n { + res += i; + } + res +} + +/* 遞迴求和 */ +fn sum_recur(n: i32) -> i32 { + if n == 1 { + return 1; + } + n + sum_recur(n - 1) +} + +/* 線性階迴圈 */ +fn linear_loop(n: i32) -> i32 { + let mut res = 0; + for i in 0..n { + res += i; + } + res +} + +/* 平方階迴圈 */ +fn quadratic_loop(n: i32) -> i32 { + let mut res = 0; + for i in 0..n { + for j in i..n { + res += j; + } + } + res +} + +/* 對數階迴圈 */ +fn logarithmic_loop(mut n: i32) -> i32 { + while n > 1 { + n /= 2; + } + n +} + +fn main() { + assert_eq!(sum_iter(1), 1); + assert_eq!(sum_recur(1), 1); + assert_eq!(sum_iter(4), 10); + assert_eq!(sum_recur(4), 10); + assert_eq!(linear_loop(4), 6); + assert_eq!(quadratic_loop(4), 20); + assert_eq!(logarithmic_loop(4), 1); + assert_eq!(logarithmic_loop(5), 1); +} diff --git a/zh-hant/codes/rust/chapter_divide_and_conquer/fast_power.rs b/zh-hant/codes/rust/chapter_divide_and_conquer/fast_power.rs new file mode 100644 index 000000000..f82276d27 --- /dev/null +++ b/zh-hant/codes/rust/chapter_divide_and_conquer/fast_power.rs @@ -0,0 +1,23 @@ +/* + * File: fast_power.rs + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 快速冪 */ +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 +} + +fn main() { + assert_eq!(fast_pow(7, 0), 1); + assert_eq!(fast_pow(3, 5), 243); + assert_eq!(fast_pow(2, 6), 64); +} diff --git a/zh-hant/codes/swift/Package.swift b/zh-hant/codes/swift/Package.swift index 5326dc138..8ccb78ab8 100644 --- a/zh-hant/codes/swift/Package.swift +++ b/zh-hant/codes/swift/Package.swift @@ -11,6 +11,7 @@ let package = Package( .executable(name: "time_complexity", targets: ["time_complexity"]), .executable(name: "worst_best_time_complexity", targets: ["worst_best_time_complexity"]), .executable(name: "space_complexity", targets: ["space_complexity"]), + .executable(name: "complexity_exercises", targets: ["complexity_exercises"]), // chapter_array_and_linkedlist .executable(name: "array", targets: ["array"]), .executable(name: "linked_list", targets: ["linked_list"]), @@ -70,6 +71,7 @@ let package = Package( .executable(name: "binary_search_recur", targets: ["binary_search_recur"]), .executable(name: "build_tree", targets: ["build_tree"]), .executable(name: "hanota", targets: ["hanota"]), + .executable(name: "fast_power", targets: ["fast_power"]), // chapter_backtracking .executable(name: "preorder_traversal_i_compact", targets: ["preorder_traversal_i_compact"]), .executable(name: "preorder_traversal_ii_compact", targets: ["preorder_traversal_ii_compact"]), @@ -114,6 +116,7 @@ let package = Package( .executableTarget(name: "time_complexity", path: "chapter_computational_complexity", sources: ["time_complexity.swift"]), .executableTarget(name: "worst_best_time_complexity", path: "chapter_computational_complexity", sources: ["worst_best_time_complexity.swift"]), .executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]), + .executableTarget(name: "complexity_exercises", path: "chapter_computational_complexity", sources: ["complexity_exercises.swift"]), // chapter_array_and_linkedlist .executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]), .executableTarget(name: "linked_list", dependencies: ["utils"], path: "chapter_array_and_linkedlist", sources: ["linked_list.swift"]), @@ -173,6 +176,7 @@ let package = Package( .executableTarget(name: "binary_search_recur", path: "chapter_divide_and_conquer", sources: ["binary_search_recur.swift"]), .executableTarget(name: "build_tree", dependencies: ["utils"], path: "chapter_divide_and_conquer", sources: ["build_tree.swift"]), .executableTarget(name: "hanota", path: "chapter_divide_and_conquer", sources: ["hanota.swift"]), + .executableTarget(name: "fast_power", path: "chapter_divide_and_conquer", sources: ["fast_power.swift"]), // chapter_backtracking .executableTarget(name: "preorder_traversal_i_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_i_compact.swift"]), .executableTarget(name: "preorder_traversal_ii_compact", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_ii_compact.swift"]), diff --git a/zh-hant/codes/swift/chapter_computational_complexity/complexity_exercises.swift b/zh-hant/codes/swift/chapter_computational_complexity/complexity_exercises.swift new file mode 100644 index 000000000..79b78e684 --- /dev/null +++ b/zh-hant/codes/swift/chapter_computational_complexity/complexity_exercises.swift @@ -0,0 +1,62 @@ +/** + File: complexity_exercises.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* 迭代求和 */ +func sumIter(n: Int) -> Int { + var res = 0 + for i in 1 ... n { + res += i + } + return res +} + +/* 遞迴求和 */ +func sumRecur(n: Int) -> Int { + if n == 1 { + return 1 + } + return n + sumRecur(n: n - 1) +} + +/* 線性階迴圈 */ +func linearLoop(n: Int) -> Int { + var res = 0 + for i in 0 ..< n { + res += i + } + return res +} + +/* 平方階迴圈 */ +func quadraticLoop(n: Int) -> Int { + var res = 0 + for i in 0 ..< n { + for j in i ..< n { + res += j + } + } + return res +} + +/* 對數階迴圈 */ +func logarithmicLoop(n: Int) -> Int { + var n = n + while n > 1 { + n /= 2 + } + return n +} + +@main +enum ComplexityExercises { + static func main() { + assert(sumIter(n: 1) == 1 && sumRecur(n: 1) == 1) + assert(sumIter(n: 4) == 10 && sumRecur(n: 4) == 10) + assert(linearLoop(n: 4) == 6) + assert(quadraticLoop(n: 4) == 20) + assert(logarithmicLoop(n: 4) == 1 && logarithmicLoop(n: 5) == 1) + } +} diff --git a/zh-hant/codes/swift/chapter_divide_and_conquer/fast_power.swift b/zh-hant/codes/swift/chapter_divide_and_conquer/fast_power.swift new file mode 100644 index 000000000..ac40d3c78 --- /dev/null +++ b/zh-hant/codes/swift/chapter_divide_and_conquer/fast_power.swift @@ -0,0 +1,26 @@ +/** + File: fast_power.swift + Created Time: 2026-08-18 + Author: Hello Algo Team + */ + +/* 快速冪 */ +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 +} + +@main +enum FastPower { + static func main() { + assert(fastPow(x: 7, n: 0) == 1) + assert(fastPow(x: 3, n: 5) == 243) + assert(fastPow(x: 2, n: 6) == 64) + } +} diff --git a/zh-hant/codes/typescript/chapter_computational_complexity/complexity_exercises.ts b/zh-hant/codes/typescript/chapter_computational_complexity/complexity_exercises.ts new file mode 100644 index 000000000..3edbb8a7e --- /dev/null +++ b/zh-hant/codes/typescript/chapter_computational_complexity/complexity_exercises.ts @@ -0,0 +1,65 @@ +/** + * File: complexity_exercises.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 迭代求和 */ +function sumIter(n: number): number { + let res = 0; + for (let i = 1; i <= n; i++) { + res += i; + } + return res; +} + +/* 遞迴求和 */ +function sumRecur(n: number): number { + if (n === 1) { + return 1; + } + return n + sumRecur(n - 1); +} + +/* 線性階迴圈 */ +function linearLoop(n: number): number { + let res = 0; + for (let i = 0; i < n; i++) { + res += i; + } + return res; +} + +/* 平方階迴圈 */ +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; +} + +/* 對數階迴圈 */ +function logarithmicLoop(n: number): number { + while (n > 1) { + n = Math.floor(n / 2); + } + return n; +} + +if ( + sumIter(1) !== 1 || + sumRecur(1) !== 1 || + sumIter(4) !== 10 || + sumRecur(4) !== 10 || + linearLoop(4) !== 6 || + quadraticLoop(4) !== 20 || + logarithmicLoop(4) !== 1 || + logarithmicLoop(5) !== 1 +) { + throw new Error('complexity exercise check failed'); +} + +export {}; diff --git a/zh-hant/codes/typescript/chapter_divide_and_conquer/fast_power.ts b/zh-hant/codes/typescript/chapter_divide_and_conquer/fast_power.ts new file mode 100644 index 000000000..f7d2ca869 --- /dev/null +++ b/zh-hant/codes/typescript/chapter_divide_and_conquer/fast_power.ts @@ -0,0 +1,23 @@ +/** + * File: fast_power.ts + * Created Time: 2026-08-18 + * Author: Hello Algo Team + */ + +/* 快速冪 */ +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; +} + +if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) { + throw new Error('fast power check failed'); +} + +export {}; diff --git a/zh-hant/docs/chapter_computational_complexity/exercises.md b/zh-hant/docs/chapter_computational_complexity/exercises.md index 04144e968..a6ec5ef87 100644 --- a/zh-hant/docs/chapter_computational_complexity/exercises.md +++ b/zh-hant/docs/chapter_computational_complexity/exercises.md @@ -7,33 +7,23 @@ 下面兩段程式碼都計算 $1 + 2 + \dots + n$(設 $n \ge 1$)。請把 `n` 設為 4, 按照程式實際執行的順序回答問題,然後比較兩種寫法的效率。 -```python -def sum_iter(n): - s = 0 - for i in range(1, n + 1): - s += i - return s - -def sum_recur(n): - if n == 1: - return 1 - return n + sum_recur(n - 1) +```src +[file]{complexity_exercises}-[class]{}-[func]{sum_iter} ``` -1. 執行 `sum_iter(4)` 時,每輪迴圈結束後,變數 `s` 的值分別是多少? -2. 執行 `sum_recur(4)` 時,會依次呼叫哪些函式?從最深的一層開始返回時,結果怎樣得到? +1. 輸入 `n = 4` 執行迭代函式時,每輪迴圈結束後,累加變數 `res` 的值分別是多少? +2. 輸入 `n = 4` 執行遞迴函式時,參數 `n` 會依次取哪些值?從最深的一層開始返回時,結果怎樣得到? 3. 兩種寫法的時間複雜度和空間複雜度分別是多少?結合第 1、2 問的執行過程說明理由。 ??? success "參考答案" - 1. 迴圈變數 `i` 依次為 `1、2、3、4`,每輪結束後,`s` 依次變為 - `1、3、6、10`,所以 `sum_iter(4)` 返回 10。 + 1. 迴圈變數 `i` 依次為 `1、2、3、4`,每輪結束後,`res` 依次變為 + `1、3、6、10`,所以迭代函式返回 10。 - 2. 函式依次呼叫 - `sum_recur(4) → sum_recur(3) → sum_recur(2) → sum_recur(1)`。 - `sum_recur(1)` 返回 1,隨後各層依次得到 `2 + 1 = 3`、`3 + 3 = 6`、`4 + 6 = 10`。 + 2. 參數 `n` 依次為 `4 → 3 → 2 → 1`。 + 最深一層返回 1,隨後各層依次得到 `2 + 1 = 3`、`3 + 3 = 6`、`4 + 6 = 10`。 在最深處,4 次函式呼叫都尚未結束。 3. 兩段程式碼都進行與 $n$ 成正比的迴圈或呼叫,因此時間複雜度均為 $O(n)$ 。 @@ -47,21 +37,8 @@ def sum_recur(n): 以下三個程式碼片段的輸入均為正整數 $n$ 。請按時間複雜度從低到高排序,並寫出各自的複雜度。 -```python -# 片段一 -s = 0 -for i in range(n): - s += i - -# 片段二 -s = 0 -for i in range(n): - for j in range(i, n): - s += j - -# 片段三 -while n > 1: - n = n // 2 +```src +[file]{complexity_exercises}-[class]{}-[func]{linear_loop} ``` ??? success "參考答案" diff --git a/zh-hant/docs/chapter_divide_and_conquer/exercises.md b/zh-hant/docs/chapter_divide_and_conquer/exercises.md index 66cb1d99e..db827280c 100644 --- a/zh-hant/docs/chapter_divide_and_conquer/exercises.md +++ b/zh-hant/docs/chapter_divide_and_conquer/exercises.md @@ -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`,用這個函式計算: 1. 遞迴呼叫時,參數 `n` 依次變成哪些值? 2. 從最深層開始返回時,各層依次返回什麼值? -3. 為什麼要先儲存 `half`,而不是把 `fast_pow(x, n // 2)` 寫兩遍? +3. 為什麼要先把遞迴結果儲存為 `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)` 在乘法兩邊各寫一次,兩次遞迴會計算完全相同的子問題。 + 3. 如果在乘法兩邊各呼叫一次相同的子問題,兩次遞迴會進行完全相同的計算。 先把結果儲存為 `half`,每層就只遞迴一次,遞迴深度約為 $\log n$; 呼叫兩次會造成大量重複計算。