This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
from sympy import * init_printing()
import sympy.ntheory as nt
Test whether a number is prime.
Find the next prime after a given number.
What is the 1000th prime number?
How many primes less than 2011 are there?
We can plot $\pi(x)$, the prime-counting function (the number of prime numbers less than or equal to some number x). The famous prime number theorem states that this function is asymptotically equivalent to $x/\log(x)$. This expression approximately quantifies the distribution of the prime numbers among all integers.
import numpy as np import matplotlib.pyplot as plt %matplotlib inline
x = np.arange(2, 10000) plt.plot(x, list(map(nt.primepi, x)), '-k', label='$\pi(x)$'); plt.plot(x, x / np.log(x), '--k', label='$x/\log(x)$'); plt.legend(loc=2);
Let's compute the integer factorization of some number.
2 * 3**3 * 37
A lazy mathematician is counting his marbles. When they are arranged in three rows, the last column contains one marble. When they form four rows, there are two marbles in the last column, and there are three with five rows. The Chinese Remainer Theorem can give him the answer directly.
from sympy.ntheory.modular import solve_congruence
solve_congruence((1, 3), (2, 4), (3, 5))
There are infinitely many solutions: 58, and 58 plus any multiple of 60. Since 118 seems visually too high, 58 is the right answer.