LTK SageMath (2023)

Last updated on 14/04/2023


SageMath basics

For installation etc. refer to LTK.


Refer also to LW0200MATHEMATICS.

Invocation: Alternatively, there's the online version Useful:



In Python, everything is an object so there isn’t any difference between types and classes. One can get the class of the object el by type(el). Behavior is defined through methods.

Sage specifics about classes

Compared to Python, Sage has particular ways to handle objects: For more details, see the Sage Developer’s Guide.


Some mathematical expressions return ‘exact’ values, rather than numerical approximations.

To get a numerical approximation, use either the function N or the method n (and both of these have a longer name, numerical_approx, and the function N is the same as n)). These take optional arguments prec, which is the requested number of bits of precision, and digits, which is the requested number of decimal digits of precision; the default is 53 bits of precision. Dynamic typing:


SageMath Number Theory


Sage also knows about other rings, such as finite fields, p-adic integers, the ring of algebraic numbers, polynomial rings, and matrix rings. Here are constructions of some of these: Sage has extensive functionality for number theory.

Factorisation - often using integers or polynomials

The 'Factorization' class provides a structure for holding quite general lists of objects with integer multiplicities. These may hold the results of an arithmetic or algebraic factorization, where the objects may be primes or irreducible polynomials and the multiplicities are the (non-zero) exponents in the factorization. Functions include:


Relative primes and Euler phi (totient) and theorem


Mod(33,9) = 6

Euler's phi-function

phi(n) is the amount of numbers that are relatively prime to n.

Euler's Theorem

If gcd(x,n)=1 then xphi(n)=1 (mod n).

Relative primes

How to get list of relative primes for a given number? See

There are multiple ways to list integers coprime to a given integer in Sage.

One way is to build the ring of integers modulo m, then list the multiplicative group of that ring. Note that this returns a list of Python integers: To get Sage integers one would need Check:

Another way is to use the method coprime integers, which expects another argument to say how far you want to list integers that are coprime to m. To get them up to m - 1: To get them further: These are returned as Sage integers:

Elliptic curves

Oblivious Transfer