diff --git a/notebooks/problem0058.ipynb b/notebooks/problem0058.ipynb new file mode 100644 index 0000000..2845e1c --- /dev/null +++ b/notebooks/problem0058.ipynb @@ -0,0 +1,91 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "7edea8e5", + "metadata": {}, + "source": [ + "# [Spiral Primes](https://projecteuler.net/problem=58)\n", + "\n", + "It's the return of the Ulam spiral from [problem 28](https://projecteuler.net/problem=28) (this time we're going counter-clockwise, but that doesn't actually affect much).\n", + "\n", + "We can handle this problem with a couple of easy-to-derive formulas. First, for a spiral with side length $n$ (note that $n$ must be odd), the number of diagonal entries is $2n-1$. Furthermore, the outermost diagonal entries will be $n^2$, $n^2 - (n-1)$, $n^2 - 2(n-1)$, and $n^2 - 3(n-1)$.\n", + "\n", + "With these facts, we can just iterate over odd values of $n$ and calculate the four outermost diagonal entries. We'll keep a running total $p$ of how many primes we see and stop when $\\frac{p}{2n-1} < 0.1$." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "4480be30", + "metadata": {}, + "outputs": [], + "source": [ + "def diagonal(n, k): return n^2 - k*(n-1)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "025d7d4b", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "26241" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from itertools import count\n", + "\n", + "p = 0\n", + "for n in count(3, 2):\n", + " for k in range(0, 4):\n", + " if is_prime(diagonal(n, k)):\n", + " p += 1\n", + " \n", + " if p / (2*n - 1) < 0.1:\n", + " break\n", + "\n", + "n" + ] + }, + { + "cell_type": "markdown", + "id": "f181c6ae", + "metadata": {}, + "source": [ + "## Relevant sequences\n", + "* Numbers on diagonals: [A200975](https://oeis.org/A200975)\n", + "* Primes at right-angle turns on the Ulam spiral: [A172979](https://oeis.org/A172979)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "SageMath 9.5", + "language": "sage", + "name": "sagemath" + }, + "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.11.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}