From e81324d05614d5d79a8c62e7032dd62ee6acbd10 Mon Sep 17 00:00:00 2001 From: filifa Date: Tue, 20 May 2025 00:17:09 -0400 Subject: [PATCH] add problem 48 --- notebooks/problem0048.ipynb | 71 +++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 notebooks/problem0048.ipynb diff --git a/notebooks/problem0048.ipynb b/notebooks/problem0048.ipynb new file mode 100644 index 0000000..d0df328 --- /dev/null +++ b/notebooks/problem0048.ipynb @@ -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 +}