80 lines
2.6 KiB
Plaintext
80 lines
2.6 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "e829e539",
|
|
"metadata": {},
|
|
"source": [
|
|
"## [Self Powers](https://projecteuler.net/problem=48)\n",
|
|
"\n",
|
|
"Easy with [modular exponentiation](https://en.wikipedia.org/wiki/Modular_exponentiation), which is built into Python."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "5e538f04",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"9110846700"
|
|
]
|
|
},
|
|
"execution_count": 1,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"modulus = 10^10\n",
|
|
"sum(pow(n, n, modulus) for n in range(1, 1001)) % modulus"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "aabc8f36",
|
|
"metadata": {},
|
|
"source": [
|
|
"How are we able to compute these powers so efficiently? It's fundamentally based off of a few simple mathematical principles:\n",
|
|
"$$a^{2x} = (a^x)^2$$\n",
|
|
"$$a^{2x+1} = a(a^x)^2$$\n",
|
|
"$$ab \\bmod{m} = (a \\bmod{m})(b \\bmod{m}) \\bmod{m}$$\n",
|
|
"The first two properties allows us to recursively break up a large power into two multiplications (if the exponent is even) or three multiplications (if the exponent is odd), a process known as [exponentiation by squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring). The third property then allows us to distribute the modulus over multiplication. In tandem, these properties allow us to compute large powers with fewer multiplications, while also using less memory by keeping intermediate values small.\n",
|
|
"\n",
|
|
"Interestingly, there is no known efficient algorithm for reversing this calculation, i.e. computing the [discrete logarithm](https://en.wikipedia.org/wiki/Discrete_logarithm).\n",
|
|
"\n",
|
|
"## Relevant sequences\n",
|
|
"* $n^n$: [A000312](https://oeis.org/A000312)\n",
|
|
"* Partial sums of $n^n$: [A001923](https://oeis.org/A001923)\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
|
|
}
|