Home
About
Resume
Projects
Links
Blog
Download notebook
{ "cells": [ { "cell_type": "markdown", "id": "86e06153", "metadata": {}, "source": [ "### Q16\n", "What is the sum of the digits of the number \\(2^{1000}\\)?" ] }, { "cell_type": "code", "execution_count": 1, "id": "16dac2f4-3864-43fc-a8a0-e99049bf2d12", "metadata": {}, "outputs": [], "source": [ "def dec_to_bin(dec):\n", " return bin(dec).replace(\"0b\", \"\")\n", "\n", "def str_num_multiply(str_num_a, str_num_b):\n", " len_a = len(str_num_a)\n", " len_b = len(str_num_b)\n", " result_str = [0]*(len_a+len_b)\n", " carry = 0\n", " for i in range(len_a)[::-1]:\n", " for j in range(len_b)[::-1]:\n", " temp_prod = result_str[j+i+1]+int(str_num_a[i])*int(str_num_b[j])+carry\n", " result_str[j+i+1] = (temp_prod)%10\n", " carry = temp_prod//10\n", " if carry:\n", " result_str[i+j] += carry\n", " carry = 0\n", " return \"\".join([str(i) for i in result_str]).lstrip(\"0\")\n", "\n", "def str_num_pow2n(str_num,n):\n", " # str_num ** (2 ** n)\n", " return str_num_pow2n(str_num_multiply(str_num,str_num),n-1) if n>=1 else str_num\n", "\n", "def str_num_pow(str_num,p):\n", " exponent = dec_to_bin(p)[::-1]\n", " result_str = \"1\"\n", " for num in [str_num_pow2n(str_num,i) for i in range(len(exponent)) if exponent[i]==\"1\"]:\n", " result_str = str_num_multiply(result_str,num)\n", " return result_str" ] }, { "cell_type": "code", "execution_count": 2, "id": "73650e3b-dd45-44bf-b084-8e76364a9233", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 12.9 ms, sys: 474 µs, total: 13.4 ms\n", "Wall time: 12 ms\n" ] }, { "data": { "text/plain": [ "1366" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "sum([int(c) for c in str_num_pow(\"2\",1000)])" ] }, { "cell_type": "code", "execution_count": 3, "id": "a7259bcf-7b75-412f-9c48-e4621ca767fe", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 31 µs, sys: 0 ns, total: 31 µs\n", "Wall time: 33.1 µs\n" ] }, { "data": { "text/plain": [ "1366" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "sum([int(c) for c in str(2**1000)])" ] }, { "cell_type": "code", "execution_count": null, "id": "61f65d34-9b29-4dc7-8365-508401a185d0", "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 Q15
Next Notebook:
Project Euler Q17
Loading