113 lines
3.0 KiB
Plaintext
113 lines
3.0 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "df906ad5",
|
|
"metadata": {},
|
|
"source": [
|
|
"# [Special Pythagorean Triplet](https://projecteuler.net/problem=9)\n",
|
|
"\n",
|
|
"The key mathematical insight for this problem is that Euclid gave a parameterization for generating [Pythagorean triplets](https://en.wikipedia.org/wiki/Pythagorean_triple): given integers $m, n$ such that $m > n > 0$, a triplet is given by\n",
|
|
"$$\n",
|
|
"\\begin{align}\n",
|
|
"a &= m^2 - n^2 \\\\\n",
|
|
"b &= 2mn \\\\\n",
|
|
"c &= m^2 + n^2\n",
|
|
"\\end{align}\n",
|
|
"$$\n",
|
|
"Furthermore, if $m$ and $n$ are [coprime](https://en.wikipedia.org/wiki/Coprime_integers) (i.e. $\\gcd(m,n)=1$) and exactly one of $m$ and $n$ is even, they will generate a primitive triplet, i.e. a triplet such that $\\gcd(a,b,c)=1$."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "644fb73e",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from itertools import count\n",
|
|
"\n",
|
|
"def primitive_pythagorean_triplets():\n",
|
|
" for m in count(2):\n",
|
|
" for n in range(1, m):\n",
|
|
" if not ((m % 2) ^^ (n % 2)) or gcd(m, n) != 1:\n",
|
|
" continue\n",
|
|
"\n",
|
|
" a = m ** 2 - n ** 2\n",
|
|
" b = 2 * m * n\n",
|
|
" c = m ** 2 + n ** 2\n",
|
|
"\n",
|
|
" yield (a, b, c)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "db3c3419",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can simply iterate through these primitive triplets, and for each one, scale them until we either find our special triplet or their sum is greater than 1000, at which point we'll try the next primitive triplet."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "7b2c3efa",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"(375, 200, 425)"
|
|
]
|
|
},
|
|
"execution_count": 2,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"def find_special_triplet():\n",
|
|
" for (a, b, c) in primitive_pythagorean_triplets():\n",
|
|
" for k in count(1):\n",
|
|
" if k * (a + b + c) == 1000:\n",
|
|
" return (k * a, k * b, k * c)\n",
|
|
" \n",
|
|
" if k * (a + b + c) > 1000:\n",
|
|
" break\n",
|
|
" \n",
|
|
" \n",
|
|
"find_special_triplet()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "8809ed3b",
|
|
"metadata": {},
|
|
"source": [
|
|
"So our product is $abc=31875000$."
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "SageMath 9.5",
|
|
"language": "sage",
|
|
"name": "sagemath"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.11.2"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|