Search code examples
pythonenumerationsagegalois-field

How to print all the additions and multiplications of a Galois Field in Sage


My command line takes two inputs, a prime p and a positive integer n. I put them in a Galois Field in the form of GF(p^n).

My goal is to print out all the elements of the field, the additions, and multiplications.

I can print out the elements of the field, but how do I get the additions and multiplications? I want them like this if p and n are 2:

(0) + (0) = 0
(0) + (x) = x
(0) + (x + 1) = x + 1
(0) + (1) = 1
(x) + (0) = x
(x) + (x) = 0
(x) + (x + 1) = 1
(x) + (1) = x + 1
(x + 1) + (0) = x + 1
(x + 1) + (x) = 1
(x + 1) + (x + 1) = 0
(x + 1) + (1) = x
(1) + (0) = 1
(1) + (x) = x + 1
(1) + (x + 1) = x

Here is my code so far:

import sys

p = int(sys.argv[1])
n = int(sys.argv[2])

k = GF(p**n, 'x')
for i,x in enumerate(k):  print x

print '(%s) + (%s) = %s' % (i, j, i + j)

Solution

  • You could simply use nested loops over the elements of k, instead of over the indices of the elements:

    sage: for e0 in k:
    ....:     for e1 in k:
    ....:         print '(%s) + (%s) = %s' % (e0, e1, e0+e1)
    ....:         
    (0) + (0) = 0
    (0) + (x) = x
    (0) + (x + 1) = x + 1
    (0) + (1) = 1
    (x) + (0) = x
    (x) + (x) = 0
    (x) + (x + 1) = 1
    (x) + (1) = x + 1
    (x + 1) + (0) = x + 1
    (x + 1) + (x) = 1
    (x + 1) + (x + 1) = 0
    (x + 1) + (1) = x
    (1) + (0) = 1
    (1) + (x) = x + 1
    (1) + (x + 1) = x
    (1) + (1) = 0
    

    Alternatively, you could use CartesianProduct (or itertools.product in pure Python):

    sage: for e0, e1 in CartesianProduct(k,k):
    ....:     print '(%s) + (%s) = %s' % (e0, e1, e0+e1)
    ....:     
    (0) + (0) = 0
    (0) + (x) = x
    [etc.]