{ "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": [ "When we know the corner of a certain spiral we can calculate it's total like $f_n = 4 c_n + 6 (n - 1)$. We then only have to update the corner value for each spiral. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "total = 1\n", "current_corner = 3\n", "\n", "for n in range(3, 1002, 2):\n", " total += 4 * current_corner + 6 * (n - 1)\n", " current_corner += 4 * n - 2\n", "\n", "s = total" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "669171001" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "assert(s == 669171001)\n", "s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The only missing piece is how could we calculate the current corner value for a certain n. The series for this is as follows:\n", "\n", "$c = 1, 3, 13, 31, 57, 91, 133, 183, 241, \\dots$\n", "\n", "With some experimenting it can be seen that\n", "\n", "$c_n = (n - 1)^2 - (n - 2) = n^2 - 2n + 1 - n + 2 = n^2 - 3n + 3$.\n", "\n", "Now, we can insert $c_n$ into $f_n$ which gives as the sum of corners for the nth spiral:\n", "\n", "$f_n = 4n^2 - 12n + 12 + 6n - 6 = 4n^2 - 6n + 6$" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "669171001" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 1 + sum([4 * n * n - 6 * n + 6 for n in range(3, 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.5.4" }, "tags": [ "spiral", "diagonals" ] }, "nbformat": 4, "nbformat_minor": 2 }