eulerbooks/problem0010.ipynb

89 lines
2.6 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "ec6f67ee",
"metadata": {},
"source": [
"# Summation of Primes\n",
"> The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n",
">\n",
"> Find the sum of all the primes below two million.\n",
"\n",
"Once again, SageMath comes with functions that do the hard part for us."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "127873d5",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"142913828922"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(prime_range(2000000))"
]
},
{
"cell_type": "markdown",
"id": "46f100db",
"metadata": {},
"source": [
"If `prime_range` didn't exist, we may have attempted using a primality test (like in [problem 7](https://projecteuler.net/problem=7)) to test each number less than 2,000,000, but for this problem, there's an even simpler way than implementing a test: the [sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), which can even be carried out on pen and paper (although maybe not for primes up to 2,000,000).\n",
"\n",
"Given an upper limit $n$, the sieve determines all the primes less than or equal to $n$. It does this by first assuming every number from 2 to $n$ is prime. Then, since 2 is assumed to be prime, every multiple of 2 up to $n$ is marked as composite. After this, we skip to the next number still assumed prime (3 for the second iteration) and mark all its multiples as composite. Repeat for each successive \"assumed\" prime. At the end, any number not marked composite is prime. We can then add those primes up to get our answer."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "35ec90ad",
"metadata": {},
"outputs": [],
"source": [
"def sieve(n):\n",
" # leave out multiples of 2 to save memory\n",
" P = set(range(3, n + 1, 2))\n",
" \n",
" for i in range(3, isqrt(n) + 1, 2):\n",
" if i in P:\n",
" P -= set(range(i ** 2, n + 1, 2 * i))\n",
" \n",
" P.add(2)\n",
" return P"
]
}
],
"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
}