eulerbooks/notebooks/problem0030.ipynb

107 lines
3.2 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "cbbd0d3f",
"metadata": {},
"source": [
"# [Digit Fifth Powers](https://projecteuler.net/problem=30)\n",
"\n",
"These sorts of numbers are called [perfect digital invariants](https://en.wikipedia.org/wiki/Perfect_digital_invariant) (that page talks about the concept for arbitrary bases, but we obviously only need to worry about base 10).\n",
"\n",
"It's not difficult to implement the PDI function from the page linked above, and to check numbers one by one to see if they are a PDI, but how do we know when to stop searching? Well, let $f(n)$ be the fifth power PDI function, and consider the largest possible six digit number, 999999. The sum of the fifth powers of the digits is $f(999999) = 6 \\times 9^5 = 354294$. If we replaced any digits in 999999, they would have to be smaller than 9, so the power digit sum would be smaller than 354294. Therefore, for any $n \\leq 999999$, $f(n) \\leq 354294$, so for $n$ to *equal* $f(n)$, $n$ must be less than or equal to 354294, as well.\n",
"\n",
"(There's a formal proof on the page linked above that shows the upper bound can be reduced even further, but I think the logic is harder to follow than what's presented here, and using this bound solves the problem quickly enough.)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "e8ab0179",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{4150, 4151, 54748, 92727, 93084, 194979}"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from functools import cache\n",
"\n",
"@cache\n",
"def F(n, p):\n",
" q = n // 10\n",
" if q == 0:\n",
" return n ** p\n",
" \n",
" return (n % 10) ** p + F(q, p)\n",
"\n",
"\n",
"pdis = {n for n in range(2, 354295) if n == F(n, 5)}\n",
"pdis"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "bda685a5",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"443839"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(pdis)"
]
},
{
"cell_type": "markdown",
"id": "f0754e9f",
"metadata": {},
"source": [
"## Relevant sequences\n",
"* Perfect digital invariants: [A252648](https://oeis.org/A252648)\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
}