Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions docs/02advanced/04recursion/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -214,20 +214,52 @@ $$

<Answer>

ユークリッドの互除法を用いれば簡単にできます。
ユークリッドの互除法を用いれば簡単にできます。$\mathrm{gcd}(a, b)$ を $a$ と $b$ の最大公約数とします。

例:$30$ と $18$ の最大公約数を求める。

- $30$ を $18$ で割った余りは、$12$
- $18$ を $12$ で割った余りは、$6$
- $12$ を $6$ で割った余りは、$0$
$$
\begin{align*}
\mathrm{gcd}(30, 18) &= \mathrm{gcd}(18, 30 - 18\times 1) \\
&= \mathrm{gcd}(18, 12) \\
&= \mathrm{gcd}(12, 18 - 12\times 1) \\
&= \mathrm{gcd}(12, 6) \\
&= \mathrm{gcd}(6, 12 - 6\times 2) \\
&= \mathrm{gcd}(6, 0) \\
&= 6
\end{align*}
$$

よって、最大公約数は $6$

これを使うと、最大公約数を求めるプログラムは次のようになります。

<ViewSource path="/recursion/gcd.ipynb" />

:::note

このプログラムは、はじめの引数が $a < b$ の場合でも動きます。一度目の再帰で、`gcd(b, a % b)` = `gcd(b, a)` が返されるからです。

つまり、$18$ と $30$ の最大公約数を求めるとき、

$$
\begin{align*}
\mathrm{gcd}(18, 30) &= \mathrm{gcd}(30, 18 - 30\times 0) \\
&= \mathrm{gcd}(30, 18) \\
&= \mathrm{gcd}(18, 30 - 18\times 1) \\
&= \mathrm{gcd}(18, 12) \\
&= \mathrm{gcd}(12, 18 - 12\times 1) \\
&= \mathrm{gcd}(12, 6) \\
&= \mathrm{gcd}(6, 12 - 6\times 2) \\
&= \mathrm{gcd}(6, 0) \\
&= 6
\end{align*}
$$

となります。

:::

また、最大公約数 $\mathrm{gcd}(a, b)$ と最小公倍数 $\mathrm{lcm}(a, b)$ の間には次のような関係があります。

$$
Expand Down
8 changes: 3 additions & 5 deletions static/practice/gcd_recursive.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@
"metadata": {},
"source": [
"def gcd(a, b):\n",
" if a < b:\n",
" a, b = b, a\n",
" if b != 0:\n",
" return gcd(b, a % b)\n",
" else:\n",
" if b == 0:\n",
" return a\n",
" else:\n",
" return gcd(b, a % b)\n",
"\n",
"\n",
"print(gcd(12, 16))"
Expand Down
2 changes: 0 additions & 2 deletions static/recursion/gcd.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
"metadata": {},
"source": [
"def gcd(a, b):\n",
" if a < b:\n",
" a, b = b, a\n",
" if b == 0:\n",
" return a\n",
" else:\n",
Expand Down
14 changes: 6 additions & 8 deletions static/recursion/lcm.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@
{
"metadata": {},
"source": [
"def gcd(m, n):\n",
" if m < n:\n",
" m, n = n, m\n",
" if n == 0:\n",
" return m\n",
"def gcd(a, b):\n",
" if b == 0:\n",
" return a\n",
" else:\n",
" return gcd(n, m % n)\n",
" return gcd(b, a % b)\n",
"\n",
"\n",
"def lcm(m, n):\n",
" return m * n / gcd(m, n)\n",
"def lcm(a, b):\n",
" return a * b / gcd(a, b)\n",
"\n",
"\n",
"print(lcm(30, 18))"
Expand Down