mathsoftware

A course about LaTeX and SageMath
git clone https://git.tronto.net/mathsoftware
Download | Log | Files | Refs | README | LICENSE

7-SageAlgebra-modified+solutions.ipynb (35780B)


      1 {
      2  "cells": [
      3   {
      4    "cell_type": "markdown",
      5    "metadata": {},
      6    "source": [
      7     "This lecture's notes are in a different format: the presentations for the $\\LaTeX$ part were made with $\\LaTeX$, so this one is made with Sage, or rather with the [Jupyter Notebook](https://jupyter.org/).\n",
      8     "\n",
      9     "# The Jupyter Notebook\n",
     10     "**Reference:** [[1](https://jupyter.org/documentation)]\n",
     11     "\n",
     12     "The Jupyter Notebook is one of the default interfaces for SageMath, along with the command line interface. You can access it via web browser, but it is running locally on your device (notice the strange url: `http://localhost:8888/notebooks...`).\n",
     13     "\n",
     14     "You can create a new notebook by clicking on `New > SageMath 9.2`. You can also create a Python 3 notebook to write Python code.\n",
     15     "\n",
     16     "Jupyter saves and reads files in the `.ipynb` format. If you download the file for this lecture you can open it and follow the examples interactively.\n",
     17     "\n",
     18     "## Cells\n",
     19     "\n",
     20     "The notebook contains one or more *interactive cells* that you can run, like this one below:"
     21    ]
     22   },
     23   {
     24    "cell_type": "code",
     25    "execution_count": null,
     26    "metadata": {},
     27    "outputs": [],
     28    "source": [
     29     "# Exercise: modify this cell to use the print() command\n",
     30     "\n",
     31     "a = 34*102\n",
     32     "\n",
     33     "print(2+2)\n",
     34     "print(\"hello\")\n",
     35     "print(a-1)"
     36    ]
     37   },
     38   {
     39    "cell_type": "markdown",
     40    "metadata": {},
     41    "source": [
     42     "If you are reading this from Jupyter rather than from the pdf file, you can edit the cell above and run it again. You can also add more cells by selecting `Insert` from the menu bar.\n",
     43     "\n",
     44     "Notice that only the last statement produces an output. You can force anything to be written as output with the `print()` command, which works like in Python. As an exercise, try to modify the cell above to provide more output!"
     45    ]
     46   },
     47   {
     48    "cell_type": "code",
     49    "execution_count": null,
     50    "metadata": {},
     51    "outputs": [],
     52    "source": [
     53     "print(a)"
     54    ]
     55   },
     56   {
     57    "cell_type": "markdown",
     58    "metadata": {},
     59    "source": [
     60     "text *hello*\n",
     61     "* this\n",
     62     "* is\n",
     63     "* a list"
     64    ]
     65   },
     66   {
     67    "cell_type": "markdown",
     68    "metadata": {},
     69    "source": [
     70     "## Markdown\n",
     71     "\n",
     72     "[Markdown](https://en.wikipedia.org/wiki/Markdown) is a simple markup language - think of LaTeX or html, but much simpler.\n",
     73     "You can add text to your notebook with Markdown cells by selecting `Cell > Cell Type > Markdown`.\n",
     74     "\n",
     75     "You can also include some LaTeX code in Markdown cells, with dollar signs $ or align environments:\n",
     76     "\n",
     77     "\\begin{align*}\n",
     78     "\\frac{(x+y)^2}{x+1} = \\frac{x^2+2xy+y^2}{x+1}\n",
     79     "\\end{align*}\n",
     80     "\n",
     81     "When you are done writing a Markdown cell, you can run it to see the well-formatted text. To edit the text again, double-click on the cell. Try doing it now to fix the formula above!"
     82    ]
     83   },
     84   {
     85    "cell_type": "markdown",
     86    "metadata": {},
     87    "source": [
     88     "# Symbolic expressions\n",
     89     "\n",
     90     "**Reference:** [[2](https://doc.sagemath.org/html/en/reference/calculus/sage/symbolic/expression.html)]\n",
     91     "\n",
     92     "Now, let's get started with Sage. One thing you might want to do is manipulating symbolic expressions, like the following:"
     93    ]
     94   },
     95   {
     96    "cell_type": "code",
     97    "execution_count": 48,
     98    "metadata": {},
     99    "outputs": [
    100     {
    101      "name": "stdout",
    102      "output_type": "stream",
    103      "text": [
    104       "[\n",
    105       "x == -1/2*(I*sqrt(3) + 1)*(1/2*I*sqrt(3) - 1/2)^(1/3) + (1/2*I*sqrt(3) - 1/2)^(2/3) - 1,\n",
    106       "x == (1/2*I*sqrt(3) - 1/2)^(4/3) - 1/2*(I*sqrt(3) + 1)/(1/2*I*sqrt(3) - 1/2)^(1/3) - 1,\n",
    107       "x == (1/2*I*sqrt(3) - 1/2)^(1/3) + 1/(1/2*I*sqrt(3) - 1/2)^(1/3) - 1\n",
    108       "]\n"
    109      ]
    110     }
    111    ],
    112    "source": [
    113     "f =  (x^2 + 2*x - 5 >= 0)\n",
    114     "solve(f,x)\n",
    115     "\n",
    116     "g =  x^3 + 3*x^2-1\n",
    117     "print(solve(g==0, x))\n",
    118     "\n",
    119     "h = x^2 +3*x -1"
    120    ]
    121   },
    122   {
    123    "cell_type": "markdown",
    124    "metadata": {},
    125    "source": [
    126     "Notice that the single `=` is part of an assignment, as in Python: we are *assigning* to the variable `f` the value `x^2 + 2*x - 5 >= 0`, which in this case is an equation, so it contains the symbol `==`. Keep in mind the difference between the two!\n",
    127     "\n",
    128     "**Exercise:** change the code above to solve the corresponding inequality $x^2+2x-5\\geq 0$."
    129    ]
    130   },
    131   {
    132    "cell_type": "markdown",
    133    "metadata": {},
    134    "source": [
    135     "## Mathematical variables\n",
    136     "\n",
    137     "Last time we saw what *variables* are in Python, and that they are a little bit different from the *Mathematical variables* that you use in Mathematics. In Sage, both concepts are present, but they are still distinct. For example in the cell above `f` is a variable in the sense of computer science, while `x` is a Mathematical variable.\n",
    138     "\n",
    139     "If you want to use Mathematical variables other than `x`, you first need to *declare* them with the `var()` command:"
    140    ]
    141   },
    142   {
    143    "cell_type": "code",
    144    "execution_count": null,
    145    "metadata": {},
    146    "outputs": [],
    147    "source": [
    148     "var('z')\n",
    149     "solve(z^2 + z - 2 == 0, z)"
    150    ]
    151   },
    152   {
    153    "cell_type": "markdown",
    154    "metadata": {},
    155    "source": [
    156     "Try removing the first line in the cell above and see what error you get!\n",
    157     "\n",
    158     "Here is another example:"
    159    ]
    160   },
    161   {
    162    "cell_type": "code",
    163    "execution_count": null,
    164    "metadata": {},
    165    "outputs": [],
    166    "source": [
    167     "var('a', 'b')\n",
    168     "f = x^2+a*x+b == 0\n",
    169     "solve(f,a)"
    170    ]
    171   },
    172   {
    173    "cell_type": "markdown",
    174    "metadata": {},
    175    "source": [
    176     "Some common constants are [already defined](https://doc.sagemath.org/html/en/reference/calculus/sage/symbolic/expression.html) in Sage:"
    177    ]
    178   },
    179   {
    180    "cell_type": "code",
    181    "execution_count": null,
    182    "metadata": {},
    183    "outputs": [],
    184    "source": [
    185     "e^(pi*I)\n",
    186     "print(N(pi), N(e))\n",
    187     "e = 42\n",
    188     "print(e)\n",
    189     "reset('e')\n",
    190     "print(N(e))"
    191    ]
    192   },
    193   {
    194    "cell_type": "markdown",
    195    "metadata": {},
    196    "source": [
    197     "We will study symbolic expressions more in detail next time, in the context of calculus/analysis."
    198    ]
    199   },
    200   {
    201    "cell_type": "markdown",
    202    "metadata": {},
    203    "source": [
    204     "# Basic rings and fields\n",
    205     "\n",
    206     "**References:** [[3](https://doc.sagemath.org/html/en/reference/rings_standard/index.html)]\n",
    207     "[[4](https://doc.sagemath.org/html/en/reference/rings_numerical/index.html)]\n",
    208     "[[5](https://doc.sagemath.org/html/en/reference/finite_rings/index.html)]\n",
    209     "\n",
    210     "As you should know, a *field* is a Mathematical structure with two operations, addition and multiplication, which respect certain rules (distributivity, associativity, commutativity...). Some examples of fields are the Rational numbers $\\mathbb Q$, the Real numbers $\\mathbb R$ and the Complex numbers $\\mathbb C$, but there are many more. As you should also know, a *(commutative) ring* is like a field, except not all elements different from $0$ need have a multiplicative inverse. For example the integers $\\mathbb Z = \\{ \\dots, -1, 0, 1, 2, \\dots\\}$ are a ring, but not a field.\n",
    211     "\n",
    212     "These structures are already implemented in Sage. Some of the most common are listed in the following table:\n",
    213     "\n",
    214     "|Mathematical object|Math symbol|Sage name|\n",
    215     "|------------------:|:---------:|:--------|\n",
    216     "|Integers|$\\mathbb Z$|`ZZ`|\n",
    217     "|Rational numbers|$\\mathbb Q$|`QQ`|\n",
    218     "|Real numbers|$\\mathbb R$|`RR`|\n",
    219     "|Complex numbers|$\\mathbb C$|`CC`|\n",
    220     "|Integers modulo $n$|$\\mathbb Z/n\\mathbb Z$|`Integers(n)`|\n",
    221     "|Finite fields|$\\mathbb F_p$|GF(p)|\n",
    222     "|$\\dots$|$\\dots$|$\\dots$|"
    223    ]
    224   },
    225   {
    226    "cell_type": "markdown",
    227    "metadata": {},
    228    "source": [
    229     "If you write a number or an expression, Sage will figure out where it \"lives\", choosing the most restrictive interpretation possible. For example `3` will be interpreted to be an integer, even if it is also a rational number, a real number and a complex number."
    230    ]
    231   },
    232   {
    233    "cell_type": "markdown",
    234    "metadata": {},
    235    "source": [
    236     "## Parents and coercion\n",
    237     "**Reference:** [[6](https://doc.sagemath.org/html/en/tutorial/tour_coercion.html)]\n",
    238     "\n",
    239     "You can check where an object \"lives\" with the `parent()` command. It works more or less like the Python command `type()`, but it gives a more Mathematically inclined answer. Check the reference link [6] above if you want more details."
    240    ]
    241   },
    242   {
    243    "cell_type": "code",
    244    "execution_count": null,
    245    "metadata": {},
    246    "outputs": [],
    247    "source": [
    248     "#Edit this cell to find out the type of other objects that we used\n",
    249     "print(parent(3/5))\n",
    250     "print(QQ)\n",
    251     "print(type(3/5))"
    252    ]
    253   },
    254   {
    255    "cell_type": "markdown",
    256    "metadata": {},
    257    "source": [
    258     "Sometimes Sage does not give you the best possible interpretation, so you can force something to be interpreted as living in a smaller ring as follows:"
    259    ]
    260   },
    261   {
    262    "cell_type": "code",
    263    "execution_count": null,
    264    "metadata": {},
    265    "outputs": [],
    266    "source": [
    267     "minus_one = e^(pi*I)\n",
    268     "print(minus_one)\n",
    269     "minus_one_coerced = ZZ(e^(pi*I))  # coercion\n",
    270     "#print(ZZ(1/2))\n",
    271     "print(parent(minus_one))\n",
    272     "print(parent(x^2))\n",
    273     "print(parent(minus_one_coerced))\n",
    274     "print(parent(5.2))\n",
    275     "print(parent(QQ(5.2)))"
    276    ]
    277   },
    278   {
    279    "cell_type": "markdown",
    280    "metadata": {},
    281    "source": [
    282     "**Remark.** Notice that there is a fundamental difference between the rings `RR` and `CC` and all the others in the table above: the real and complex numbers are *approximated*."
    283    ]
    284   },
    285   {
    286    "cell_type": "code",
    287    "execution_count": null,
    288    "metadata": {},
    289    "outputs": [],
    290    "source": [
    291     "print(QQ(3))\n",
    292     "print(RR(3))"
    293    ]
    294   },
    295   {
    296    "cell_type": "markdown",
    297    "metadata": {},
    298    "source": [
    299     "You can also choose the precision of this approximation using the alternative name `RealField`."
    300    ]
    301   },
    302   {
    303    "cell_type": "code",
    304    "execution_count": null,
    305    "metadata": {},
    306    "outputs": [],
    307    "source": [
    308     "print(RR)\n",
    309     "print(RealField(prec=1000))"
    310    ]
    311   },
    312   {
    313    "cell_type": "markdown",
    314    "metadata": {},
    315    "source": [
    316     "# Polynomial rings\n",
    317     "\n",
    318     "**Reference:** [[7](https://doc.sagemath.org/html/en/reference/polynomial_rings/index.html)]\n",
    319     "\n",
    320     "If you want to work with polynomials over a certain ring it is better to use this specific construction, rather than the symbolic expressions introduced above."
    321    ]
    322   },
    323   {
    324    "cell_type": "code",
    325    "execution_count": 55,
    326    "metadata": {},
    327    "outputs": [
    328     {
    329      "name": "stdout",
    330      "output_type": "stream",
    331      "text": [
    332       "Univariate Polynomial Ring in x over Rational Field\n",
    333       "[]\n",
    334       "[(-2, 2)]\n"
    335      ]
    336     }
    337    ],
    338    "source": [
    339     "polring.<x> = QQ[]  # Alternative: polring.<x,y,z> = PolynomialRing(RR)\n",
    340     "polring\n",
    341     "print(parent(x))\n",
    342     "g =  x^3 + 3*x^2-1\n",
    343     "print(g.roots())\n",
    344     "print((x^2+4*x+4).roots())"
    345    ]
    346   },
    347   {
    348    "cell_type": "markdown",
    349    "metadata": {},
    350    "source": [
    351     "You can use as many variables as you like, and you can replace `RR` with any ring. In the example above `polring` is just the name of the variable (in the computer science sense) associated with this polynomial ring.\n",
    352     "\n",
    353     "## Operations on polynomials\n",
    354     "\n",
    355     "The usual Mathematical operations are available on polynomial rings, including Euclidean division `//` and remainder `%`. There is also the single-slash division `/`, but the result may not be a polynomial anymore.\n",
    356     "\n",
    357     "**Exercise:** use the `parent()` command to find out what the quotient of two polynomials is.\n",
    358     "\n",
    359     "**Question:** what happens if you remove the first line in the cell below? What if we used the variable `y` instead of `x`?"
    360    ]
    361   },
    362   {
    363    "cell_type": "code",
    364    "execution_count": 60,
    365    "metadata": {},
    366    "outputs": [
    367     {
    368      "name": "stdout",
    369      "output_type": "stream",
    370      "text": [
    371       "x + 1\n",
    372       "-4\n",
    373       "(x^2 + 2*x - 3)/(x + 1)\n",
    374       "Fraction Field of Univariate Polynomial Ring in x over Rational Field\n"
    375      ]
    376     },
    377     {
    378      "data": {
    379       "text/plain": [
    380        "x^4 + 2*x^3 - 4*x^2 - 2*x + 3"
    381       ]
    382      },
    383      "execution_count": 60,
    384      "metadata": {},
    385      "output_type": "execute_result"
    386     }
    387    ],
    388    "source": [
    389     "polring.<x> = QQ[]\n",
    390     "p = x^2 + 2*x - 3   # Don't forget * for multiplication!\n",
    391     "q = p // (x+1)\n",
    392     "r = p %  (x+1)\n",
    393     "f = p /  (x+1)\n",
    394     "print(q)\n",
    395     "print(r)\n",
    396     "print(f)\n",
    397     "print(parent(f))\n",
    398     "p*(x^2-1)"
    399    ]
    400   },
    401   {
    402    "cell_type": "markdown",
    403    "metadata": {},
    404    "source": [
    405     "You can do more complex operations. Try out `roots()` and `factor` in the cell below.\n",
    406     "\n",
    407     "**Remark.** Notice how the result can change substantially if you change the base ring.\n",
    408     "\n",
    409     "**Remark.** [Factorizations](https://doc.sagemath.org/html/en/reference/structure/sage/structure/factorization.html) are a particular object in Sage. They are kinda like a list, but not really. You can get a list of pairs (factor, power) with `list(factor(f))`."
    410    ]
    411   },
    412   {
    413    "cell_type": "code",
    414    "execution_count": 76,
    415    "metadata": {
    416     "scrolled": true
    417    },
    418    "outputs": [
    419     {
    420      "name": "stdout",
    421      "output_type": "stream",
    422      "text": [
    423       "(t + 1) * (t^2 - 3) * (t^2 + 1)\n",
    424       "[(t + 1, 1), (t^2 - 3, 1), (t^2 + 1, 1)]\n",
    425       "t^5 + t^4 - 2*t^3 - 2*t^2 - 3*t - 3\n",
    426       "t^2 - 1\n",
    427       "[(-1, 1)]\n",
    428       "Multivariate Polynomial Ring in x, y, z over Rational Field\n"
    429      ]
    430     },
    431     {
    432      "data": {
    433       "text/plain": [
    434        "Multivariate Polynomial Ring in x, y, z over Rational Field"
    435       ]
    436      },
    437      "execution_count": 76,
    438      "metadata": {},
    439      "output_type": "execute_result"
    440     }
    441    ],
    442    "source": [
    443     "polring_onevar.<t> = QQ[]\n",
    444     "\n",
    445     "f = t^5 + t^4 - 2*t^3 - 2*t^2 - 3*t - 3\n",
    446     "fact = factor(f)\n",
    447     "print(factor(f))\n",
    448     "print(list(fact))\n",
    449     "print((t + 1) * (t^2 - 3) * (t^2 + 1))\n",
    450     "print((t+1)*(t-1))\n",
    451     "print(f.roots())  # Result: list of pairs (root,multiplicity)\n",
    452     "\n",
    453     "polring_manyvar.<x,y,z> = QQ[]\n",
    454     "factor(x*y+x)\n",
    455     "\n",
    456     "# The following line gives an error, because the polynomial\n",
    457     "# is understood to possibly have many variables:\n",
    458     "print(parent(x))\n",
    459     "(QQ['x'](x^2-1)).roots()\n",
    460     "parent(x)"
    461    ]
    462   },
    463   {
    464    "cell_type": "markdown",
    465    "metadata": {},
    466    "source": [
    467     "# Matrices and vectors\n",
    468     "\n",
    469     "**References:** [[8](https://doc.sagemath.org/html/en/reference/matrices/index.html)], but in particular the subections [[9](https://doc.sagemath.org/html/en/reference/matrices/sage/matrix/docs.html)] and [[10](https://doc.sagemath.org/html/en/reference/matrices/sage/matrix/matrix2.html)]\n",
    470     "\n",
    471     "In Sage you can easily manipulate matrices and vectors"
    472    ]
    473   },
    474   {
    475    "cell_type": "code",
    476    "execution_count": 94,
    477    "metadata": {},
    478    "outputs": [
    479     {
    480      "name": "stdout",
    481      "output_type": "stream",
    482      "text": [
    483       "[   1    2    3]\n",
    484       "[   0    0    1]\n",
    485       "[   4   -3 22/7] \n",
    486       "\n",
    487       "[1/2   0   0]\n",
    488       "[  7   0   0]\n",
    489       "[  1   1   1] \n",
    490       "\n",
    491       "[1 0]\n",
    492       "[0 1] \n",
    493       "\n",
    494       "(3/2, 21, 6) \n",
    495       "\n",
    496       "[  -7/2    -10   80/7]\n",
    497       "[    17     -4   15/7]\n",
    498       "[ 241/7  -18/7 869/49] \n",
    499       "\n",
    500       "Rank of A = 3\n",
    501       "Rank of B = 2\n"
    502      ]
    503     },
    504     {
    505      "data": {
    506       "text/plain": [
    507        "11"
    508       ]
    509      },
    510      "execution_count": 94,
    511      "metadata": {},
    512      "output_type": "execute_result"
    513     }
    514    ],
    515    "source": [
    516     "A = matrix([[1,2,3],[0,0,1],[4,-3,22/7]])\n",
    517     "B = matrix([[1/2,0,0],[7,0,0],[1,1,1]])\n",
    518     "C = matrix([[1,0],[0,1]])\n",
    519     "v = vector([3,4,-1])\n",
    520     "\n",
    521     "print(A, \"\\n\")  # \\n just means \"newline\"\n",
    522     "print(B, \"\\n\")\n",
    523     "print(C, \"\\n\")\n",
    524     "#print(A*C) Error!\n",
    525     "print(B*v, \"\\n\")\n",
    526     "print(A^2 + 2*B - A*B, \"\\n\")\n",
    527     "\n",
    528     "print(\"Rank of A =\", rank(A)) # You can also use A.rank()\n",
    529     "print(\"Rank of B =\", rank(B))\n",
    530     "A.determinant()"
    531    ]
    532   },
    533   {
    534    "cell_type": "markdown",
    535    "metadata": {},
    536    "source": [
    537     "**Exercise:** in the cell above, compute the determinant, inverse and characteristic polynomial of the matrix `A`. *Hint: look at the reference [10] above (the functions are listed in alphabetic order).*\n",
    538     "\n",
    539     "As for polynomials, you can specify where a matrix or a vector lives"
    540    ]
    541   },
    542   {
    543    "cell_type": "code",
    544    "execution_count": 97,
    545    "metadata": {},
    546    "outputs": [
    547     {
    548      "data": {
    549       "text/plain": [
    550        "Full MatrixSpace of 2 by 2 dense matrices over Complex Field with 53 bits of precision"
    551       ]
    552      },
    553      "execution_count": 97,
    554      "metadata": {},
    555      "output_type": "execute_result"
    556     }
    557    ],
    558    "source": [
    559     "M = matrix(CC, [[0,1/2],[1,0]])\n",
    560     "parent(M)"
    561    ]
    562   },
    563   {
    564    "cell_type": "markdown",
    565    "metadata": {},
    566    "source": [
    567     "You can also solve linear systems and compute eigenvalues and eigenvectors of a matrix\n",
    568     "\n",
    569     "**Warning.** In linear algebra there are distinct concepts of *left* and *right* eigenvalues (and eigenvector). The one you know is probably that of **right** eigen-{value,vector}, that is an element $\\lambda$ of the base field and a non-zero vector $\\mathbf v$ with $A\\mathbf v=\\lambda\\mathbf v$. The other concept corresponds to the equality $\\mathbf v^TA=\\lambda \\mathbf v$."
    570    ]
    571   },
    572   {
    573    "cell_type": "code",
    574    "execution_count": null,
    575    "metadata": {},
    576    "outputs": [],
    577    "source": [
    578     "A = Matrix(RR, [[sqrt(59),32],[-1/4,3]])\n",
    579     "v = vector(RR, [3,0])\n",
    580     "A.solve_right(v) # Solve Ax=v. Alternative: A \\ v"
    581    ]
    582   },
    583   {
    584    "cell_type": "code",
    585    "execution_count": 103,
    586    "metadata": {},
    587    "outputs": [
    588     {
    589      "name": "stderr",
    590      "output_type": "stream",
    591      "text": [
    592       "<ipython-input-103-d1ccc4990851>:2: UserWarning: Using generic algorithm for an inexact ring, which will probably give incorrect results due to numerical precision issues.\n",
    593       "  A.eigenvalues() # Also: A.eigenvalues(), A.eigenvectors_right()\n"
    594      ]
    595     },
    596     {
    597      "data": {
    598       "text/plain": [
    599        "[5.37228132326901, -0.372281323269014]"
    600       ]
    601      },
    602      "execution_count": 103,
    603      "metadata": {},
    604      "output_type": "execute_result"
    605     }
    606    ],
    607    "source": [
    608     "A = Matrix(RR, [[1,2],[3,4]])\n",
    609     "A.eigenvalues() # Also: A.eigenvalues(), A.eigenvectors_right()"
    610    ]
    611   },
    612   {
    613    "cell_type": "markdown",
    614    "metadata": {},
    615    "source": [
    616     "We can also extract a specific submatrix by selecting only some rows and columns, with a syntax similar to that of Python's lists. Check out more examples in the reference [9] above, and try them in the cell below."
    617    ]
    618   },
    619   {
    620    "cell_type": "code",
    621    "execution_count": 105,
    622    "metadata": {},
    623    "outputs": [
    624     {
    625      "name": "stdout",
    626      "output_type": "stream",
    627      "text": [
    628       "[ -3 -25  -5  -3  61   0  -1]\n",
    629       "[ 23   0  -1   1   0   1  -1]\n",
    630       "[286   2   7   0 -21  -1   0]\n",
    631       "[  2  -1  -2   0  -1   4   0]\n",
    632       "[  1  -1   1   0   2  -2   7]\n",
    633       "[  0  15  -1   0  -3   1  -1]\n",
    634       "[ -1   1  -2   0   2   1   1] \n",
    635       "\n",
    636       "[ -1   1   0]\n",
    637       "[  7   0 -21] \n",
    638       "\n",
    639       "[ -3 -25  -5  -3  61   0  -1] \n",
    640       "\n",
    641       "[ -3 -25  -5  -3  61]\n",
    642       "[  0  15  -1   0  -3]\n",
    643       "[286   2   7   0 -21]\n",
    644       "-25\n"
    645      ]
    646     }
    647    ],
    648    "source": [
    649     "A = MatrixSpace(ZZ, 7).random_element()\n",
    650     "print(A, \"\\n\")\n",
    651     "print(A[1:3,2:5], \"\\n\") # Rows from 1 to 3, columns from 2 to 5\n",
    652     "print(A[0,0:], \"\\n\")    # First row, all columns\n",
    653     "print(A[[0,5,2],0:5])   # Rows 0, 5 and 2 (in this order) and columns 0 to 5\n",
    654     "print(A[0,1])"
    655    ]
    656   },
    657   {
    658    "cell_type": "markdown",
    659    "metadata": {},
    660    "source": [
    661     "**Exercise:** write a sage function that computes the determinant of an $n\\times n$ matrix $A=(a_{ij})$ using Laplace's rule by the first row, that is \n",
    662     "\\begin{align*}\n",
    663     "    \\operatorname{det}A = \\sum_{j=1}^n (-1)^ja_{0j}M_{0j}\n",
    664     "\\end{align*}\n",
    665     "where $M_{0j}$ is the determinant of the $(n-1)\\times(n-1)$ matrix obtained by removing the $0$-th row and the $j$-th column from $A$."
    666    ]
    667   },
    668   {
    669    "cell_type": "code",
    670    "execution_count": 6,
    671    "metadata": {},
    672    "outputs": [
    673     {
    674      "name": "stdout",
    675      "output_type": "stream",
    676      "text": [
    677       "[ -1  -3  -1  11   2  -1  -5]\n",
    678       "[  1   0   0  -6  -1   0   1]\n",
    679       "[  1   0  -1   0   1  -1   0]\n",
    680       "[-24   1  -2  -7   4   0   1]\n",
    681       "[ -3   0  -1   0   6  -1   0]\n",
    682       "[-17  -1   1   0  28   1   0]\n",
    683       "[  1  -4   1   1  -2  -6  -2]\n",
    684       "Sage determinant:  13578\n",
    685       "my_det:  13578\n"
    686      ]
    687     }
    688    ],
    689    "source": [
    690     "def my_det(A):\n",
    691     "    if not A.is_square():\n",
    692     "        print(\"Error: matrix is not square\")\n",
    693     "    \n",
    694     "    n = A.nrows()  # size of the matrix\n",
    695     "    \n",
    696     "    if n == 1:\n",
    697     "        return A[0,0]\n",
    698     "    \n",
    699     "    my_sum = 0\n",
    700     "    for j in range(0,n):\n",
    701     "        rows = range(1,n)\n",
    702     "        columns = [element for element in range(0,n) if element != j]\n",
    703     "        submatrix = A[rows,columns]\n",
    704     "        my_sum += (-1)^j * A[0,j] * my_det(submatrix)\n",
    705     "    \n",
    706     "    return my_sum\n",
    707     "\n",
    708     "A = MatrixSpace(ZZ, 7).random_element()\n",
    709     "print(A)\n",
    710     "print(\"Sage determinant: \", A.determinant())\n",
    711     "print(\"my_det: \", my_det(A))"
    712    ]
    713   },
    714   {
    715    "cell_type": "markdown",
    716    "metadata": {},
    717    "source": [
    718     "# Number Theory\n",
    719     "\n",
    720     "**Reference:** [[11](https://doc.sagemath.org/html/en/reference/rings_standard/sage/rings/integer.html)]\n",
    721     "\n",
    722     "Sage includes a large library of functions for computing with the integers, see the link above."
    723    ]
    724   },
    725   {
    726    "cell_type": "code",
    727    "execution_count": 8,
    728    "metadata": {},
    729    "outputs": [
    730     {
    731      "name": "stdout",
    732      "output_type": "stream",
    733      "text": [
    734       "3^2 * 3607 * 3803\n",
    735       "[(3, 2), (3607, 1), (3803, 1)]\n",
    736       "True\n",
    737       "True\n",
    738       "619703040\n",
    739       "9\n",
    740       "13548070123626141\n"
    741      ]
    742     }
    743    ],
    744    "source": [
    745     "n = 123456789\n",
    746     "m = 987654321\n",
    747     "p = 3607\n",
    748     "\n",
    749     "print(factor(n))\n",
    750     "print(list(factor(n)))\n",
    751     "print(is_prime(p))\n",
    752     "print(p.divides(n))\n",
    753     "print(euler_phi(m))\n",
    754     "print(gcd(n, m))\n",
    755     "print(lcm(n, m))"
    756    ]
    757   },
    758   {
    759    "cell_type": "markdown",
    760    "metadata": {},
    761    "source": [
    762     "## Primes\n",
    763     "\n",
    764     "**Reference:** [[12](https://doc.sagemath.org/html/en/reference/sets/sage/sets/primes.html)]\n",
    765     "\n",
    766     "The set of prime numbers is called `Primes()`. It is like an infinite list: for example you can get the one-millionth prime number or you can use this list to create other lists. You can also check what the first prime number larger than a given number is."
    767    ]
    768   },
    769   {
    770    "cell_type": "code",
    771    "execution_count": null,
    772    "metadata": {},
    773    "outputs": [
    774     {
    775      "name": "stdout",
    776      "output_type": "stream",
    777      "text": [
    778       "Set of all prime numbers: 2, 3, 5, 7, ...\n",
    779       "31 252097800629\n",
    780       "47\n",
    781       "[79, 83, 89, 97]\n"
    782      ]
    783     }
    784    ],
    785    "source": [
    786     "PP = Primes()\n",
    787     "print(PP)\n",
    788     "print(PP[10], PP[10^10])\n",
    789     "print(PP.next(44))\n",
    790     "\n",
    791     "First_Thousand_Primes = PP[0:1000]\n",
    792     "print([p for p in First_Thousand_Primes if p < 100 and p > 75])\n",
    793     "#print([p for p in PP if p < 100 and p > 75])"
    794    ]
    795   },
    796   {
    797    "cell_type": "markdown",
    798    "metadata": {},
    799    "source": [
    800     "## The Chinese remainder theorem (CRT)\n",
    801     "\n",
    802     "We say that two integers $a$ and $b$ are *congruent* modulo another integer $n>0$ if they have the same remainder when divided by $n$. We denote this by $a\\equiv b\\pmod n$, or in Python/Sage syntax `a % n == b % n`.\n",
    803     "\n",
    804     "The Chinese remainder theorem states that if $a,b\\in\\mathbb Z$ and $n,m\\in \\mathbb Z_{>0}$ are such that $\\gcd(n,m)=1$ then the system of congruences\n",
    805     "\n",
    806     "\\begin{align*}\n",
    807     "\\begin{cases}\n",
    808     "    x \\equiv a \\pmod n\\\\\n",
    809     "    x \\equiv b \\pmod m\n",
    810     "\\end{cases}\n",
    811     "\\end{align*}\n",
    812     "\n",
    813     "\n",
    814     "has exactly one solution modulo $mn$. This means that there is one and only one number $x$ with $0\\leq x<mn$ such that $x\\equiv a\\pmod n$ and $x\\equiv b\\pmod m$.\n",
    815     "\n",
    816     "\n",
    817     "For example:\n",
    818     "\n",
    819     "\\begin{align*}\n",
    820     "\\begin{cases}\n",
    821     "    x \\equiv 1 \\pmod 3\\\\\n",
    822     "    x \\equiv 2 \\pmod 5\n",
    823     "\\end{cases}\n",
    824     "\\end{align*}\n",
    825     "\n",
    826     "Solution: $x=7$ (any other solution is congruent to $7$ modulo $15$; for example $22=15+7$ is also a solution).\n",
    827     "\n",
    828     "The procedure to find such a number is not too hard to describe (you might see it in an algebra or number theory course), but it can be a bit long. Luckily, Sage can do this for you:"
    829    ]
    830   },
    831   {
    832    "cell_type": "code",
    833    "execution_count": 1,
    834    "metadata": {},
    835    "outputs": [
    836     {
    837      "name": "stdout",
    838      "output_type": "stream",
    839      "text": [
    840       "74306 2 798\n"
    841      ]
    842     }
    843    ],
    844    "source": [
    845     "a = 2\n",
    846     "b = -1\n",
    847     "n = 172\n",
    848     "m = 799\n",
    849     "\n",
    850     "if gcd(n,m) != 1:\n",
    851     "    print(\"The numbers are not comprime, I can't solve this!\")\n",
    852     "else:\n",
    853     "    x = crt(a, b, n, m)\n",
    854     "    print(x, x%n, x%m)"
    855    ]
    856   },
    857   {
    858    "cell_type": "markdown",
    859    "metadata": {},
    860    "source": [
    861     "**Exercise.** There is a more general version of the Chinese remainder theorem which says that if $a_0, a_1, \\dots, a_k\\in\\mathbb Z$ and $n_0, n_2, \\dots, n_k\\in\\mathbb Z_{>0}$ are such that $\\gcd(n_i, n_j)=1$ for $i\\neq j$, then the system of congruences\n",
    862     "\n",
    863     "\\begin{align*}\n",
    864     "\\begin{cases}\n",
    865     "    x \\equiv a_0 \\pmod {n_0}\\\\\n",
    866     "    x \\equiv a_1 \\pmod {n_1}\\\\\n",
    867     "    \\dots \\\\\n",
    868     "    x \\equiv a_k \\pmod {n_k}\n",
    869     "\\end{cases}\n",
    870     "\\end{align*}\n",
    871     "\n",
    872     "has exactly one solution modulo $\\prod_{i=0}^kn_i$. Use the `crt()` function to find a solution to such a system.\n",
    873     "*Hint: start by running the command `help(crt)`."
    874    ]
    875   },
    876   {
    877    "cell_type": "code",
    878    "execution_count": 3,
    879    "metadata": {},
    880    "outputs": [],
    881    "source": [
    882     "#help(crt)"
    883    ]
    884   },
    885   {
    886    "cell_type": "markdown",
    887    "metadata": {},
    888    "source": [
    889     "# Cryptography: RSA\n",
    890     "\n",
    891     "[Cryptography](https://en.wikipedia.org/wiki/Cryptography) is the discipline that studies methods to communicate secrets in such a way that any unauthorized listener would not be able to understand the message.\n",
    892     "\n",
    893     "A simple cryptographic protocol could be changing every letter of your text following a fixed scheme (or *cypher*), for example by turning every A into a B, every B into a C and so on. However this is not a very secure method, for many reasons. One of them is that at some point the people who want to communicate need to agree on what method to use, and anyone listening to that conversation would be able to decypher every subsequent conversation. A public-key cryptographic protocol solves this problem.\n",
    894     "\n",
    895     "## Public-key cryptography\n",
    896     "\n",
    897     "Public-key cryptographic protocols, such as RSA, work like this: there are two keys, a *private* key that is only known to person A (traditionally called Alice in every example), and a *public* key that does not need to be secret.\n",
    898     "\n",
    899     "The public key is used to *encrypt* the message (that is to \"lock\" it, or \"hyde\" it), but one needs the private key to *decrypt* it. Imagine having two keys for your door, but one can only be used to lock it, while the other only to open it.\n",
    900     "\n",
    901     "The message exchange works like this: suppose that person B (Bob) wants to send a secret message to Alice. Then Alice secretely generates a private and a public key and sends only the public one to Bob. Now Bob encrypts the message and sends it to Alice, who can use her private key to decrypt it. Even if Eve (short for *eavesdropper*, an unauthorized listener) listens to every message exchanged, she won't be able to decypher the secret: the private key has never left Alice's house!\n",
    902     "\n",
    903     "Notice that such a protocol is *asymmetric*: if Alice wanted to send a secret to Bob in reply, Bob would need to generate a pair of keys of his own.\n",
    904     "\n",
    905     "Let's see how we can do this in practice, using number theory!\n",
    906     "\n",
    907     "## RSA\n",
    908     "\n",
    909     "As many other cryptography protocols, RSA is based on a Mathematical process that is easy to do in one direction, but very hard to invert. In this case the hard process is integer factorization, that is decomposing an integer number as a product of primes."
    910    ]
    911   },
    912   {
    913    "cell_type": "code",
    914    "execution_count": 5,
    915    "metadata": {},
    916    "outputs": [
    917     {
    918      "name": "stdout",
    919      "output_type": "stream",
    920      "text": [
    921       "True True False\n"
    922      ]
    923     },
    924     {
    925      "data": {
    926       "text/plain": [
    927        "1 loop, best of 1: 9.06 s per loop"
    928       ]
    929      },
    930      "execution_count": 5,
    931      "metadata": {},
    932      "output_type": "execute_result"
    933     }
    934    ],
    935    "source": [
    936     "p = 100003100019100043100057100069\n",
    937     "q = 100144655312449572059845328443\n",
    938     "n = p*q\n",
    939     "print(is_prime(p), is_prime(q), is_prime(p*q))\n",
    940     "\n",
    941     "# Use the command below to see how long it takes\n",
    942     "timeit(\"factor(n)\", number=1, repeat=1)"
    943    ]
    944   },
    945   {
    946    "cell_type": "markdown",
    947    "metadata": {},
    948    "source": [
    949     "In order to generate the keys, Alice picks a number $n$ which is the product of two large primes $p$ and $q$ of more or less the same size. Finding such primes is relatively easy compared to factoring the number $n$ she obtained. Then she computes the Euler totient $\\varphi(n)=(p-1)(q-1)$ of $n$, which she can do because she knows that $n=pq$ - it would be impossible otherwise!\n",
    950     "\n",
    951     "Then Alice can compute two integers $(d,e)$ such that $de\\equiv 1\\pmod{\\varphi(n)}$. She will send the numbers $n$ and $d$ to Bob and keep $e$ secret. In this case the public key is the pair $(n,d)$, while $e$ is the private key.\n",
    952     "\n",
    953     "Of course, she does all of this using Sage!"
    954    ]
    955   },
    956   {
    957    "cell_type": "code",
    958    "execution_count": 6,
    959    "metadata": {},
    960    "outputs": [
    961     {
    962      "data": {
    963       "text/plain": [
    964        "(338547806707501, 141995674537431, 107165393087271)"
    965       ]
    966      },
    967      "execution_count": 6,
    968      "metadata": {},
    969      "output_type": "execute_result"
    970     }
    971    ],
    972    "source": [
    973     "def two_large_primes():\n",
    974     "    p, q = 0, 0\n",
    975     "    # We make sure that they are different\n",
    976     "    while p == q:\n",
    977     "        p = Primes()[randint(10^6, 2*10^6)]\n",
    978     "        q = Primes()[randint(10^6, 2*10^6)]\n",
    979     "    return p, q\n",
    980     "\n",
    981     "def random_unit_mod(N):\n",
    982     "    R = Integers(N)\n",
    983     "    d = R(0)\n",
    984     "    # We make sure that it is invertible\n",
    985     "    while not d.is_unit():\n",
    986     "        d = R.random_element()\n",
    987     "    return d\n",
    988     "\n",
    989     "def Alice_generate_keys():\n",
    990     "    p, q = two_large_primes()\n",
    991     "    n = p*q\n",
    992     "    phi_n = (p-1)*(q-1) # euler_phi(n) is slow!\n",
    993     "    \n",
    994     "    d = random_unit_mod(phi_n)\n",
    995     "    e = d^-1\n",
    996     "    return n, d, e\n",
    997     "\n",
    998     "Alice_generate_keys()"
    999    ]
   1000   },
   1001   {
   1002    "cell_type": "markdown",
   1003    "metadata": {},
   1004    "source": [
   1005     "Now, how does Bob encrypt his message? Let's say he wants to send to Alice the number $m$ with $1<m<n$ (In practice he would like to send her some text with emojis, or maybe a voice message; but for computers everything is a number, and there are different ways to translate any sort of information to a number. He just chooses one of the many standard methods that already exist, no cryptography is needed in this step. If the message $m$ is too long, he can split it up in some pieces and repeat the process multiple times.)\n",
   1006     "\n",
   1007     "Now he computes $m^d\\pmod n$ and sends it back to Alice."
   1008    ]
   1009   },
   1010   {
   1011    "cell_type": "code",
   1012    "execution_count": 7,
   1013    "metadata": {},
   1014    "outputs": [
   1015     {
   1016      "data": {
   1017       "text/plain": [
   1018        "177776139844621"
   1019       ]
   1020      },
   1021      "execution_count": 7,
   1022      "metadata": {},
   1023      "output_type": "execute_result"
   1024     }
   1025    ],
   1026    "source": [
   1027     "def Bob_encrypt(m, n, d):\n",
   1028     "    R = Integers(n)\n",
   1029     "    return R(m)^d  # Assume that n is large enough\n",
   1030     "    \n",
   1031     "message = 42424242\n",
   1032     "Bob_encrypt(message, 338547806707501, 141995674537431)"
   1033    ]
   1034   },
   1035   {
   1036    "cell_type": "markdown",
   1037    "metadata": {},
   1038    "source": [
   1039     "Since $de\\equiv 1\\pmod{\\varphi(n)}$, it follows that $(m^d)^e\\equiv m\\pmod n$ (see [Wikipedia: Euler's theorem](https://en.wikipedia.org/wiki/Euler%27s_theorem)). So for Alice it is very easy to get back the original message:"
   1040    ]
   1041   },
   1042   {
   1043    "cell_type": "code",
   1044    "execution_count": 8,
   1045    "metadata": {},
   1046    "outputs": [
   1047     {
   1048      "data": {
   1049       "text/plain": [
   1050        "42424242"
   1051       ]
   1052      },
   1053      "execution_count": 8,
   1054      "metadata": {},
   1055      "output_type": "execute_result"
   1056     }
   1057    ],
   1058    "source": [
   1059     "def Alice_decrypt(m_encrypted, n, e):\n",
   1060     "    R = Integers(n)\n",
   1061     "    return R(m_encrypted)^e\n",
   1062     "\n",
   1063     "Alice_decrypt(177776139844621, 338547806707501, 107165393087271)"
   1064    ]
   1065   },
   1066   {
   1067    "cell_type": "markdown",
   1068    "metadata": {},
   1069    "source": [
   1070     "Another assumption on which RSA relies is that even if one knows $M=m^e$ and $e$, extracting the $e$-th root of $M$ modulo $n$ (and thus obtaining $m$) is very hard. Currently the best known way to do this is by factorizing $n$ first, which is considered to be a very hard problem. However, there is no proof that faster algorithms can't be devised.\n",
   1071     "\n",
   1072     "Moreover, one day we will overcome the current technological difficulties and quantum computers will be available. Quantum computers are not just \"more powerful\" than classical hardware, but they work based on completely different logical foundations and they make the factorization problem much easier to solve: for example [Shor's algorithm](https://en.wikipedia.org/wiki/Shor%27s_algorithm) takes advantage of this different logic and can factorize numbers quickly, if run on a quantum computer.\n",
   1073     "\n",
   1074     "To this day the largest number factorized with a quantum computer is $21=3\\times 7$. Nonetheless, quantum-safe cryptography protocols (i.e. based on problems that are hard to solve also with quantum computers) have already been developed."
   1075    ]
   1076   }
   1077  ],
   1078  "metadata": {
   1079   "kernelspec": {
   1080    "display_name": "SageMath 9.0",
   1081    "language": "sage",
   1082    "name": "sagemath"
   1083   },
   1084   "language_info": {
   1085    "codemirror_mode": {
   1086     "name": "ipython",
   1087     "version": 3
   1088    },
   1089    "file_extension": ".py",
   1090    "mimetype": "text/x-python",
   1091    "name": "python",
   1092    "nbconvert_exporter": "python",
   1093    "pygments_lexer": "ipython3",
   1094    "version": "3.8.10"
   1095   }
   1096  },
   1097  "nbformat": 4,
   1098  "nbformat_minor": 4
   1099 }