add problem 48

This commit is contained in:
filifa 2025-05-20 00:17:09 -04:00
parent fc7c74c323
commit e81324d056
1 changed files with 71 additions and 0 deletions

View File

@ -0,0 +1,71 @@
{
"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 products (if the exponent is even) or three products (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)."
]
}
],
"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
}