Home
About
Resume
Projects
Links
Blog
Download notebook
{ "cells": [ { "cell_type": "markdown", "id": "86e06153", "metadata": {}, "source": [ "### Q20\n", "Find the sum of the digits in the number 100!." ] }, { "cell_type": "code", "execution_count": 1, "id": "16dac2f4-3864-43fc-a8a0-e99049bf2d12", "metadata": {}, "outputs": [], "source": [ "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_factorial(n):\n", " return str_num_multiply(str(n),str_num_factorial(n-1)) if n else \"1\"" ] }, { "cell_type": "code", "execution_count": 2, "id": "73650e3b-dd45-44bf-b084-8e76364a9233", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 3.15 ms, sys: 420 µs, total: 3.57 ms\n", "Wall time: 3.57 ms\n" ] }, { "data": { "text/plain": [ "648" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "sum([int(c) for c in str_num_factorial(100)])" ] }, { "cell_type": "code", "execution_count": 3, "id": "61f65d34-9b29-4dc7-8365-508401a185d0", "metadata": {}, "outputs": [], "source": [ "def factorial(n):\n", " return (n*factorial(n-1)) if n else 1" ] }, { "cell_type": "code", "execution_count": 4, "id": "3c5ccc8e-8a39-463f-b83e-53a961159812", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 30 µs, sys: 4 µs, total: 34 µs\n", "Wall time: 35.8 µs\n" ] }, { "data": { "text/plain": [ "648" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "sum([int(c) for c in str(factorial(100))])" ] }, { "cell_type": "code", "execution_count": null, "id": "bffadd80-d4f4-4a81-a63b-2ccb90748912", "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 Q19
Next Notebook:
Project Euler Q21
Loading