Home
About
Resume
Projects
Links
Blog
Download notebook
{ "cells": [ { "cell_type": "markdown", "id": "a469358e-2f57-4bd6-9c8d-c59f3d77920b", "metadata": {}, "source": [ "### Q30\n", "Find the sum of all the numbers that can be written as the sum of fifth powers of their digits." ] }, { "cell_type": "code", "execution_count": 1, "id": "d4f3859a-662a-49ea-9d4b-e6767fd6f717", "metadata": {}, "outputs": [], "source": [ "def sum_of_n_powers_nums(n):\n", " max_digit = 1\n", " while len(str(max_digit*9**n)) > max_digit:\n", " max_digit += 1\n", " max_range = (int(str(max_digit*9**n)[0])-1)**n + (max_digit-1)*9**n\n", " n_powers_nums_map = {str(i):i**n for i in range(10)}\n", " sum_history = {}\n", " result = 0\n", " for i in range(10,max_range+1)[::-1]:\n", " sorted_num_str = ''.join(sorted(str(i)))\n", " if sorted_num_str in sum_history:\n", " powers_sum = sum_history[sorted_num_str]\n", " else:\n", " powers_sum = sum(n_powers_nums_map[c] for c in str(i))\n", " sum_history[sorted_num_str] = powers_sum\n", " if i == powers_sum:\n", " result += i\n", " print(f\"history count: {len(sum_history)}\")\n", " return result" ] }, { "cell_type": "code", "execution_count": 2, "id": "327f730e-9c3b-4d30-abf1-70740d61ce59", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "history count: 6276\n", "CPU times: user 120 ms, sys: 0 ns, total: 120 ms\n", "Wall time: 118 ms\n" ] }, { "data": { "text/plain": [ "443839" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "sum_of_n_powers_nums(5)" ] }, { "cell_type": "code", "execution_count": null, "id": "b3d42f30-7cac-4ffe-bb6e-cfbf056c4b20", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "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.8.10" } }, "nbformat": 4, "nbformat_minor": 5 }
Previous Notebook:
Project Euler Q29
Next Notebook:
Project Euler Q31
Loading