{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Euler Problem 34\n", "\n", "145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.\n", "\n", "Find the sum of all numbers which are equal to the sum of the factorial of their digits.\n", "\n", "Note: as 1! = 1 and 2! = 2 are not sums they are not included." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The algorithm for checking if a number is curious should be efficient. The more difficult thing is to select the upper bound for the brute force. It can be seen that $9 999 999 < 9! * 7$. Hence we can select $10^7$ as our bound." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from math import factorial\n", "\n", "def is_curious(n):\n", " s = sum([factorial(int(d)) for d in str(n)])\n", " return n == s\n", "\n", "assert(is_curious(145) == True)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "s = sum([n for n in range(3, 10**7) if is_curious(n)])" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "40730" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "assert(s == 40730)\n", "s" ] } ], "metadata": { "completion_date": "Mon, 12 Feb 2018, 17:57", "kernelspec": { "display_name": "Python 3", "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.5.4" }, "tags": [ "factorial", "brute force" ] }, "nbformat": 4, "nbformat_minor": 0 }