{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "We'll use the dual algorithm explained in [Linear prime-number sieves: a family tree](https://www.sciencedirect.com/science/article/pii/0167642387900244) to generate the primes. The primes themselves will be stored inside a [bit array](https://en.wikipedia.org/wiki/Bit_array)." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "142913828922" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import array\n", "\n", "def primes_upto(N):\n", " S = array.array('B')\n", " S.extend(0 for x in range((N >> 3) + 1))\n", " def set_bit(i):\n", " S[i>>3] |= 1<<(i&7)\n", " def is_bit_set(i):\n", " return S[i>>3]&(1<<(i&7)) \n", " \n", " f = 2\n", " while f*2 <= N:\n", " p = 2\n", " pOK = True\n", " while pOK:\n", " set_bit(f*p)\n", " t = p\n", " p += 1\n", " while is_bit_set(p):\n", " p += 1\n", " pOK = f*p <= N and (f % t != 0)\n", " f += 1\n", " \n", " for i in range(2, N+1):\n", " if not is_bit_set(i):\n", " yield i\n", "\n", "sum(primes_upto(2_000_000))\n" ] } ], "metadata": { "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.7.4" }, "title": "Summation of primes" }, "nbformat": 4, "nbformat_minor": 2 }