This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.

15.5. A bit of number theory with SymPy

In [ ]:
from sympy import *
init_printing()
In [ ]:
import sympy.ntheory as nt

Prime numbers

Test whether a number is prime.

In [ ]:
nt.isprime(2011)

Find the next prime after a given number.

In [ ]:
nt.nextprime(2011)

What is the 1000th prime number?

In [ ]:
nt.prime(1000)

How many primes less than 2011 are there?

In [ ]:
nt.primepi(2011)

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.

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [ ]:
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.

In [ ]:
nt.factorint(1998)
In [ ]:
2 * 3**3 * 37

Chinese Remainder Theorem

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.

In [ ]:
from sympy.ntheory.modular import solve_congruence
In [ ]:
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.

You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).

IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).