{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Euler Problem 7\n", "\n", "By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\n", "\n", "What is the 10 001st prime number?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We reuse our prime functions and use a trick from [stackoverflow](https://stackoverflow.com/questions/2300756/get-the-nth-item-of-a-generator-in-python) to get the nth element." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "104743\n" ] } ], "source": [ "import itertools\n", "\n", "def is_prime(n, smaller_primes):\n", " for s in smaller_primes:\n", " if n % s == 0:\n", " return False\n", " if s * s > n:\n", " return True\n", " return True\n", "\n", "def prime_generator_function():\n", " primes = [2, 3, 5, 7]\n", " for p in primes:\n", " yield p\n", " while True:\n", " p += 2\n", " if is_prime(p, primes):\n", " primes.append(p)\n", " yield p\n", "\n", "def get_nth_prime(n):\n", " ps = prime_generator_function()\n", " return next(itertools.islice(ps, n - 1, n))\n", "\n", "assert(get_nth_prime(6) == 13)\n", "print(get_nth_prime(10001))" ] } ], "metadata": { "completion_date": "Wed, 20 Aug 2014, 15:40", "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": [ "prime", "nth prime", "nth", "generator" ] }, "nbformat": 4, "nbformat_minor": 0 }