Sage-Intro-NumThy

1268 days ago by kast5807

Welcome to Sage! 

This is a worksheet to introduce Sage and Python to undergraduates taking a first number theory course, and not necessarily having any programming background.  Students should know the basics of prime numbers and modular arithmetic.

Created by Katherine E. Stange

(I release this work to the public domain; feel free to use and adapt. I don't mind if you let me know it was useful, though, or provide feedback.)

 

Section 1:  Overview of Interacting with Sage

 

This is a "notebook" where you type commands and see the results.  Sage runs on the underlying programming language Python.  To get started, ask Sage what is 2+2 by clicking on the cell and hitting shift+enter.  This "evaluates" the cell.

2+2 
       
4
4

Your turn.  Find out what is $(5 \cdot 2^{10}+3)/47$.  In Python, exponents are typed like this:  2^3 = 8, and multiplication is typed like this: 2*3 = 6.

(Hint: the answer should be 109.)

 
       

An important thing to know about Sage is that it has variables which are stored throughout the notebook.  To save a value into a variable name, e.g. save the value 3 into the variable "mynumber", you do this:

mynumber = 3 
       

Sage doesn't actually print out anything in response to that, but now the name "mynumber" will return 3 if you use it.  Ask Sage, what is mynumber+3?

mynumber+3 
       
6
6

Sage is full of in-built number theory functions.  Here are some self-explanatory examples (please always evaluate each example cell as we work through this notebook):

is_prime(105) 
       
factor(105) 
       

It's important to know the alternate format for calling a function on an object:

105.factor() 
       

Another important thing to know is how to check equalities or inequalities.  Try these out:

3 > 7 
       
3 < 7 
       
3 == 7 
       
3+4 == 7 
       

Did you notice the double ==?  That is for comparison (meaning the answer is true or false, they are equal or not).  (You used a single = to assign a value to a variable when you defined mynumber.  Don't forget the difference.)  Now please determine whether $\gcd(36,54)$ or $18$ is larger, or if they are equal.  The syntax for $\gcd$ is just gcd(36,54).

 
       

Section 2: Figuring out Sage Functions

Oftentimes, you will want to find a function you know should exist.  There are a few really good strategies:

(1) Tab completion for functions.  If you type the beginning of the name of a function, then hit tab, the possible functions that start that way appear.

Try it now here.  Note, you can hit "escape" to get out of the menu that appears.

prime 
       

 (2) Tab completion for objects.  Once you have defined something, it has all kinds of things you can do to it.  Type the thing's name, followed by a period, and hit tab to see your options. 

Try it now here.  Note, you can hit "escape" to get out of the menu that appears.

mynumber. 
       

Now experiment with using some of the functions that appeared on mynumber, and see if you can guess what they do.

 
       

(2) Question mark.  If you have a function, and you want to see the documentation for that function, type a question mark after the function and Sage will pop up info.

Try it here:

factor? 
       

(3) Google search.  Make sure to use the words "sage math" in the search if you are having trouble.  If what you are searching is really about programming, not math, then use the keyword "python" (the underlying programming language for Sage).


Okay, now that you have some strategies for figuring out how to discover Sage's inbuilt funcitons, figure out how to compute the prime counting function, $\pi(x)$ for $x=1000$.  (But wait, first take a guess what you think it might be, just ballpark estimate?  Surprised?)

 
       

Section 3:  Modular Arithmetic

You can do modular arithmetic in Sage, which looks like this:

Mod(23, 7) 
       

That's fine for a one-off computation.  But what if we really want to play with integers modulo 7 a lot?  We can work in the integers modulo 7 by defining the ring (number system) itself as an object:

R = IntegerModRing(7) 
       

From now on, Sage knows the name "R" refers to the integers considered modulo 7.

Now I just wrap my integers in R (by this I mean write R(3) instead of just 3 etc.) and Sage will know that I want them to be thought of as integers modulo 7.  Then I can do all kinds of math, just using those!

R(23) 
       
R(3) + R(12) 
       

I can even take the inverse of something Mod 7.

R(2)^(-1) 
       

Let's double check that last result is correct.  Multiply the answer you got by 2 (working in R) and make sure you get 1.

 
       

Section 4:  Basic Intro to Programming

Sage can do programming.  The simplest thing you might want to do as far as programming is to repeat something a bunch of times.  See if you can parse the following code and guess what it will do.  Then, run it and see.

for i in range(1,10): print R(i) 
       

Now, using the same idea, make Sage print the inverse of every possible value Modulo 7.  Use a "for loop" like the last example.

 
       

Next challenge:  use a for loop to do the following for every n in the range 10 to 20:

Define the integers modulo n and compute the inverse of 101 modulo n in that ring.

 
       

Here's an example of the syntax for checking with an if statement, as well as printing a result.

for i in range(1,50): if Mod(i,7) == 0: print "I found something that is divisible by 7. I found: ", i 
       

Now here's your next challenge:  find all the twin primes up to 1000, and print them out.

 
       

Section 5: Creating Functions (and rational numbers)

You can create your own functions.  Here's an example.

def myproduct( x, y ): return x*y 
       
myproduct(2, 3) 
       

Here's a more complicated example, which computes the mediant of two fractions:

def mediant( x, y ): a = x.numerator() b = x.denominator() c = y.numerator() d = y.denominator() return (a+c)/(b+d) 
       
mediant( 1/3, 4/5 ) 
       

Your challenge:  create a function kissing(x,y) which returns True if x and y are kissing fractions and False otherwise.

 
       

Section 6:  Basic Graphics (and Lists and Matrices)

Sage can do lots of visualizing, which is a big part of the fun!  Here's a basic way to plot a function on integers:

list_plot( [ prime_pi(x) for x in range(1,300) ] ) 
       

The syntax above may have been a bit mysterious:  it used a list.  One of the most useful things in Python is lists.  A list is a list of objects, e.g. a list of numbers.  You can manipulate lists to do all manner of things.  Here's how you define a list:

mylist = [ 1, 2, 3 ] 
       

Here's how you get the an element from a list.  The first element is "element 0", the second element is "element 1" and so on (weird, I know).

mylist[0] 
       
mylist[2] 
       

You can define lists very compactly (avoiding making for loops).  For example:

gcdwithme = [ gcd( x, 15 ) for x in range(1,20) ] 
       
gcdwithme 
       

Side tip:  The syntax range(a,b) which we've been using actually just returns a list:  the list of all the integers starting with a and ending with b-1.  Try it:

range(1,10) 
       
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Your turn.  Make a list of the values of x modulo $11$, for x in the range of 1 to 100.

 
       

Now print out the 11th term of your list.

 
       

And finally plot your list like in the first plot above.  (Hint:  you can just use its name, instead of typing out its definition again.)

 
       

Another really useful graphical method for number theory is matrix_plot, which will plot data from an array.  First, I'll show you how to make a matrix (this one is 7x7 with entries in the integers, which Sage refers to as ZZ).  This matrix is just full of zeroes by default.

mymatrix = matrix(ZZ,7,7) 
       

Here's how you get one entry of your matrix:

mymatrix[0,2] 
       

Now I will populate my matrix with an addition table modulo 7.

for i in range(0,7): for j in range(0,7): mymatrix[i,j] = R(i)+R(j) 
       

First, let's print the matrix:

mymatrix 
       

And now let's "plot" it.

matrix_plot( mymatrix, colorbar = True, cmap = 'GnBu' ) 
       

Your turn!  Graph a multiplication table modulo 103.  Re-type, don't cut-and-paste (it helps you learn).

 
       

Section 7:  Building Lists

Lists are convenient for storing things you find while working through a for loop.  Check out this example which solves a linear Diophantine equation by exhaustive search:

solutions = [] # this creates an empty list (# is a comment symbol) for i in range(1,100): for j in range(1,100): # we've nested two loops, so we'll see every pair i with j if 3*i - 4*j == 1: # check if i and j satisfy the equation solutions.append([i,j]) # if so, add the solution [i,j] to the list of solutions 
       
solutions 
       

Create a list of all the primes up to 100 which are 1 modulo 12.  Hint: you could use is_prime() or you could use primes().

 
       

Section 8:  Challenges

Here's a series of challenges for you to practice the skills you learned above and learn new ones.  Read through them first and pick the ones that interest you.

Challenge 1:

Create a list of the first 100 primes.  (Hint: Sage has lots of useful functions, you don't need to program the Sieve of Eratosthenes.  Look for a cheap solution.)

 
       

Challenge 2:

Figure out how to compute the sum-of-divisors function and graph the function on the range of integers from 1 to 100

 
       

Challenge 3:

Create a function that, given $n$, will return those residues modulo $n$ which are squares.

 
       

Challenge 4:

Find all the primes up to 100 which are sums of two integer squares (e.g. $5 = 1^2 + 2^2$ but 7 has no such expression).

 
       

Challenge 5:

Create a plot of the number of distinct prime divisors of n.  Find a curve that is an upper bound and graph it on the same axes.

 
       

Challenge 6:

Use matrix_plot to show, in a square grid 100x100, which pairs of integers are coprime.

 
       

Challenge 7:

Make Sage output a LaTeX table suitable for cutting and pasting into your homework (there are inbuilt functions for this!), showing the multiplication table for integers modulo 13.