{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Euler Problem 28\n", "\n", "Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:\n", "\n", "~~~\n", "21 22 23 24 25\n", "20 7 8 9 10\n", "19 6 1 2 11\n", "18 5 4 3 12\n", "17 16 15 14 13\n", "~~~\n", "\n", "$1 + 3 + 5 + 7 + 9 + 13 + 17 + 21 + 25 = 101$\n", "\n", "It can be verified that the sum of the numbers on the diagonals is 101.\n", "\n", "What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I would try to create a function $f(n)$ which yields the sum of the outmost ring of a n by n spiral.\n", "\n", "For example:\n", "\n", "$f(1) = 1$\n", "\n", "$f(3) = 3 + 5 + 7 + 9 = 24$\n", "\n", "$f(5) = 13 + 17 + 21 + 25 = 76$\n", "\n", "When we have this function we calculate the solution simply by\n", "\n", "~~~\n", "s = sum([f(n) for n in range(1, 1002, 2)])\n", "~~~\n", "\n", "For each outer ring there is an initial corner value c ($c_3 = 3, c_5 = 76$). Once we have this value we can caluclate f like $f(n) = c_{n} + (c_n + n - 1) + (c_n + 2(n-1)) + (c_n + 3(n-1)) = 4c_n + 6 (n-1)$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def f(n):\n", " if n == 1:\n", " return 1\n", " return 0\n", "\n", "s = sum([f(n) for n in range(1, 1002, 2)])\n", "assert(s == 669171001)\n", "s" ] } ], "metadata": { "completion_date": "Wed, 23 Aug 2017, 15:54", "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.6.3" }, "tags": [ "spiral", "diagonals" ] }, "nbformat": 4, "nbformat_minor": 2 }