eulerbooks/notebooks/problem0075.ipynb

135 lines
3.2 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "eb8a199b",
"metadata": {},
"source": [
"# [Singular Integer Right Triangles](https://projecteuler.net/problem=75)\n",
"\n",
"This problem is eerily similar to [problem 39](https://projecteuler.net/problem=39). We'll reuse our generator from that problem:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "9d02cd79",
"metadata": {},
"outputs": [],
"source": [
"from itertools import count\n",
"\n",
"def primitive_pythagorean_triplets(max_perim):\n",
" for m in count(2):\n",
" if 2*m^2 + 2*m > max_perim:\n",
" break\n",
"\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",
" if a + b + c > max_perim:\n",
" break\n",
" \n",
" yield (a, b, c)"
]
},
{
"cell_type": "markdown",
"id": "3d3e6bf8",
"metadata": {},
"source": [
"And we'll reuse the main loop from that problem, too!"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "09e14708",
"metadata": {},
"outputs": [],
"source": [
"from collections import Counter\n",
"\n",
"limit = 1500000\n",
"lengths = Counter()\n",
"\n",
"for (a, b, c) in primitive_pythagorean_triplets(limit):\n",
" for k in count(1):\n",
" L = k * (a + b + c)\n",
" if L > limit:\n",
" break\n",
" \n",
" lengths[L] += 1"
]
},
{
"cell_type": "markdown",
"id": "c12a3e3c",
"metadata": {},
"source": [
"The only differences in this problem are our maximum perimeter, and that we're looking for perimeters that can only be made from one Pythagorean triplet."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "0e7ce4b0",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"161667"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len({k for (k, v) in lengths.items() if v == 1})"
]
},
{
"cell_type": "markdown",
"id": "84d83e3b",
"metadata": {},
"source": [
"## Relevant sequences\n",
"* Perimeters with one Pythagorean triple: [A098714](https://oeis.org/A098714)\n",
"\n",
"#### Copyright (C) 2025 filifa\n",
"\n",
"This work is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/) and the [BSD Zero Clause license](https://spdx.org/licenses/0BSD.html)."
]
}
],
"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
}