euler/ipython/EulerProblem045.ipynb
2018-12-22 18:44:11 -05:00

133 lines
2.7 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Triangular, pentagonal, and hexagonal (Euler Problem 45)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"[https://projecteuler.net/problem=45](https://projecteuler.net/problem=45)\n",
"\n",
"Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:\n",
"\n",
"Triangle\t \t$T_n=n(n+1)/2 = 1, 3, 6, 10, 15, ...$\n",
"\n",
"Pentagonal\t \t$P_n=n(3n1)/2 = 1, 5, 12, 22, 35, ...$\n",
"\n",
"Hexagonal\t \t$H_n=n(2n1) = 1, 6, 15, 28, 45, ...$\n",
"\n",
"It can be verified that T285 = P165 = H143 = 40755.\n",
"\n",
"Find the next triangle number that is also pentagonal and hexagonal."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def T(n):\n",
" return n * (n + 1) // 2\n",
"\n",
"assert(T(3) == 6)\n",
"\n",
"def P(n):\n",
" return n * (3 * n - 1) // 2\n",
"\n",
"assert(P(3) == 12)\n",
"\n",
"def H(n):\n",
" return n * (2 * n - 1)\n",
"\n",
"assert(H(3) == 15)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"n_max = 100000\n",
"s = 0\n",
"\n",
"T_list = [T(n) for n in range(1, n_max + 1)]\n",
"P_set = {P(n) for n in range(1, n_max + 1)}\n",
"H_set = {H(n) for n in range(1, n_max + 1)}\n",
"\n",
"for n in range(1, n_max + 1):\n",
" if T_list[n - 1] in P_set and T_list[n - 1] in H_set:\n",
" t = T_list[n - 1]\n",
" if t > 40755:\n",
" s = t"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1533776805\n"
]
}
],
"source": [
"print(s)\n",
"assert(s == 1533776805)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"completion_date": "Sat, 22 Dec 2018, 23:17",
"kernelspec": {
"display_name": "Python 3",
"language": "python3.6",
"name": "python3"
},
"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.6.5"
},
"tags": [
"triangular",
"pentagonal",
"hexagonal"
]
},
"nbformat": 4,
"nbformat_minor": 2
}