\documentclass{memoir}
\usepackage{notestemplate}

%\logo{./resources/pdf/logo.pdf}
%\institute{Rice University}
%\faculty{Faculty of Whatever Sciences}
%\department{Department of Mathematics}
%\title{Class Notes}
%\subtitle{Based on MATH xxx}
%\author{\textit{Author}\\Gabriel \textsc{Gress}}
%\supervisor{Linus \textsc{Torvalds}}
%\context{Well, I was bored...}
%\date{\today}

\begin{document}

% \maketitle

% Notes taken on 01/27/21

\begin{defn}[Norm of Integral Domain]
	Let \(R\) be an integral domain. Any function \(N:R\to \Z^{+}\cup \left\{ 0 \right\} \) with \(N(0)\) is called a \textbf{norm} on the integral domain \(R\). If \(N(a) > 0\) for \(a\neq 0\) then \(N\) is a \textbf{positive norm}
\end{defn}
This is a pretty loose construction, and an integral domain can have many norms on it.\\

\begin{defn}[Euclidean Function]
	An integral domain \(R\) is a \textbf{Euclidean Domain} if there exists a norm called the \textbf{Euclidean function} \(N:R\setminus\left\{ 0 \right\} \to \N\) that satisfies \(\forall a,b \in R\setminus \left\{ 0 \right\} \):
	\begin{align*}
		N(ab) \geq \textrm{max}\left\{ N(a),N(b) \right\}\\
		\exists q,r \in R \text{ such that }a = qb + r \text{ and }\left[ r = 0 \text{ or }N(r)<N(b) \right]
	\end{align*}
	We call the element \(q\) the \textbf{quotient} and the element \(r\) the  \textbf{remainder}.
\end{defn}
The existence of a Euclidean function is integral to constructing a Euclidean algorithm to perform division of elements \(a,b \in R\). We can perform successive divisions to get
\begin{align*}
	a = q_0b + r_0\\
	b = q_1r_0 + r_1\\
	r_0 = q_2r_1 + r_2\\
	\vdots\\
	r_{n-1}= q_nr_{n-1}+r_n\\
	r_{n-1} = q_{n+1}r_n
\end{align*}
where \(r_n\) is the last nonzero remainder. This \(r_n\) always exists as the norms form a decreasing sequence of nonnegative integers. However, these elements are not necessarily unique.

\begin{prop}
	Every ideal in a Euclidean Domain is principal. That is, if \(I\triangleleft R\) is a nontrivial ideal in \(R\), then \(I = (d)\) for some nonzero element of \(I\) with minimum norm.
\end{prop}
This also makes it convenient to show an integral domain is not a Euclidean Domain by simply finding a non-principal ideal. Moreover, it motivates the notion of greatest common divisors from \(\Z\) into comumutative rings.

\begin{defn}[Greatest Common Divisor]
	Let \(R\) be a commutative ring and let \(a,b \in R\) with \(b\neq 0\). Then \(a\) is said to be a \textbf{multiple} of \(b\) if there exists an element \(x \in R\) with \(a=bx\). In this case, we say \(b\) \textbf{divides} \(a\) (or is a \textbf{divisor} of \(a \)) written \(b\mid a\).\\

	A \textbf{greatest common divisor} of \(a,b\) is a nonzero element \(d\) such that
	\begin{align*}
		d \mid a, \; d \mid b \\
		d'\mid a \; d'\mid b \implies d'\mid d
	\end{align*}
	We will denote a greatest common divisor by \(\textrm{gcd}(a,b)\), or sometimes simply \((a,b)\) if it is clear from context.\\

	If \(gcd(a,b) = 1_R\), then we say that \(a\) and \(b\) are \textbf{relatively prime}.
\end{defn}
We can easily extend this to finite sequences of elements \((a_1,a_2,\ldots,a_n)\).\\

Recall that in a ring \(b\mid a \iff a \in (b) \iff (a) \subset (b)\). Hence, we can discuss greatest common factors in terms of ideals. That is, if \(I = (a,b)\) is the ideal of \(R\) generated by \(a,b\), then \(d = \textrm{gcd}(a,b)\) if \(I\subset (d)\) and if \(I\subset (d') \implies (d)\subset (d')\). Thus, it is the unique smallest principal ideal containing \(a\) and \(b\). However, it may not exist in all rings.

\begin{prop}[Sufficient Conditions for Existence]
	If \(a,b \in R\) are nonzero elements in a commutative ring such that \(I = (a,b) = (d)\), then \(d\) is the greatest common divisor of \(a,b\).
\end{prop}
Obviously this is a sufficient and not a necessary condition. But it also clarifies why \((a,b)\) is used both for ideals and greatest common divisors. Any integral domain that satisfies the above condition for all ideals of two elements is called a \textbf{Bezout Domain}.

\begin{prop}
	Let \(R\) be an integral domain. If two elements \(d,d' \in R\) generate the same principal ideal, i.e. \((d) = (d')\), then \(d' = ud\) for some unit \(u \in R\). In particular, this tells us that greatest common divisors are unique up to units.
\end{prop}

\begin{thm}
	Let \(R\) be a Euclidean Domain and let \(a,b \in R\) be nonzero. Let \(d = r_n\) be the last nonzero remainder in the Euclidean Algorithm for \(a,b\) described earlier. Then \(d = \textrm{gcd}(a,b)\) and \((d) = (a,b)\). That is, \(d\) can be written as an \textbf{\(R\)-linear combination} of \(a,b\):
	\begin{align*}
		d = ax+by
	\end{align*}
	for some \(x,y \in R\).
\end{thm}
Notice that \(x,y\) are not unique in this case. One can show that that if \(x_0,y_0\) are solutions to
\begin{align*}
	ax+by=N
\end{align*}
then any other solutions are of the form
\begin{align*}
	x = x_0 + m \frac{b}{(a,b)}\\
	y = y_0 - m \frac{a}{(a,b)}
\end{align*}
for \(m \in \Z\). This is really strong as it gives a complete solution of the first order Diophantine equation provided we have one solution. Our work here essentially tells us that \(ax+by = N\) is solvable in integers \(x,y\) if and only if \(\textrm{gcd}(a,b)\mid N\).

\begin{proof}

\end{proof}

Finally, we discuss a definition that is useful to determine whether an integral domain is a Euclidean Domain.
\begin{defn}[Universal Side Divisor]
	Let \(R\) be an integral domain, and define \(\tilde{R}= R^{\times }\cup \left\{ 0 \right\} \). We say an element \(u \in R-\tilde{R}\) is a \textbf{universal side divisor} if for every \(x \in R\) there is a \(z \in \tilde{R}\) such that
	\begin{align*}
		u\mid x-z
	\end{align*}
	That is, every \(x\) can be written
	\begin{align*}
		x = qu + z
	\end{align*}
	where \(z\) is either zero or a unit.
\end{defn}

\begin{prop}
	Let \(R\) be an integral domain that is not a field. If \(R\) is a Euclidean Domain, then there exist universal side divisors in \(R\).
\end{prop}
It is often simpler to show that an integral domain can't have universal side divisors by assuming one exists of minimal norm, finding candidates, then showing they fail to satisfy the necessary properties.

\begin{hw}
	Let \(F = \Q(\sqrt{D} )\) be a quadratic field with quadratic integer ring \(\mathcal{O}\) and field norm \(N\).
	\begin{itemize}
		\item Suppose \(D \in \left\{ -1,-2,-3,-7,-11 \right\} \). Prove that \(\mathcal{O}\) is a Euclidean Domain with respect to \(N\). %Hint: Modify the proof for Z[i] in the text. For D = -3,-7, -11, prove that every element of F differs from an element in O by an element whose norm is at most (1+|D|)^2 / (16|D|), which is less than 1 for these values. Plotting the points of O might be helpful
		\item Suppose that \(D \in \left\{ -43,-67,-163 \right\} \). Prove that \(\mathcal{O}\) is not a Euclidean Domain with respect to any norm. %Apply same proof as D = -19 from text
	\end{itemize}
	These numbers are specially chosen because they are the only negative values of \(D\) that makes every ideal in \(\mathcal{O}\) principal.
\end{hw}

\subsection{Principal Ideal Domains}
\label{sub:principal_ideal_domains}

\begin{defn}[Princiapl Ideal Domain]
	A \textbf{Principal Ideal Domain} is an integral domain in which every ideal is principal.
\end{defn}
We have already shown that every Euclidean Domain is a Principal Ideal Domain. The converse does not hold. The biggest difference from a practicality angle is that while PIDs have gcds, there is no algorithm to compute them.

\begin{prop}
	Let \(R\) be a Principal Ideal Domain and let \(a,b \in R\) be nonzero. Let \(d\) be a generator for the principal ideal generated by \(a,b\). Then \(d = \textrm{gcd}(a,b)\) and can be written as an \(R\)-linear combination
	\begin{align*}
		d = ax+by
	\end{align*}
	for \(x,y \in R\). Finally, \(d\) is unique up to multiplication by a unit.
\end{prop}
Recall that maximal ideals are always prime ideals but the converse is not true in general. Fortunately, PIDs have enough structure so this holds.

\begin{prop}
	Every nonzero prime ideal in a Principal Ideal Domain is a maximal ideal.
\end{prop}
\begin{proof}% Try yourself

\end{proof}

\begin{cor}
	If \(R\) is any commutative ring such that \(R[x]\) is a PID, then \(R\) is necessarily a field.
\end{cor}
\begin{proof}

\end{proof}

We construct some definitions that help us distinguish PIDs and EDs.

\begin{defn}[Dedeking-Hasse Norm]
	Define \(N\) to be a \textbf{Dedekind-Hasse norm} if \(N\) is a positive norm and for every \(a,b \in R\) nonzero either \(a \in (b)\) or there exists \(s,t \in R\) with \(0 < N(sa-tb) < N(b)\) (that is, a nonzero element in the ideal \((a,b)\) with norm smaller than \(b\)).
\end{defn}
This is a weakening of the Euclidean condition. \(R\) is an ED with respect to a positive norm \(N\) if it is always possble to satisfy the above condition with \(s=1\).

\begin{prop}
	The integral domain \(R\) is a PID if and only if \(R\) has a Dedeking-Hasse norm.
\end{prop}

\begin{exmp}
	%Show that in Z[1+sqrt(-19) / 2] N()=a^2+ab+5b%2 is a Dedekind-Hasse norm
\end{exmp}

\subsection{Unique Factorization Domain}
\label{sub:unique_factorization_domain}

Unique Factorization Domains capture the idea that some rings admit a proper factorization on elements.

\begin{defn}[Reducibility and Primes]
	Let \(R\) be an integral domain
	\begin{itemize}
		\item Suppose \(r \in R\) is nonzero and not a unit. Then \(r\) is called \textbf{irreducible in \(R\)} if for all \(a,b \in R\), \(r = ab\) implies that either \(a\) or \(b\) is a unit. Otherwise, we say \(r\) is \textbf{reducible}.
		\item Let \(p \in R\) be nonzero. We say it is \textbf{prime in \(R\)} if the ideal \((p)\) is a prime ideal. An equivalent statement is that \(p\) is not a unit and if \(p\mid ab\), then \(p\mid a\) or \(p\mid b\).
		\item If \(a=ub\) for \(a,b \in R\) and \(u \in R\) a unit, then we say \(a\) and \(b\) are \textbf{associates}.
	\end{itemize}
\end{defn}

\begin{prop}
	In an integral domain, a prime element is always irreducible.
\end{prop}
The converse does not hold in general. However, in a PID, the converse does hold.

\begin{proof}% Try yourself, also try showing that in a PID it does hold

\end{proof}
This is also a useful tool to show a ring is not a PID.

\begin{defn}[Proper Factorization]
	Let \(a \in R\) be a nonzero nonunit. A \textbf{proper factorization} of \(a\) is a finite product \(a=p_1p_2\ldots p_n\), where \(p_i\) are not units of \(R\). If this exists, we say \(\left\{ p_i \right\} \) are \textbf{proper factors} of \(a\).
\end{defn}
Of course, an irreducible element has no proper factorizations.

\begin{defn}[Unique Factorization Domain]
	An integral domain \(R\) is a \textbf{unique factorization domain} if every nonzero, non-unit element has a proper factorization
	\begin{align*}
		r = p_1p_2\ldots p_n
	\end{align*}
	where \(\left\{ p_i \right\} \) are irreducible elements and unique up to associates and reordering.
\end{defn}
It turns out that primes are equivalent to irreducibles in a UFD as well.

\begin{prop}
	In a Unique Factorization Domain, a nonzero element is a prime if and only if it is an irreducible.
\end{prop}
We will also see that UFDs admit a greatest common divisor via its factorization

\begin{prop}
	Let \(a,b \in R\) be nonzero elements of a UFD \(R\) and suppose
	\begin{align*}
		a = up_1^{e_1}p_2^{e_2}\ldots p_n^{e_n}\\
		b= v p_1^{f_1}p_2^{f_2}\ldots p_n^{f_n}
	\end{align*}
	are prime factorizations with \(u,v\) units, primes \(p_1,p_2,\ldots,p_n\) distinct, and exponents \(e_i,f_i \geq 0\). Then the element
	\begin{align*}
		d = p_1^{\textrm{min}(e_1,f_1)}p_2^{\textrm{min}(e_2,f_2)}\ldots p_n^{\textrm{min}(e_n,f_n)}
	\end{align*}
	is a greatest common divisor of \(a\) and \(b\).
\end{prop}

\begin{hw}
	Let \(R\) be a UFD.
	\begin{enumerate}[(a).]
		\item Let \(b\) and \(a_1,\ldots,a_s\) be nonzero elements of \(R\). For \(d \in R\), show that
			\begin{align*}
				bd = gcd(ba_1,\ldots,ba_s) \iff d = gcd(a_1,\ldots,a_s)
			\end{align*}
		\item Let \(f(x) \in R[x]\) where \(f(x) = bf_1(x)\) for \(f_1(x)\) \textbf{primitive} (i.e. \(gcd(\text{coefficients of }f_1(x)) = 1_R\) ). Show that
			\begin{align*}
				b = gcd(\left\{ \text{coefficients of }f(x) \right\} ).
			\end{align*}
	\end{enumerate}
\end{hw}

This leads us to the full description of the structure of these domains.

\begin{thm}
	Every Principal Ideal Domain is a Unique Factorization Domain. Hence, every Euclidean Domain is a Unique Factorization Domain.
\end{thm}
\begin{proof}

\end{proof}

This forms a strict classification hierarchy by
\begin{align*}
	\textbf{Euclidean Domains} \subset \textbf{Principal Ideal Domains} \subset \textbf{Unique Factorization Domains} \subset \textbf{Integral Domains} \subset \textbf{commutative rings}
\end{align*}

\begin{cor}
	The integers \(\Z\) are a UFD.
\end{cor}

\begin{cor}
	Let \(R\) be a PID. Then there exists a multiplicative Dedekind-Hausse norm on \(R\).
\end{cor}

\end{document}

Abstract Algebra - Introductory/Algebra II/Notes/source/Lecture2 - ED_UFD_PID.tex


\providecommand{\main}{../..}
\documentclass[\main/thesis.tex]{subfiles}
\begin{document}

\section{Digit: the basic building block}\label{digit}

As the fundamental building block of numerals, we will devise a suitable
representation for digits in this section.

\subsection{Fin}

To represent a digit, we use a datatype conventionally called \textit{Fin}
which can be indexed to have an exact number of inhabitants.

\begin{lstlisting}
data Fin : ℕ → Set where
    zero : {n : ℕ} → Fin (suc n)
    suc  : {n : ℕ} (i : Fin n) → Fin (suc n)
\end{lstlisting}

The definition of {\lstinline|Fin|} looks the same as {\lstinline|ℕ|} on the term
level, but different on the type level. The index of a {\lstinline|Fin|} increases
with every {\lstinline|suc|}, and there can only be at most {\lstinline|n|} of
them before reaching {\lstinline|Fin (suc n)|}. In other words, {\lstinline|Fin n|}
has exactly \textit{n} inhabitants.

\subsection{Definition of \lstinline|Digit|}

{\lstinline|Digit|} is simply just a synonym for {\lstinline|Fin|}, indexed by
the number of digits {\lstinline|d|} of a system.
Since the same digit may represent different values in different numeral systems,
it is essential to make the context clear.

\begin{lstlisting}
Digit : ℕ → Set
Digit d = Fin d
\end{lstlisting}

Ordinary binary digits for example can thus be represented as:

\begin{lstlisting}
Binary : Set
Binary = Digit 2

零 : Binary
零 = zero

一 : Binary
一 = suc zero
\end{lstlisting}

\subsection{Digit Assignment}

\begin{center}
    \begin{adjustbox}{max width=\textwidth}
        \begin{tikzpicture}
            % the frame
            \path[clip] (-1, -1) rectangle (11, 2);
            % the spine
            \draw[ultra thick] (0,0) -- (1,0);
            \draw[ultra thick] (9,0) -- (10,0);
            % the body

            \foreach \i in {1,...,8} {
                \draw[ultra thick, fill=white] ({\i+0.05}, -0.2) rectangle ({\i+0.95}, +0.2);
            };

            % ticks
            \draw (0,0.2) -- (0,-0.2) node[below] {$0$};

            % labels
            \draw[->, ultra thick] (1.5,1) -- (1.5,0.5)
                node at (1.5, 1.3) {$o$};
            \draw[->, ultra thick] (8.5,1) -- (8.5,0.5)
                node at (8.5, 1.3) {$o+d$};
            \node at (5, -0.7) {{\lstinline|ℕ|}};
        \end{tikzpicture}
    \end{adjustbox}
\end{center}

Digits are assigned to {\lstinline|ℕ|} together with the offset {\lstinline|o|}
of a system, ranging from $ o $ to $ d + o $.

\begin{lstlisting}
Digit-toℕ : ∀ {d} → Digit d → ℕ → ℕ
Digit-toℕ x o = toℕ x + o
\end{lstlisting}
\footnote{
    {\lstinline|toℕ : ∀ {n} → Fin n → ℕ|}
    \newline\hspace*{4em} converts from {\lstinline|Fin n|} to {\lstinline|ℕ|}.
}

However, not all natural numbers can be converted to digits.
The value has to be in a certain range, between $ o $ and $ d + o $.
Values less than $ o $ are increased to $ o $.
Values greater than $ d + o $ are prohibited by the supplied upper-bound.

\begin{lstlisting}
Digit-fromℕ : ∀ {d}
    → (n o : ℕ)
    → (upper-bound : d + o ≥ n)
    → Digit (suc d)
Digit-fromℕ {d} n o upper-bound with n ∸ o ≤? d
Digit-fromℕ {d} n o upper-bound | yes p = fromℕ≤ (s≤s p)
Digit-fromℕ {d} n o upper-bound | no ¬p = contradiction p ¬p
    where   p : n ∸ o ≤ d
            p = start
                    n ∸ o
                ≤⟨ ∸n-mono o upper-bound ⟩
                    (d + o) ∸ o
                ≈⟨ m+n∸n≡m d o ⟩
                    d
                □
\end{lstlisting}
\footnote{
    {\lstinline|fromℕ≤ : ∀ {m n} → m < n → Fin n|}
    \newline\hspace*{4em} converts from {\lstinline|ℕ|} to {\lstinline|Fin n|} given the number is small enough.
}

\subsubsection{Properties of \lstinline|Digit|}

\begin{center}
    \begin{tikzpicture}
        \matrix (m) [matrix of nodes,row sep=6em,column sep=8em,minimum width=4em]
            {
                {\lstinline|ℕ|} & {\lstinline|Digit d|} \\
            };
        \path[-stealth]
            ($(m-1-1.east)+(0,+0.1)$)
                edge node [above] {{\lstinline|Digit-fromℕ|}}
                ($(m-1-2.west)+(0,+0.1)$)
            ($(m-1-2.west)+(0,-0.1)$)
                edge node [below] {{\lstinline|Digit-toℕ|}}
                ($(m-1-1.east)+(0,-0.1)$)
            ;
    \end{tikzpicture}
\end{center}

{\lstinline|Digit-fromℕ-toℕ|} states that the value of a natural number should
remain the same, after converting back and forth between {\lstinline|Digit|} and
{\lstinline|ℕ|}.

\begin{lstlisting}
Digit-fromℕ-toℕ : ∀ {d o}
    → (n : ℕ)
    → (lower-bound :     o ≤ n)
    → (upper-bound : d + o ≥ n)
    → Digit-toℕ (Digit-fromℕ {d} n o upper-bound) o ≡ n
Digit-fromℕ-toℕ {d} {o} n lb ub with n ∸ o ≤? d
Digit-fromℕ-toℕ {d} {o} n lb ub | yes q =
    begin
        toℕ (fromℕ≤ (s≤s q)) + o
    ≡⟨ cong (λ x → x + o) (toℕ-fromℕ≤ (s≤s q)) ⟩
        n ∸ o + o
    ≡⟨ m∸n+n≡m lb ⟩
        n
    ∎
Digit-fromℕ-toℕ {d} {o} n lb ub | no ¬q = contradiction q ¬q
    where   q : n ∸ o ≤ d
            q = +n-mono-inverse o (
                start
                    n ∸ o + o
                ≈⟨ m∸n+n≡m lb ⟩
                    n
                ≤⟨ ub ⟩
                    d + o
                □)
\end{lstlisting}
\footnote{
    {\lstinline|toℕ-fromℕ≤ : ∀ {m n} (m<n : m < n) → toℕ (fromℕ≤ m<n) ≡ m|}
    \newline\hspace*{4em} states that a number should remain the same after converting back and forth.
}

Digits have a upper-bound and a lower-bound after evaluated to \lstinline|ℕ|.

\begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
Digit-upper-bound : ∀ {d} → (o : ℕ) → (x : Digit d) → Digit-toℕ x o < d + o
Digit-upper-bound {d} o x = +n-mono o (bounded x)

Digit-lower-bound : ∀ {d} → (o : ℕ) → (x : Digit d) → Digit-toℕ x o ≥ o
Digit-lower-bound {d} o x = m≤n+m o (toℕ x)
\end{lstlisting}
\footnote{
    {\lstinline|bounded : ∀ {n} (i : Fin n) → toℕ i < n|}
    \newline\hspace*{4em} a property about the upper-bound of a {\lstinline|Fin n|}.
}

\subsection{Functions on \lstinline|Digit|}

\subsubsection{Increment}

To increment a digit, the digit must not be \textit{the greatest}.

\begin{lstlisting}
digit+1 : ∀ {d}
    → (x : Digit d)
    → (¬greatest : ¬ (Greatest x))
    → Digit d
digit+1 x ¬greatest =
    fromℕ≤ {suc (toℕ x)} (≤∧≢⇒< (bounded x) ¬greatest)
\end{lstlisting}
%
where {\lstinline|≤∧≢⇒< (bounded x) ¬greatest : suc (toℕ x) < d|}.

\begin{center}
    \begin{tikzpicture}
        \matrix (m) [matrix of nodes,row sep=6em,column sep=8em,minimum width=4em]
            {
                {\lstinline|Digit d|} & {\lstinline|Digit d|} \\
                {\lstinline|ℕ|} & {\lstinline|ℕ|} \\
            };
      \path[-stealth]
            (m-1-1)
                edge node [left] {{\lstinline|Digit-toℕ|}} (m-2-1)
                edge node [above] {{\lstinline|digit+1|}} (m-1-2)
            (m-2-1.east|-m-2-2)
                edge node [below] {{\lstinline|suc|}} (m-2-2)
            (m-1-2)
                edge node [right] {{\lstinline|Digit-toℕ|}} (m-2-2);
                % edge [dashed,-] (m-2-1);
    \end{tikzpicture}
\end{center}

A digit taking these two routes should result in the same {{\lstinline|ℕ|}}.

\begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
digit+1-toℕ : ∀ {d o}
    → (x : Digit d)
    → (¬greatest : ¬ (Greatest x))
    → Digit-toℕ (digit+1 x ¬greatest) o ≡ suc (Digit-toℕ x o)
digit+1-toℕ {d} {o} x ¬greatest =
    begin
        Digit-toℕ (digit+1 x ¬greatest) o
    ≡⟨ cong (λ w → w + o) (toℕ-fromℕ≤ (≤∧≢⇒< (bounded x) ¬greatest)) ⟩
        suc (Digit-toℕ x o)
    ∎
\end{lstlisting}

\subsubsection{Increase and then Subtract}

Increases a digit and then subtract it by $ n $.
This function is useful for implementing \textit{carrying}.
When the digit to increase is already the greatest,
it has to be subtracted from an amount (usually the base) after the increment.

\begin{lstlisting}
digit+1-n : ∀ {d}
    → (x : Digit d)
    → Greatest x
    → (n : ℕ)
    → n > 0
    → Digit d
digit+1-n x greatest n n>0 =
    fromℕ≤ (digit+1-n-lemma x greatest n n>0)
\end{lstlisting}

\begin{center}
    \begin{tikzpicture}
        \matrix (m) [matrix of nodes,row sep=4em,column sep=6em,minimum width=2em]
            {
                {\lstinline|Digit d|} & & {\lstinline|Digit d|} \\
                {\lstinline|ℕ|} & {\lstinline|ℕ|} & {\lstinline|ℕ|} \\
            };
      \path[-stealth]
            (m-1-1)
                edge node [left] {{\lstinline|Digit-toℕ|}} (m-2-1)
                edge node [above] {{\lstinline|digit+1-n|}} (m-1-3)
            (m-2-1)
                edge node [below] {{\lstinline|suc|}} (m-2-2)
            (m-2-2)
                edge node [below] {{\lstinline|∸ n|}} (m-2-3)
            (m-1-3)
                edge node [right] {{\lstinline|Digit-toℕ|}} (m-2-3);
    \end{tikzpicture}
\end{center}

A digit taking these two routes should result in the same {{\lstinline|ℕ|}}.

\begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
digit+1-n-toℕ : ∀ {d o}
    → (x : Digit d)
    → (greatest : Greatest x)
    → (n : ℕ)
    → (n>0 : n > 0)
    → n ≤ d
    → Digit-toℕ (digit+1-n x greatest n n>0) o ≡ suc (Digit-toℕ x o) ∸ n
digit+1-n-toℕ {zero}  {o} () greatest n n>0 n≤d
digit+1-n-toℕ {suc d} {o} x greatest n n>0  n≤d =
    begin
        toℕ (digit+1-n x greatest n n>0) + o
    ≡⟨ cong (λ w → w + o) (toℕ-fromℕ≤ (digit+1-n-lemma x greatest n n>0)) ⟩
        suc (toℕ x) ∸ n + o
    ≡⟨ +-comm (suc (toℕ x) ∸ n) o ⟩
        o + (suc (toℕ x) ∸ n)
    ≡⟨ sym (+-∸-assoc o {suc (toℕ x)} {n} (
        start
            n
        ≤⟨ n≤d ⟩
            suc d
        ≈⟨ sym greatest ⟩
            suc (toℕ x)
        □)
    ⟩
        (o + suc (toℕ x)) ∸ n
    ≡⟨ cong (λ w → w ∸ n) (+-comm o (suc (toℕ x))) ⟩
        suc (toℕ x) + o ∸ n
    ∎)
\end{lstlisting}

\subsection{Special Digits}

\subsubsection{The Greatest Digit}

The greatest digit of a system is constructed by converting the index
{\lstinline|d|} to {\lstinline|Fin|}.

\begin{lstlisting}
greatest-digit : ∀ d → Digit (suc d)
greatest-digit d = fromℕ d
\end{lstlisting}
\footnote{
    {\lstinline|fromℕ : ∀ {n} → Fin n → ℕ|}
    \newline\hspace*{4em} construct the greatest possible {\lstinline|Fin n|}
    when given an index {\lstinline|n|}.
}

\paragraph{predicates}

We can see whether a digit is the greatest by converting it to {\lstinline|ℕ|}.
This predicate also comes with a decidable version.

\begin{lstlisting}
Greatest : ∀ {d} (x : Digit d) → Set
Greatest {d} x = suc (toℕ x) ≡ d

Greatest? : ∀ {d} (x : Digit d) → Dec (Greatest x)
Greatest? {d} x = suc (toℕ x) ≟ d
\end{lstlisting}

\paragraph{properties}

Converting from the greatest digit to {\lstinline|ℕ|} should result in
{\lstinline|d + o|}.

\begin{lstlisting}
greatest-digit-toℕ : ∀ {d o}
    → (x : Digit (suc d))
    → Greatest x
    → Digit-toℕ x o ≡ d + o
greatest-digit-toℕ {d} {o} x greatest = cancel-suc (
    begin
        suc (Digit-toℕ x o)
    ≡⟨ refl ⟩
        suc (toℕ x) + o
    ≡⟨ cong (λ w → w + o) greatest ⟩
        suc d + o
    ∎)
\end{lstlisting}

A digit is the greatest if and only if it is greater than or equal to all other
digits. This proposition is proven by induction on both of the compared digits.

\begin{lstlisting}
greatest-of-all : ∀ {d} (o : ℕ) → (x y : Digit d)
    → Greatest x
    → Digit-toℕ x o ≥ Digit-toℕ y o
greatest-of-all o zero    zero     refl     = ≤-refl
greatest-of-all o zero    (suc ()) refl
greatest-of-all o (suc x) zero     greatest
    = +n-mono o {zero} {suc (toℕ x)} z≤n
greatest-of-all o (suc x) (suc y)  greatest
    = s≤s (greatest-of-all o x y (cancel-suc greatest))
\end{lstlisting}

\subsubsection{The Carry}

A carry is a digit that is transferred to a more significant digit to compensate
the ``loss'' of the original digit.

The carry is defined as the greater of these two values:

\begin{itemize}
    \item the least digit of a system
    \item the digit that is assigned to $ 1 $
\end{itemize}

We define the carry as the greater number of $ 1 $ and $ o $.
In case that the least digit (which is determined by $o$) is assigned to $ 0 $,
rendering the carry useless.

\begin{lstlisting}
carry : ℕ → ℕ
carry o = 1 ⊔ o
\end{lstlisting}

The corresponding numeral of the carry is constructed by converting
{\lstinline|carry o|} to {\lstinline|Digit|}.

\begin{lstlisting}
carry-digit : ∀ d o → 2 ≤ suc d + o → Digit (suc d)
carry-digit d o proper =
    Digit-fromℕ
        (carry o)
        o
        (carry-upper-bound {d} proper)
\end{lstlisting}

\paragraph{properties}

The value of the carry should remain the same after convertions.

\begin{lstlisting}
carry-digit-toℕ : ∀ d o
    → (proper : 2 ≤ suc (d + o))
    → Digit-toℕ (carry-digit d o proper) o ≡ carry o
carry-digit-toℕ d o proper
    = Digit-fromℕ-toℕ
        (carry o)
        (m≤n⊔m o 1)
        (carry-upper-bound {d} proper)
\end{lstlisting}

The carry also have an upper-bound and a lower-bound,
similar to that of {\lstinline|Digit|}.

\begin{lstlisting}
carry-lower-bound : ∀ {o} → carry o ≥ o
carry-lower-bound {o} = m≤n⊔m o 1

carry-upper-bound : ∀ {d o} → 2 ≤ suc d + o → carry o ≤ d + o
carry-upper-bound {d} {zero}  proper = ≤-pred proper
carry-upper-bound {d} {suc o} proper = n≤m+n d (suc o)
\end{lstlisting}

\end{document}


\section{Function extensionality}
\label{chap:funext}

\subsection{Equivalent forms of function extensionality}
\begin{defn}
  The \define{axiom of function extensionality} asserts that for any type family $B$ over $A$, and any two dependent functions $f,g:\prd{x:A}B(x)$, the canonical map
  \begin{equation*}
    \mathsf{htpy\usc{}eq}:(f=g)\to (f\htpy g)
  \end{equation*}
  is an equivalence.
\end{defn}

In other words, the axiom of function extensionality asserts that any an identification of any two dependent functions is equivalent to an identification of all their values. By \cref{thm:id_fundamental} there are three equivalent ways of asserting function extensionality. In the following theorem we state one further equivalent condition.

\begin{thm}\label{thm:funext_wkfunext}
The axiom of function extensionality is equivalent to any of the following statements:\index{function extensionality}
\begin{enumerate}
\item
  The principle of \define{homotopy induction}\index{homotopy induction}:
  for any type family $B$ over $A$, any dependent function $f:\prd{x:A}B(x)$, and any family of types $P(g,H)$ indexed by $g:\prd{x:A}B(x)$ and $H:f\htpy g$, the evaluation function
\begin{equation*}
\Big(\prd{g:\prd{x:A}B(x)}{H:f\htpy g}P(g,H)\Big)\to P(f,\mathsf{htpy\usc{}refl}_f)
\end{equation*}
given by $s\mapsto s(f,\mathsf{htpy\usc{}refl}_f)$ has a section.
\item For any type family $B$ over $A$ and any dependent function $f:\prd{x:A}B(x)$, the total space
  \begin{equation*}
    \sm{g:\prd{x:A}B(x)}f\htpy g
  \end{equation*}
  is contractible.
\item The \define{weak function extensionality principle}\index{weak function extensionality} holds: For every type family $B$ over $A$ one has\index{contractible!weak function extensionality}
\begin{equation*}
\Big(\prd{x:A}\iscontr(B(x))\Big)\to\iscontr\Big(\prd{x:A}B(x)\Big).
\end{equation*}
\end{enumerate}
\end{thm}

\begin{proof}
The fact that function extensionality is equivalent to (i) and (ii) follows directly from \cref{thm:id_fundamental}.

To show that function extensionality implies weak function extensionality, suppose that each $B(a)$ is contractible with center of contraction $c(a)$ and contraction $C_a:\prd{y:B(a)}c(a)=y$. Then we take $c\defeq \lam{a}c(a)$ to be the center of contraction of $\prd{x:A}B(x)$. To construct the contraction we have to define a term of type
\begin{equation*}
\prd{f:\prd{x:A}B(x)}c=f.
\end{equation*}
Let $f:\prd{x:A}B(x)$. By function extensionality we have a map $(c\htpy f)\to (c=f)$, so it suffices to construct a term of type $c\htpy f$. Here we take $\lam{a}C_a(f(a))$. This completes the proof that function extensionality implies weak function extensionality.

To prove function extensionality from weak function extensionality, observe that it suffices by \cref{thm:id_fundamental} to show that
\begin{equation*}
\sm{g:\prd{x:A}B(x)}f\htpy g
\end{equation*}
is contractible.

Since the type $\sm{b:B(x)}f(x)=b$ is contractible for each $x:X$, it follows by our assumption of weak function extensionality that the type $\prd{x:A}\sm{b:B(x)}f(x)=b$ is contractible. By \cref{ex:contr_retr} it therefore suffices to show that
\begin{equation*}
\sm{g:\prd{x:A}B(x)}f\htpy g
\end{equation*}
is a retract of the type $\prd{x:A}\sm{b:B(x)}f(x)=b$. We have the functions
\begin{align*}
i & \defeq \ind{\Sigma}(\lam{g}{H}{x}\pairr{g(x),H(x)}) \\
r & \defeq \lam{p}\pairr{\lam{x}\proj 1(p(x)),\lam{x}\proj 2(p(x))}.
\end{align*}
It remains to show that $r\circ i\htpy \idfunc$. This homotopy is constructed by $\Sigma$-induction. Let $g:\prd{x:A}B(x)$ and let $H:f\htpy g$. Then we have
\begin{align*}
r(i(g,H)) & \jdeq r(\lam{x}\pairr{g(x),H(x)}) \\
& \jdeq \pairr{\lam{x}g(x),\lam{x}H(x)} \\
& \jdeq \pairr{g,H}.
\end{align*}
In other words, the homotopy $r\circ i\htpy \idfunc$ is given by $\ind{\Sigma}(\lam{g}{H}\refl{(\pairr{g,H})})$.
\end{proof}

From now on we will assume that the function extensionality axiom holds.

\begin{defn}
  Consider a type family $B$ over $A$ and let $f,g:\prd{x:A}B(x)$. We define
  \begin{equation*}
    \mathsf{eq\usc{}htpy}: (f\htpy g) \to (f = g)
  \end{equation*}
  to be the inverse of $\mathsf{htpy\usc{}eq}$.
\end{defn}

As a first application of the function extensionality axiom we generalize the weak function extensionality axiom to $k$-types.

\begin{thm}\label{thm:trunc_pi}
Assume function extensionality. Then for any type family $B$ over $A$ one has\index{truncated}
\begin{equation*}
\Big(\prd{x:A}\istrunc{k}(B(x))\Big)\to \istrunc{k}\Big(\prd{x:A}B(x)\Big).
\end{equation*}
\end{thm}

\begin{proof}
The theorem is proven by induction on $k\geq -2$. The base case is just the weak function extensionality principle, which was shown to follow from function extensionality in \cref{thm:funext_wkfunext}.

For the inductive hypothesis, assume that the $k$-types are closed under dependent function types. Assume that $B$ is a family of $(k+1)$-types. By function extensionality, the type $f=g$ is equivalent to $f\htpy g$ for any two dependent functions $f,g:\prd{x:A}B(x)$. Now observe that $f\htpy g$ is a dependent product of $k$-types, and therefore it is an $k$-type by our inductive hypotheses. Therefore, it follows by \cref{thm:ktype_eqv} that $f=g$ is an $k$-type, and hence that $\prd{x:A}B(x)$ is an $(k+1)$-type.
\end{proof}

\begin{cor}\label{cor:funtype_trunc}
Suppose $B$ is a $k$-type. Then $A\to B$ is also a $k$-type, for any type $A$.
\end{cor}

\subsection{The type theoretic principle of choice}

The \define{type theoretic principle of choice}\index{type theoretic choice|textbf} asserts that \emph{$\Pi$ distributes over $\Sigma$}. More precisely, it asserts that the canonical map
\begin{equation*}
  \mathsf{choice}:\Big(\prd{x:A}\sm{y:B(x)}C(x,y)\Big)\to \Big(\sm{f:\prd{x:A}B(x)}\prd{x:A}C(x,f(x))\Big)
\end{equation*}
given by $\lam{h}(\proj 1(h(x)),\proj 2(h(x)))$, is an equivalence. In order to see this as a principle of choice, one can view the left hand side as the type of functions $h$ that pick for every $x:A$ a term $y:B(x)$ equipped with a term of type $C(x,y)$. The function $\mathsf{choice}$ then constructs a dependent function $f:\prd{x:A}B(x)$ equipped with a term of type $\prd{x:A}C(x,f(x))$. In this section we show that the map $\mathsf{choice}$ is an equivalence, and we use this to characterize the identity of any dependent function type $\prd{x:A}B(x)$ in terms of any characterization of the identity types of the individual types $B(x)$.

\begin{thm}\label{thm:choice}
Consider a family of types $C(x,y)$ indexed by $x:A$ and $y:B(x)$. Then the map
\begin{equation*}
  \mathsf{choice}:\Big(\prd{x:A}\sm{y:B(x)}C(x,y)\Big)\to \Big(\sm{f:\prd{x:A}B(x)}\prd{x:A}C(x,f(x))\Big)
\end{equation*}
given by $\lam{h}(\proj 1(h(x)),\proj 2(h(x)))$ is an equivalence.
\end{thm}

\begin{proof}
  We define the map
  \begin{equation*}
    \mathsf{choice}^{-1}:\Big(\sm{f:\prd{x:A}B(x)}\prd{x:A}C(x,f(x))\Big)\to\Big(\prd{x:A}\sm{y:B(x)}C(x,y)\Big)
  \end{equation*}
  by $\lam{(f,g)}{x}(f(x),g(x))$. Then we have to construct homotopies
  \begin{equation*}
    \mathsf{choice}\circ\mathsf{choice}^{-1}\htpy\idfunc,\qquad\text{and}\qquad
    \mathsf{choice}^{-1}\circ\mathsf{choice}\htpy\idfunc.
  \end{equation*}
  For the first homotopy it suffices to construct an identification
  \begin{equation*}
    \mathsf{choice}(\mathsf{choice}^{-1}(f,g))=(f,g)
  \end{equation*}
  for any $f:\prd{x:A}B(x)$ and any $g:\prd{x:A}C(x,f(x))$. We compute the left-hand side as follows:
  \begin{align*}
    \mathsf{choice}(\mathsf{choice}^{-1}(f,g))
    & \jdeq \mathsf{choice}(\lam{x}(f(x),g(x))) \\
    & \jdeq (\lam{x}f(x),\lam{x}g(x)).
  \end{align*}
  By the $\eta$-rule it follows that $f\jdeq \lam{x}f(x)$ and $g\jdeq\lam{x}g(x)$. Therefore we have the identification
  \begin{equation*}
    \refl{(f,g)}:\mathsf{choice}(\mathsf{choice}^{-1}(f,g))=(f,g).
  \end{equation*}
  This completes the construction of the first homotopy.

  For the second homotopy we have to construct an identification
  \begin{equation*}
    \mathsf{choice}^{-1}(\mathsf{choice}(h))=h
  \end{equation*}
  for any $h:\prd{x:A}\sm{y:B(x)}C(x,y)$. We compute the left-hand side as follows:
  \begin{align*}
    \mathsf{choice}^{-1}(\mathsf{choice}(h))
    & \jdeq \mathsf{choice}^{-1}(\lam{x}\proj 1(h(x)),(\lam{x}\proj 2(h(x)))) \\
    & \jdeq \lam{x}(\proj 1(h(x)),\proj 2(h(x)))
  \end{align*}
  However, it is \emph{not} the case that $(\proj 1(h(x)),\proj 2(h(x)))\jdeq h(x)$ for any $h:\prd{x:A}\sm{y:B(x)}C(x,y)$. Nevertheless, we have the identification
  \begin{equation*}
    \mathsf{eq\usc{}pair}(\refl{},\refl{}):(\proj 1(h(x)),\proj 2(h(x)))= h(x).
  \end{equation*}
  Therefore we obtain the required homotopy by function extensionality:
  \begin{equation*}
    \lam{h}\mathsf{eq\usc{}htpy}(\lam{x}\mathsf{eq\usc{}pair}(\refl{\proj 1(h(x))},\refl{\proj 2(h(x))}):\mathsf{choice}^{-1}\circ\mathsf{choice}\htpy\idfunc.\qedhere
  \end{equation*}
\end{proof}

\begin{cor}
For type $A$ and any type family $C$ over $B$, the map
\begin{equation*}
\Big(\sm{f:A\to B} \prd{x:A}C(f(x))\Big)\to\Big(A\to\sm{y:B}C(x)\Big)
\end{equation*}
given by $\lam{(f,g)}{x}(f(x),g(x))$ is an equivalence.
\end{cor}

\subsection{Universal properties}
The function extensionality principle allows us to prove \emph{universal properties}: characterizations of all maps out of (or into) a given type. Universal properties characterize a type up to equivalence. In the following theorem we prove the universal property of dependent pair types.

\begin{thm}
Let $B$ be a type family over $A$, and let $X$ be a type. Then the map
\begin{equation*}
\mathsf{ev\usc{}pair}:\Big(\Big(\sm{x:A}B(x)\Big)\to X\Big)\to \Big(\prd{x:A}(B(x)\to X)\Big)
\end{equation*}
given by $f\mapsto\lam{a}{b}f(a,b)$ is an equivalence.
\end{thm}

\begin{proof}
The map in the converse direction is simply
\begin{equation*}
\ind{\Sigma} : \Big(\prd{x:A}(B(x)\to X)\Big)\to \Big(\Big(\sm{x:A}B(x)\Big)\to X\Big).
\end{equation*}
By the computation rules for $\Sigma$-types we have
\begin{equation*}
\lam{f}\refl{f}:\mathsf{ev\usc{}pair}\circ\ind{\Sigma}\htpy\idfunc
\end{equation*}

To show that $\ind{\Sigma}\circ\mathsf{ev\usc{}pair}\htpy\idfunc$ we will also apply function extensionality. Thus, it suffices to show that $\ind{\Sigma}(\lam{x}{y}f((x,y)))=f$. We apply function extensionality again, so it suffices to show that
\begin{equation*}
\prd{t:\sm{x:A}B(x)}\ind{\Sigma}\big(\lam{x}{y}f((x,y))\big)(t)=f(t).
\end{equation*}
We obtain this homotopy by another application of $\Sigma$-induction.
\end{proof}

\begin{cor}\label{cor:times_up_out}
Let $A$, $B$, and $X$ be types. Then the map
\begin{equation*}
\mathsf{ev\usc{}pair}: (A\times B \to X)\to (A\to (B\to X))
\end{equation*}
given by $f\mapsto\lam{a}{b}f((a,b))$ is an equivalence.
\end{cor}

The universal property of identity types is sometimes called the \emph{type theoretical Yoneda lemma}: families of maps out of the identity type are uniquely determined by their action on the reflexivity identification.

\begin{thm}\label{thm:yoneda}
Let $B$ be a type family over $A$, and let $a:A$. Then the map
\begin{equation*}
\mathsf{ev\usc{}refl}:\Big(\prd{x:A} (a=x)\to B(x)\Big)\to B(a)
\end{equation*}
given by $\lam{f} f(a,\refl{a})$ is an equivalence.
\end{thm}

\begin{proof}
The inverse $\varphi$ is defined by path induction, taking $b:B(a)$ to the function $f$ satisfying $f(a,\refl{a})\jdeq b$. It is immediate that $\mathsf{ev\usc{}refl}\circ\varphi\htpy \idfunc$.

To see that $\varphi\circ \mathsf{ev\usc{}refl}\htpy\idfunc$, let $f:\prd{x:A}(a=x)\to B(x)$. To show that $\varphi(f(a,\refl{a}))=f$ we use function extensionality (twice), so it suffices to show that
\begin{equation*}
\prd{x:A}{p:a=x} \varphi(f(a,\refl{a}),x,p)=f(x,p).
\end{equation*}
This follows by path induction on $p$, since $\varphi(f(a,\refl{a}),a,\refl{a})\jdeq f(a,\refl{a})$.
\end{proof}

\subsection{Composing with equivalences}

We show in this section that a map $f:A\to B$ is an equivalence if and only if for any type $X$ the precomposition map
\begin{equation*}
\blank\circ f: (B\to X)\to (A\to X)
\end{equation*}
is an equivalence. Moreover, we will show in \cref{ex:equiv_precomp} that the `dependent version' of this statement also holds: a map $f:A\to B$ is an equivalence if and only if for any type family $P$ over $B$, the precomposition map
\begin{equation*}
\blank\circ f: \Big(\prd{y:B}P(y)\Big)\to\Big(\prd{x:A}P(f(x))\Big)
\end{equation*}
is an equivalence.

\begin{thm}\label{ex:equiv_precomp}
For any map $f:A\to B$, the following are equivalent:
\begin{enumerate}
\item $f$ is an equivalence.
\item For any type family $P$ over $B$ the map
\begin{equation*}
\Big(\prd{y:B}P(y)\Big)\to\Big(\prd{x:A}P(f(x))\Big)
\end{equation*}
given by $h\mapsto h\circ f$ is an equivalence.
\item For any type $X$ the map
\begin{equation*}
(B\to X)\to (A\to X)
\end{equation*}
given by $g\mapsto g\circ f$ is an equivalence.
\end{enumerate}
\end{thm}

\begin{proof}
To show that (i) implies (ii), we first recall from \cref{lem:coherently-invertible} that any equivalence is also coherently invertible. Therefore $f$ comes equipped with
\begin{align*}
g & : B \to A\\
G & : f\circ g \htpy \idfunc[B] \\
H & : g\circ f \htpy \idfunc[A] \\
K & : G\cdot f \htpy f\cdot H.
\end{align*}
Then we define the inverse of $\blank\circ f$ to be the map
\begin{equation*}
\varphi:\Big(\prd{x:A}P(f(x))\Big)\to\Big(\prd{y:B}P(y)\Big)
\end{equation*}
given by $h\mapsto \lam{y}\mathsf{tr}_P(G(y),h(g(y)))$.

To see that $\varphi$ is a section of $\blank\circ f$, let $h:\prd{x:A}P(f(x))$. By function extensionality it suffices to construct a homotopy $\varphi(h)\circ f\htpy h$. In other words, we have to show that
\begin{equation*}
\mathsf{tr}_P(G(f(x)),h(g(f(x)))=h(x)
\end{equation*}
for any $x:A$. Now we use the additional homotopy $K$ from our assumption that $f$ is a half-adjoint equivalence. Since we have $K(x):G(f(x))=\ap{f}{H(x)}$ it suffices to show that
\begin{equation*}
\mathsf{tr}_P(\ap{f}{H(x)},hgf(x))=h(x).
\end{equation*}
A simple path-induction argument yields that
\begin{equation*}
\mathsf{tr}_P(\ap{f}{p})\htpy \mathsf{tr}_{P\circ f}(p)
\end{equation*}
for any path $p:x=y$ in $A$, so it suffices to construct an identification
\begin{equation*}
\mathsf{tr}_{P\circ f}(H(x),hgf(x))=h(x).
\end{equation*}
We have such an identification by $\apd{h}{H(x)}$.

To see that $\varphi$ is a retraction of $\blank\circ f$, let $h:\prd{y:B}P(y)$. By function extensionality it suffices to construct a homotopy $\varphi(h\circ f)\htpy h$. In other words, we have to show that
\begin{equation*}
\mathsf{tr}_P(G(y),hfg(y))=h(y)
\end{equation*}
for any $y:B$. We have such an identification by $\apd{h}{G(y)}$. This completes the proof that (i) implies (ii).

Note that (iii) is an immediate consequence of (ii), since we can just choose $P$ to be the constant family $X$.

It remains to show that (iii) implies (i). Suppose that
\begin{equation*}
\blank\circ f:(B\to X)\to (A\to X)
\end{equation*}
is an equivalence for every type $X$. Then its fibers are contractible by \cref{thm:contr_equiv}. In particular, choosing $X\jdeq A$ we see that the fiber
\begin{equation*}
\fib{\blank\circ f}{\idfunc[A]}\jdeq \sm{h:B\to A}h\circ f=\idfunc[A]
\end{equation*}
is contractible. Thus we obtain a function $h:B\to A$ and a homotopy $H:h\circ f\htpy\idfunc[A]$ showing that $h$ is a retraction of $f$. We will show that $h$ is also a section of $f$. To see this, we use that the fiber
\begin{equation*}
\fib{\blank\circ f}{f}\jdeq \sm{i:B\to B} i\circ f=f
\end{equation*}
is contractible (choosing $X\jdeq B$).
Of course we have $(\idfunc[B],\refl{f})$ in this fiber. However we claim that there also is an identification $p:(f\circ h)\circ f=f$, showing that $(f\circ h,p)$ is in this fiber, because
\begin{align*}
(f\circ h)\circ f & \jdeq f\circ (h\circ f) \\
& = f\circ \idfunc[A] \\
& \jdeq f
\end{align*}
Now we conclude by the contractibility of the fiber that $(\idfunc[B],\refl{f})=(f\circ h,p)$. In particular we obtain that $\idfunc[B]=f\circ h$, showing that $h$ is a section of $f$.
\end{proof}

\begin{exercises}
\item Show that the functions
\begin{align*}
\mathsf{htpy\usc{}inv} & : (f \htpy g) \to (g \htpy f) \\
\mathsf{htpy\usc{}concat}(H) & : (g \htpy h) \to (f \htpy h) \\
\mathsf{htpy\usc{}concat}'(K) & : (f \htpy g) \to (f \htpy h)
\end{align*}
are equivalences for every $f,g,h : \prd{x:A}B(x)$. Here, $\mathsf{htpy\usc{}concat}'(K)$ is the function defined by $H\mapsto \ct{H}{K}$.
\item \label{ex:isprop_istrunc}
\begin{subexenum}
\item Show that for any type $A$ the type $\iscontr(A)$ is a proposition. %There's an easy proof using double singleton induction. This is a nice application of weak funext.
\item Show that for any type $A$ and any $k\geq-2$, the type $\istrunc{k}(A)$ is a proposition.
\end{subexenum}
\item \label{lem:postcomp_equiv}
Let $f:X\to Y$ be a map. Show that the following are equivalent:
\begin{enumerate}
\item $f$ is an equivalence.\index{equivalence!post-composition|textit}
\item The map $f\circ\blank : X^A\to Y^A$ is an equivalence for every type $A$.
\end{enumerate}
\item \label{ex:isprop_isequiv}Let $f:A\to B$ be a function.
\begin{subexenum}
\item Show that if $f$ is an equivalence, then the type $\sm{g:B\to A}f\circ g\htpy \idfunc$ of sections of $f$ is contractible.
\item Show that if $f$ is an equivalence, then the type $\sm{h:B\to A}h\circ f\htpy \idfunc$ of retractions of $f$ is contractible.
\item Show that $\isequiv(f)$ is a proposition.
\item Use \cref{ex:prop_equiv,ex:isprop_istrunc} to show that $\isequiv(f)\eqvsym \iscontr(f)$.
\end{subexenum}
Conclude that $\eqv{A}{B}$ is a subtype of $A\to B$, and in particular that the map $\proj 1 : (\eqv{A}{B})\to (A\to B)$ is an embedding.
\item \label{ex:prop_equiv}
\begin{subexenum}
\item \label{ex:equiv-bi-implication}Let $P$ and $Q$ be propositions. Show that
\begin{equation*}
\eqv{(P\leftrightarrow Q)}{(\eqv{P}{Q})}.
\end{equation*}
\item Show that $P$ is a proposition if and only if $P\to P$ is contractible.
\end{subexenum}
\item Show that $\mathsf{path\usc{}split}(f)$ and $\mathsf{half\usc{}adj}(f)$ are propositions for any map $f:A\to B$. Conclude that we have equivalences
  \begin{equation*}
    \isequiv(f) \eqvsym \mathsf{path\usc{}split}(f) \eqvsym \mathsf{half\usc{}adj}(f).
  \end{equation*}
%\item Let $B$ and $C$ be type families over $A$, suppose that $p:\id{a}{a'}$ in $A$, and consider two functions $f:B(a)\to C(a)$ and $g:B(a')\to C(a')$.
%\begin{subexenum}
%\item Show that the square
%\begin{equation*}
%\begin{tikzcd}
%B(a) \arrow[r,"f"] \arrow[d,swap,"\mathsf{tr}_B(p)"] & C(a) \arrow[d,"\mathsf{tr}_C(p)"] \\
%B(a') \arrow[r,swap,"g"] & C(a')
%\end{tikzcd}
%\end{equation*}
%commutes for every homotopy $H:\mathsf{tr}_{B(x)\to C(x)}(p,f)\htpy g$. In other words, construct a function of type
%\begin{equation*}
%\Big(\mathsf{tr}_{B(x)\to C(x)}(p,f)\htpy g\Big)\to \Big(\mathsf{tr}_C(p)\circ f\htpy g\circ \mathsf{tr}_B(p)\Big)
%\end{equation*}
%\item Show that this map is an equivalence.
%\end{subexenum}
\item \label{ex:idfunc_autohtpy}Construct for any type $A$ an equivalence
\begin{equation*}
\eqv{\mathsf{is\usc{}invertible}(\idfunc[A])}{\Big(\idfunc[A]\htpy\idfunc[A]\Big)}.
\end{equation*}
Note: We will use this fact in \cref{ex:is_invertible_id_S1} to show that there
are types for which $\mathsf{is\usc{}invertible}(\idfunc[A])\not\eqvsym\isequiv(\idfunc[A])$.
\item
\begin{subexenum}
\item Show that the type
\begin{equation*}
\prd{t:\emptyt}P(t)
\end{equation*}
is contractible for any $P:\emptyt\to \UU$.
\item Show that for any type $X$ the following are equivalent:
  \begin{enumerate}
  \item the unique map $\emptyt \to X$ is an equivalence.
  \item The type $Y^X$ is contractible for any type $Y$.
  \end{enumerate}
\end{subexenum}
\item Consider two types $A$ and $B$.
\begin{subexenum}
\item Show that the map
\begin{equation*}
  \mathsf{ev\usc{}inl\usc{}inr}: \Big(\prd{t:A+B}P(t)\Big) \to
  \Big(\prd{x:A}P(\inl(x))\Big)\times\Big(\prd{y:B}P(\inr(y))\Big)
\end{equation*}
given by $f\mapsto (f\circ\inl,f\circ\inr)$ is an equivalence.
\item Show that the following are equivalent for any type $X$ equipped with maps $i:A\to X$ and $j:B\to X$:
  \begin{enumerate}
  \item The map $\mathsf{ind\usc{}coprod}(i,j) :A+B\to X$ is an equivalence.
  \item For any type $Y$, the map
    \begin{equation*}
      \lam{f}(f\circ i,f\circ j):(X\to Y)\to (A\to Y)\times (B \to Y)
    \end{equation*}
    is an equivalence.
  \end{enumerate}
\end{subexenum}
\item
\begin{subexenum}
\item Show that the map
\begin{equation*}
\Big(\prd{t:\unit}P(t)\Big)\to P(\ttt)
\end{equation*}
given by $\lam{f}f(\ttt)$ is an equivalence.
\item Consider a type $X$ equipped with a point $x:X$. Show that the following are equivalent:
\begin{enumerate}
\item The map $\mathsf{ind\usc{}unit}(x):\unit\to X$ is an equivalence (i.e., $X$ is contractible).
\item For any type $Y$ the map
\begin{equation*}
\lam{f}f(x) : (X\to Y)\to Y
\end{equation*}
is an equivalence.
\end{enumerate}
\end{subexenum}
\item \label{ex:sec_retr}Consider a commuting triangle
\begin{equation*}
\begin{tikzcd}[column sep=tiny]
A \arrow[rr,"h"] \arrow[dr,swap,"f"] & & B \arrow[dl,"g"] \\
& X
\end{tikzcd}
\end{equation*}
with $H:f\htpy g\circ h$.
\begin{subexenum}
\item Show that if $h$ has a section, then $\mathsf{sec}(g)$ is a retract of $\mathsf{sec}(f)$.
\item Show that if $g$ has a retraction, then $\mathsf{retr}(h)$ is a retract of $\mathsf{sec}(f)$.
\end{subexenum}
\item \label{ex:equiv_pi}Let $e_i:\eqv{A_i}{B_i}$ be an equivalence for every $i:I$. Show that the map
\begin{equation*}
\lam{f}{i}e_i\circ f:\Big(\prd{i:I}A_i\Big)\to\Big(\prd{i:I}B_i\Big)
\end{equation*}
is an equivalence.
\item \label{ex:triangle_fib}Consider a diagram of the form
\begin{equation*}
\begin{tikzcd}[column sep=tiny]
A \arrow[dr,swap,"f"] & & B \arrow[dl,"g"] \\
& X
\end{tikzcd}
\end{equation*}
\begin{subexenum}
\item Show that the type $\sm{h:A\to B} f\htpy g\circ h$ is equivalent to the type of families of maps
\begin{equation*}
\prd{x:X}\fib{f}{x}\to\fib{g}{x}.
\end{equation*}
Note: In \cref{thm:pb_fibequiv_complete} we will characterize the type of families of equivalences $\prd{x:X}\fib{f}{x}\simeq\fib{g}{x}$.
\item Show that the type $\sm{h:\eqv{A}{B}} f\htpy g\circ h$ is equivalent to the type of families of equivalences
\begin{equation*}
\prd{x:X}\fib{f}{x}\eqvsym\fib{g}{x}.
\end{equation*}
\end{subexenum}
\item \label{ex:sq_fib}Consider a diagram of the form
\begin{equation*}
\begin{tikzcd}
A \arrow[d,swap,"f"] & B \arrow[d,"g"] \\
X \arrow[r,swap,"h"] & Y.
\end{tikzcd}
\end{equation*}
Show that the type $\sm{i:A\to B}h\circ f\htpy g\circ i$ is equivalent to the type of families of maps
\begin{equation*}
\prd{x:X}\fib{f}{x}\to\fib{g}{h(x)}.
\end{equation*}
%\item Show that the type $\sm{i:\eqv{A}{B}}h\circ f\htpy g\circ i$ is equivalent to the type of families of equivalences
%\begin{equation*}
%\prd{x:X}\fib{f}{x}\eqvsym\fib{g}{h(x)}.
%\end{equation*}
\item \label{ex:iso_equiv}Let $A$ and $B$ be sets. Show that type type $\eqv{A}{B}$ of equivalences from $A$ to $B$ is equivalent to the type $A\cong B$ of \define{isomorphisms} from $A$ to $B$, i.e., the type of quadruples $(f,g,H,K)$ consisting of
\begin{align*}
f & : A\to B \\
g & : B\to A \\
H & : f\circ g = \idfunc[B] \\
K & : g\circ f = \idfunc[A].
\end{align*}
\item \label{ex:pi_sec}Let $B$ be a type family over $A$, and consider the maps
  \begin{align*}
    \proj 1 & : \sm{x:A} B(x)\to A \\
    \proj1 \circ \blank & : \Big(\sm{x:A} B(x)\Big)^A \to A^A.
  \end{align*}
  Construct equivalences
  \begin{equation*}
    \Big(\prd{x:A}B(x)\Big) \eqvsym \mathsf{sec}(\proj 1) \eqvsym \fib{\proj 1 \circ\blank}{\idfunc[A]}.
  \end{equation*}
\item Suppose that $A:I\to \UU$ is a type family over a set $I$ with decidable equality. Show that
  \begin{equation*}
    \Big(\prd{i:I}\iscontr(A_i)\Big)\leftrightarrow \iscontr\Big(\prd{i:I}A_i\Big).
  \end{equation*}
\item Construct equivalences
  \begin{align*}
    \mathsf{Fin}(n^m) & \simeq (\mathsf{Fin}(m)\to\mathsf{Fin}(n)) \\
    \mathsf{Fin}(n!) & \simeq (\mathsf{Fin}(n)\simeq\mathsf{Fin}(n)).
  \end{align*}
\end{exercises}


% Copyright 2018 Markus J. Pflaum, licensed under GNU FDL v1.3
% main author:
%   Markus J. Pflaum
%
\section{Unbounded linear operators}
\label{sec:unbounded-linear-operators}
%
\para
In this section let $\banachV,\banachW$ always denote Banach spaces over the field
$\fldK =\R$ or $\fldK=\C$. The symbols $\hilbertH$, $\hilbertH_1$, ... will always stand for Hilbert spaces over $\fldK$.

\begin{definition}
  By an \emph{unbounded $\fldK$-linear operator} or shortly by an
  \emph{unbounded operator} from $\banachV$ to $\banachW$ we understand a linear map
  $A: \Dom (A) \to \banachW$ defined on a $\fldK$-linear subspace $\Dom (A)\subset \banachV$.
  As usual, $\Dom (A)$ is called the \emph{domain} of the operator $A$.
  The space of unbounded $\fldK$-linear operators from $V$ to $W$ will be
  denoted $\linOps_\fldK (V,W)$ or just  $\linOps (V,W)$.
\end{definition}

\begin{remark}
  In this work, the term ``unbounded'' is meant in the sense of
  ``not necessarily bounded''. Sometimes we just say
  \emph{linear operator} or even only \emph{operator} instead of
  ``unbounded linear operator''.
\end{remark}

\para Observe that besides the domain $\Dom (A)$ of an unbounded operator
  $A \in \linOps (\banachV,\banachW)$ the
  \emph{kernel}
  \[\Ker(A)=\big\{ v \in \banachV \bigmid Av = 0 \big\}\subset\banachV \ , \]
  the \emph{image}
  \[\Img(A)=\big\{ w \in \banachW \bigmid \exists v\in \Dom (A): w = Av \big\}
  \subset \banachW \ , \]
  and the \emph{graph}
  \[\Graph(A)=\big\{ (v,w) \in \Dom (A) \times \banachW \bigmid
    w = Av \big\} \subset \banachV \times \banachW \]
  of $A$  are all linear subspaces. We will frequently make use of this.

\begin{definition}
  An unbounded operator $A\in \linOps (\banachV,\banachW)$ is called
  \emph{densely defined} if $\Dom (A)$ is dense in $\banachV$,
  and \emph{closed} if the graph $\Gr (A)$
  is closed in $\banachV \times \banachW$.
  The operator $A \in \linOps (V,W)$ is called \emph{closable} if the closure
  $\closure{\Gr(A)}$ is the graph of an unbounded operator
  from $\banachV$ to $\banachW$.

  An operator $A \in \linOps (V,W)$ is called an \emph{extension} of
  $B \in \linOps (V,W)$ if $\Gr (B) \subset \Gr (A)$. One writes in this
  situation $B \subset A$.
\end{definition}


\documentclass{article}
\usepackage{fullpage}
\usepackage{parskip}
\usepackage{booktabs}
\usepackage{amsmath}
\pagenumbering{gobble}

\begin{document}

\section{Select your strategies}

$$A=
\begin{pmatrix}
2 & -2\\
-1 & 1
\end{pmatrix}
\qquad
B=
\begin{pmatrix}
-2 & 2\\
1 & -1
\end{pmatrix}
$$

\begin{enumerate}
\item Choose your strategies (as the column player) against the mixed strategy.
\item Wait for me to generate random strategies according to the random distribution.
\end{enumerate}
\vspace{1cm}

\begin{center}
\begin{tabular}{c|c|c|c|c|c|c}
\toprule
& \multicolumn{2}{c|}{$\sigma_1 = (.2,.8)$} & \multicolumn{2}{|c|}{$\sigma_1 = (.9,.1)$} & \multicolumn{2}{|c}{$\sigma_1=(1/3,2/3)$}\\
Round&$s_2$&$\sum u_2$&$s_2$&$\sum u_2$&$s_2$&$\sum u_2$\\
\midrule
&&&&&&\\
1&&&&&&\\
&&&&&&\\
&&&&&&\\
2&&&&&&\\
&&&&&&\\
&&&&&&\\
3&&&&&&\\
&&&&&&\\
&&&&&&\\
4&&&&&&\\
&&&&&&\\
&&&&&&\\
5&&&&&&\\
&&&&&&\\
&&&&&&\\
6&&&&&&\\
&&&&&&\\
\bottomrule
\end{tabular}
\end{center}

\end{document}


\chapter{Arithmetic}
\label{chap:Arithmetic}

In this chapter, we will learn how to perform basic
arithmetic with libzahl: addition, subtraction,
multiplication, division, modulus, exponentiation,
and sign manipulation. \secref{sec:Division} is of
special importance.

\vspace{1cm}
\minitoc

\newpage
\section{Addition}
\label{sec:Addition}

To calculate the sum of two terms, we perform
addition using {\tt zadd}.

\vspace{1em}
$r \gets a + b$
\vspace{1em}

\noindent
is written as

\begin{alltt}
   zadd(r, a, b);
\end{alltt}

libzahl also provides {\tt zadd\_unsigned} which
has slightly lower overhead. The calculates the
sum of the absolute values of two integers.

\vspace{1em}
$r \gets \lvert a \rvert + \lvert b \rvert$
\vspace{1em}

\noindent
is written as

\begin{alltt}
   zadd_unsigned(r, a, b);
\end{alltt}

\noindent
{\tt zadd\_unsigned} has lower overhead than
{\tt zadd} because it does not need to inspect
or change the sign of the input, the low-level
function that performs the addition inherently
calculates the sum of the absolute values of
the input.

In libzahl, addition is implemented using a
technique called ripple-carry. It is derived
from that observation that

\vspace{1em}
$f : \textbf{Z}_n, \textbf{Z}_n \rightarrow \textbf{Z}_n$
\\ \indent
$f : a, b \mapsto a + b + 1$
\vspace{1em}

\noindent
only wraps at most once, that is, the
carry cannot exceed 1. CPU:s provide an
instruction specifically for performing
addition with ripple-carry over multiple words,
adds twos numbers plus the carry from the
last addition. libzahl uses assembly to
implement this efficiently. If, however, an
assembly implementation is not available for
the on which machine it is running, libzahl
implements ripple-carry less efficiently
using compiler extensions that check for
overflow. In the event that neither an
assembly implementation is available nor
the compiler is known to support this
extension, it is implemented using inefficient
pure C code. This last resort manually
predicts whether an addition will overflow;
this could be made more efficient, by never
using the highest bit in each character,
except to detect overflow. This optimisation
is however not implemented because it is
not deemed important enough and would
be detrimental to libzahl's simplicity.

{\tt zadd} and {\tt zadd\_unsigned} support
in-place operation:

\begin{alltt}
   zadd(a, a, b);
   zadd(b, a, b);           \textcolor{c}{/* \textrm{should be avoided} */}
   zadd_unsigned(a, a, b);
   zadd_unsigned(b, a, b);  \textcolor{c}{/* \textrm{should be avoided} */}
\end{alltt}

\noindent
Use this whenever possible, it will improve
your performance, as it will involve less
CPU instructions for each character addition
and it may be possible to eliminate some
character additions.

\newpage
\section{Subtraction}
\label{sec:Subtraction}

TODO % zsub zsub_unsigned

\newpage
\section{Multiplication}
\label{sec:Multiplication}

TODO % zmul zmodmul

\newpage
\section{Division}
\label{sec:Division}

To calculate the quotient or modulus of two integers,
use either of

\begin{alltt}
   void zdiv(z_t quotient, z_t dividend, z_t divisor);
   void zmod(z_t remainder, z_t dividend, z_t divisor);
   void zdivmod(z_t quotient, z_t remainder,
                z_t dividend, z_t divisor);
\end{alltt}

\noindent
These function \emph{do not} allow {\tt NULL}
for the output parameters: {\tt quotient} and
{\tt remainder}. The quotient and remainder are
calculated simultaneously and indivisibly, hence
{\tt zdivmod} is provided to calculated both; if
you are only interested in the quotient or only
interested in the remainder, use {\tt zdiv} or
{\tt zmod}, respectively.

These functions calculate a truncated quotient.
That is, the result is rounded towards zero. This
means for example that if the quotient is in
$(-1,~1)$, {\tt quotient} gets 0. That is, this % TODO try to clarify
would not be the case for one of the sides of zero.
For example, if the quotient would have been
floored, negative quotients would have been rounded
away from zero. libzahl only provides truncated
division.

The remainder is defined such that $n = qd + r$ after
calling {\tt zdivmod(q, r, n, d)}. There is no
difference in the remainer between {\tt zdivmod}
and {\tt zmod}. The sign of {\tt d} has no affect
on {\tt r}, {\tt r} will always, unless it is zero,
have the same sign as {\tt n}.

There are of course other ways to define integer
division (that is, \textbf{Z} being the codomain)
than as truncated division. For example integer
divison in Python is floored — yes, you did just
read `integer divison in Python is floored,' and
you are correct, that is not the case in for
example C. Users that want another definition
for division than truncated division are required
to implement that themselves. We will however
lend you a hand.

\begin{alltt}
   #define isneg(x) (zsignum(x) < 0)
   static z_t one;
   \textcolor{c}{__attribute__((constructor)) static}
   void init(void) \{ zinit(one), zseti(one, 1); \}

   static int
   cmpmag_2a_b(z_t a, z_b b)
   \{
       int r;
       zadd(a, a, a), r = zcmpmag(a, b), zrsh(a, a, 1);
       return r;
   \}
\end{alltt}

% Floored division
\begin{alltt}
   void \textcolor{c}{/* \textrm{All arguments must be unique.} */}
   divmod_floor(z_t q, z_t r, z_t n, z_t d)
   \{
       zdivmod(q, r, n, d);
       if (!zzero(r) && isneg(n) != isneg(d))
           zsub(q, q, one), zadd(r, r, d);
   \}
\end{alltt}

% Ceiled division
\begin{alltt}
   void \textcolor{c}{/* \textrm{All arguments must be unique.} */}
   divmod_ceiling(z_t q, z_t r, z_t n, z_t d)
   \{
       zdivmod(q, r, n, d);
       if (!zzero(r) && isneg(n) == isneg(d))
           zadd(q, q, one), zsub(r, r, d);
   \}
\end{alltt}

% Division with round half aways from zero
% This rounding method is also called:
%    round half toward infinity
%    commercial rounding
\begin{alltt}
   /* \textrm{This is how we normally round numbers.} */
   void \textcolor{c}{/* \textrm{All arguments must be unique.} */}
   divmod_half_from_zero(z_t q, z_t r, z_t n, z_t d)
   \{
       zdivmod(q, r, n, d);
       if (!zzero(r) && cmpmag_2a_b(r, d) >= 0) \{
           if (isneg(n) == isneg(d))
               zadd(q, q, one), zsub(r, r, d);
           else
               zsub(q, q, one), zadd(r, r, d);
       \}
   \}
\end{alltt}

\noindent
Now to the weird ones that will more often than
not award you a face-slap. % Had positive punishment
% been legal or even mildly pedagogical. But I would
% not put it past Coca-Cola.

% Division with round half toward zero
% This rounding method is also called:
%     round half away from infinity
\begin{alltt}
   void \textcolor{c}{/* \textrm{All arguments must be unique.} */}
   divmod_half_to_zero(z_t q, z_t r, z_t n, z_t d)
   \{
       zdivmod(q, r, n, d);
       if (!zzero(r) && cmpmag_2a_b(r, d) > 0) \{
           if (isneg(n) == isneg(d))
               zadd(q, q, one), zsub(r, r, d);
           else
               zsub(q, q, one), zadd(r, r, d);
       \}
   \}
\end{alltt}

% Division with round half up
% This rounding method is also called:
%     round half towards positive infinity
\begin{alltt}
   void \textcolor{c}{/* \textrm{All arguments must be unique.} */}
   divmod_half_up(z_t q, z_t r, z_t n, z_t d)
   \{
       int cmp;
       zdivmod(q, r, n, d);
       if (!zzero(r) && (cmp = cmpmag_2a_b(r, d)) >= 0) \{
           if (isneg(n) == isneg(d))
               zadd(q, q, one), zsub(r, r, d);
           else if (cmp)
               zsub(q, q, one), zadd(r, r, d);
       \}
   \}
\end{alltt}

% Division with round half down
% This rounding method is also called:
%     round half towards negative infinity
\begin{alltt}
   void \textcolor{c}{/* \textrm{All arguments must be unique.} */}
   divmod_half_down(z_t q, z_t r, z_t n, z_t d)
   \{
       int cmp;
       zdivmod(q, r, n, d);
       if (!zzero(r) && (cmp = cmpmag_2a_b(r, d)) >= 0) \{
           if (isneg(n) != isneg(d))
               zsub(q, q, one), zadd(r, r, d);
           else if (cmp)
               zadd(q, q, one), zsub(r, r, d);
       \}
   \}
\end{alltt}

% Division with round half to even
% This rounding method is also called:
%     unbiased rounding        (really stupid name)
%     convergent rounding      (also quite stupid name)
%     statistician's rounding
%     Dutch rounding
%     Gaussian rounding
%     odd–even rounding
%     bankers' rounding
% It is the default rounding method used in IEEE 754.
\begin{alltt}
   void \textcolor{c}{/* \textrm{All arguments must be unique.} */}
   divmod_half_to_even(z_t q, z_t r, z_t n, z_t d)
   \{
       int cmp;
       zdivmod(q, r, n, d);
       if (!zzero(r) && (cmp = cmpmag_2a_b(r, d)) >= 0) \{
           if (cmp || zodd(q)) \{
               if (isneg(n) != isneg(d))
                   zsub(q, q, one), zadd(r, r, d);
               else
                   zadd(q, q, one), zsub(r, r, d);
           \}
       \}
   \}
\end{alltt}

% Division with round half to odd
\newpage
\begin{alltt}
   void \textcolor{c}{/* \textrm{All arguments must be unique.} */}
   divmod_half_to_odd(z_t q, z_t r, z_t n, z_t d)
   \{
       int cmp;
       zdivmod(q, r, n, d);
       if (!zzero(r) && (cmp = cmpmag_2a_b(r, d)) >= 0) \{
           if (cmp || zeven(q)) \{
               if (isneg(n) != isneg(d))
                   zsub(q, q, one), zadd(r, r, d);
               else
                   zadd(q, q, one), zsub(r, r, d);
           \}
       \}
   \}
\end{alltt}

% Other standard methods include stochastic rounding
% and round half alternatingly, and what is is
% New Zealand called “Swedish rounding”, which is
% no longer used in Sweden, and is just normal round
% half aways from zero but with 0.5 rather than
% 1 as the integral unit, and is just a special case
% of a more general rounding method.

Currently, libzahl uses an almost trivial division
algorithm. It operates on positive numbers. It begins
by left-shifting the divisor as much as possible with
letting it exceed the dividend. Then, it subtracts
the shifted divisor from the dividend and add 1,
left-shifted as much as the divisor, to the quotient.
The quotient begins at 0. It then right-shifts
the shifted divisor as little as possible until
it no longer exceeds the diminished dividend and
marks the shift in the quotient. This process is
repeated until the unshifted divisor is greater
than the diminished dividend. The final diminished
dividend is the remainder.

\newpage
\section{Exponentiation}
\label{sec:Exponentiation}

Exponentiation refers to raising a number to
a power. libzahl provides two functions for
regular exponentiation, and two functions for
modular exponentiation. libzahl also provides
a function for raising a number to the second
power, see \secref{sec:Multiplication} for
more details on this. The functions for regular
exponentiation are

\begin{alltt}
   void zpow(z_t power, z_t base, z_t exponent);
   void zpowu(z_t, z_t, unsigned long long int);
\end{alltt}

\noindent
They are identical, except {\tt zpowu} expects
an intrinsic type as the exponent. Both functions
calculate

\vspace{1em}
$power \gets base^{exponent}$
\vspace{1em}

\noindent
The functions for modular exponentiation are
\begin{alltt}
   void zmodpow(z_t, z_t, z_t, z_t modulator);
   void zmodpowu(z_t, z_t, unsigned long long int, z_t);
\end{alltt}

\noindent
They are identical, except {\tt zmodpowu} expects
and intrinsic type as the exponent. Both functions
calculate

\vspace{1em}
$power \gets base^{exponent} \mod modulator$
\vspace{1em}

The sign of {\tt modulator} does not affect the
result, {\tt power} will be negative if and only
if {\tt base} is negative and {\tt exponent} is
odd, that is, under the same circumstances as for
{\tt zpow} and {\tt zpowu}.

These four functions are implemented using
exponentiation by squaring. {\tt zmodpow} and
{\tt zmodpowu} are optimised, they modulate
results for multiplication and squaring at
every multiplication and squaring, rather than
modulating the result at the end. Exponentiation
by modulation is a very simple algorithm which
can be expressed as a simple formula

\vspace{-1em}
\[ \hspace*{-0.4cm}
    a^b =
    \prod_{k \in \textbf{Z}_{+} ~:~ \left \lfloor \frac{b}{2^k} \hspace*{-1ex} \mod 2 \right \rfloor = 1}
    a^{2^k}
\]

\noindent
This is a natural extension to the
observations\footnote{The first of course being
that any non-negative number can be expressed
with the binary positional system. The latter
should be fairly self-explanatory.}

\vspace{-1em}
\[ \hspace*{-0.4cm}
    \forall b \in \textbf{Z}_{+} \exists B \subset \textbf{Z}_{+} : b = \sum_{i \in B} 2^i
    ~~~~ \textrm{and} ~~~~
    a^{\sum x} = \prod a^x.
\]

\noindent
The algorithm can be expressed in psuedocode as

\vspace{1em}
\hspace{-2.8ex}
\begin{minipage}{\linewidth}
\begin{algorithmic}
    \STATE $r, f \gets 1, a$
    \WHILE{$b \neq 0$}
      \STATE $r \gets r \cdot f$ {\bf unless} $2 \vert b$
      \STATE $f \gets f^2$ \textcolor{c}{\{$f \gets f \cdot f$\}}
      \STATE $b \gets \lfloor b / 2 \rfloor$
    \ENDWHILE
    \RETURN $r$
\end{algorithmic}
\end{minipage}
\vspace{1em}

\noindent
Modular exponentiation ($a^b \mod m$) by squaring can be
expressed as

\vspace{1em}
\hspace{-2.8ex}
\begin{minipage}{\linewidth}
\begin{algorithmic}
    \STATE $r, f \gets 1, a$
    \WHILE{$b \neq 0$}
      \STATE $r \gets r \cdot f \hspace*{-1ex}~ \mod m$ \textbf{unless} $2 \vert b$
      \STATE $f \gets f^2 \hspace*{-1ex}~ \mod m$
      \STATE $b \gets \lfloor b / 2 \rfloor$
    \ENDWHILE
    \RETURN $r$
\end{algorithmic}
\end{minipage}
\vspace{1em}

{\tt zmodpow} does \emph{not} calculate the
modular inverse if the exponent is negative,
rather, you should expect the result to be
1 and 0 depending of whether the base is 1
or not 1.

\newpage
\section{Sign manipulation}
\label{sec:Sign manipulation}

libzahl provides two functions for manipulating
the sign of integers:

\begin{alltt}
   void zabs(z_t r, z_t a);
   void zneg(z_t r, z_t a);
\end{alltt}

{\tt zabs} stores the absolute value of {\tt a}
in {\tt r}, that is, it creates a copy of
{\tt a} to {\tt r}, unless {\tt a} and {\tt r}
are the same reference, and then removes its sign;
if the value is negative, it becomes positive.

\vspace{1em}
\(
    r \gets \lvert a \rvert =
    \left \lbrace \begin{array}{rl}
        -a & \quad \textrm{if}~a \le 0 \\
        +a & \quad \textrm{if}~a \ge 0 \\
    \end{array} \right .
\)
\vspace{1em}

{\tt zneg} stores the negated of {\tt a}
in {\tt r}, that is, it creates a copy of
{\tt a} to {\tt r}, unless {\tt a} and {\tt r}
are the same reference, and then flips sign;
if the value is negative, it becomes positive,
if the value is positive, it becomes negative.

\vspace{1em}
\(
    r \gets -a
\)
\vspace{1em}

Note that there is no function for

\vspace{1em}
\(
    r \gets -\lvert a \rvert =
    \left \lbrace \begin{array}{rl}
         a & \quad \textrm{if}~a \le 0 \\
        -a & \quad \textrm{if}~a \ge 0 \\
    \end{array} \right .
\)
\vspace{1em}

\noindent
calling {\tt zabs} followed by {\tt zneg}
should be sufficient for most users:

\begin{alltt}
   #define my_negabs(r, a)  (zabs(r, a), zneg(r, r))
\end{alltt}


\documentclass[../../main.tex]{subfiles}

\begin{document}

\subsection{Motivation}

It is considered a problem of constructing a phase trajectory of a video file using tensor-based singular spectrum analysis method. Usually, phase trajectory of a time series is constructed using SSA method that is applied to a matrix with two indices \cite{golyandina, usmanova}. In this work it is proposed to apply tensor-based SSA method that constructs a trajectory matrix that has 3 indices, then apply HOSVD method for extracting principal components.

\subsection{Problem statement}

Given a sequence of images that composes a gray-scale video. Let us consider this as a time series system. Each time series is a sequence of a particular pixel brightness:

$$F^{(k)} = (f_j^{(k)})_{j=0}^{N-1}, \quad k = 1, \dots, hw,$$

\noindent
where $h$ is the video height, $w$ is the video width, $hw$ is a number of signals with length $N$.

The purpose is to construct a phase trajectory of the time series system and make a forecast $\hat{\mathbf{X}}^\prime$ using tensor-based SSA method and HOSVD.

\subsection{Problem solution}

It is proposed to solve a problem with tensor-based singular spectrum analysis and make a forecast using HOSVD.

\textbf{1st step: Embedding}

Let $L$ be a window length, $1 < L < N$. The embedding procedure forms $K = N-L+1$ lagged vectors for every time series:

$$X_l^{(k)} = (f_{l-1}^{(k)}, \dots, f_{l+L-2}^{(k)})^\top.$$

The trajectory matrix of the time series system $F^{(1)}, \dots, F^{(hw)}$ is a tensor that has a form

$$\hat{\mathbf{X}} = (\mathbf{X}^{(1)}, \dots, \mathbf{X}^{(hw)}),$$

\noindent
where $\mathbf{X}^{(k)} = (X_l^{(k)})_{l=0}^{K}$.

\textbf{2nd step: HOSVD}

Truncated HOSVD is performed:

$$\hat{\mathbf{X}} = \mathbf{S} \times_1 U_1 \times_2 U_2 \times_3 U_3,$$

\noindent
where $\mathbf{S}$ is a core tensor, $U_1, U_2, U_3$ are matrices with unitary columns containing a basis of the left singular vectors corresponding to the nonzero singular values of the standard factor-$k$ flattening $X_{(k)}$ of $X$ for $k = 1, 2, 3$.

The HOSVD of $\hat{\mathbf{X}}$ can be represent as

$$\hat{\mathbf{X}} = \hat{\mathbf{X}}_1 + \dots + \hat{\mathbf{X}}_d,$$

\noindent
where $\hat{\mathbf{X}}_i$ has rank equal to 1.

\textbf{3rd step: Grouping}

The grouping procedure partitions the
set of indices $\{1, \dots, d\}$ into $m$ disjoint subsets $I_1, \dots, I_m$. Let $I = {i_1, \dots, i_p}$. Then the resultant matrix $\hat{\mathbf{X}}$ corresponding to the group $I$ is defined as $\hat{\mathbf{X}}_I = \hat{\mathbf{X}}_{i_1} + \dots + \hat{\mathbf{X}}_{i_p}$. Thus, we have the grouped decomposition:

$$\hat{\mathbf{X}} = \hat{\mathbf{X}}_{I_1} + \dots + \hat{\mathbf{X}}_{I_m}.$$

\textbf{4th step: Diagonal averaging}

The last step is in a sense opposite to the first step and transforms each matrix of the grouped decomposition into a system of new (reconstructed) series of length $N$ by hankelization-like procedure.

\subsection{Code analysis}

Code for HOSVD decomposition was taken from GitHub repository\footnote{https://github.com/hottbox/hottbox}. Code of the computational experiment can be found in the repository\footnote{https://github.com/gorpinich-m/Math-methods-of-forecasting}.

\subsection{Experiment}

\begin{figure}[h!]
\centering
\includegraphics[width=0.8\textwidth]{sections/gorpinich/trajectories_base.pdf}
\caption{Some description}
\label{fig:1}
\end{figure}

Fig. \ref{fig:1} plots phase trajectories of 4 pixels of the basic video.

\begin{figure}[h!]
\centering
\includegraphics[width=0.8\textwidth]{sections/gorpinich/mario_trajectory.pdf}
\caption{Some description}
\label{fig:2}
\end{figure}

Fig. \ref{fig:1} plots phase trajectories of 1000 pixels of the video.

\begin{figure}[h!]
\centering
\includegraphics[width=0.6\textwidth]{sections/gorpinich/ssa_base.pdf}
\caption{Some description}
\label{fig:3}
\end{figure}

Fig. \ref{fig:3} plots SSA decomposition of the basic video. We can see that the first component is a trend and other 2 components depict periodicity ans seasonality.

\begin{figure}[h!]
\centering
\includegraphics[width=0.6\textwidth]{sections/gorpinich/ssa_mario.pdf}
\caption{Some description}
\label{fig:4}
\end{figure}

Fig. \ref{fig:4} plots SSA decomposition of the more complex video.

\end{document}


\section{Introduction}
The bread-first search is an algorithm visiting a graph in amplitude. It starts from a node,
often called the root or source node, and continues visiting all its descendants level
by level, whereas the $i$-th level will contain all the nodes at a distance
$i$ from the root.
For each node visited the algorithm checks its label to count the occurrences of the target label.
The assumption underlying all the work is that the input to the algorithm is a direct and
acyclic graph. In addition, for the sake of clarity, the notation used is summarized below:
\subsection{Notation}
Let $\mathcal{G} = (V, E)$, $|V| = n$ is the number of node and $|E| = m$ is the number of edges.
For all the node $v \in V$:
\begin{itemize}
    \item $\mathcal{N}(v) = \{u : (v, u) \in E\}$ is the neighborhood of $v$;
    \item $k_{in}(v) = |\{e: e=(u, v) \in E\}|$ is the in-degree of $v$;
    \item $k_{out}(v) = |\mathcal{N}(v)|$ is the out-degree of $v$;
    \item $k(v) = k_{in}(v) + k_{out}(v)$ is the degree of $v$.
    \item $d(u, v)$ is the distance from $u$ to $v$, i.e. the minimum path from $u$ to $v$.
    \item $C(v)$ is the clustering coefficient, i.e.e $\frac{2 \cdot L_i}{k_i\cdot(k_i - 1)}$, where $L_i$ represents the number of edges between the $k_i$ neighbors of node i.
\end{itemize}
Using the node-focus notation above,
 it is possible to define general properties for the graph:
\begin{itemize}
    \item $\bar{k}(G)$ is the average degree;
    \item $\bar{d}(G)$ is the average distance;
    \item $\bar{h}(G)$ is the diameter, hence the maximum distance among any two nodes.
\end{itemize}
In addition, we can define
the graph inducted by a node $v$ as the subgraph $G'=(V', E')$ containing all the nodes reachable from v.
\subsection{Preliminary analysis}
\subsubsection{Data structure}
Before entering in the algorithmic details let's first introduce the data structure used.
There are many ways to represent a graph; among these the main ones are the adjacency list and the adjacency
matrix. The choices among them is mainly a matter of the usage of the adjacency information and the
expected nature of the graph. As for every node $v$ of the graph, induced by the root, it will be necessary
to go through each node $u \in \mathcal{N}(v)$, the adjacency list is way more efficient since for each
node $v$ the listing of $\mathcal{N}(v)$ takes a time proportional to $k_{out}(v)$, which is thus optimal.
Moreover, if the expected input of the algorithm are "real" graphs, since they are very sparse, the representation as a adjacency list is way
more efficient in terms of space complexity.
\\
In particular, the solution implements a graph $G$ as a vector of nodes.
 The node is a pair, the first component is the label of the node, while the second
 component is the adjacency list containing the indices of the nodes in the graph.
In addition, to mark each node as visited, a vector of boolean is used (having a space complexity of $O(log_2n)$). This vector is called in the report
\textit{vector of visits}.

 \subsubsection{Sequential version}
\label{sub:seq-version}
The sequential version is a straightforward implementation of the problem
description. It uses two vectors $F_i$ and $F_{i+1}$: the former is the frontier
while the latter is used to add new nodes and therefore represents the frontier
to be used in the next iteration. At the beginning, the algorithm initializes the vector of visits,
 the frontier with the neighborhood of the source node and marks each child as visited. Then it marks the source node
as visited and updates occurrences if needed (i.e. if the root has the searched label). After this first phase,
 the algorithm starts the first loop which iterates on each level checking that $F_i$ is not empty.
 Subsequently, for each level, it goes through each node $v \in F_i$, updates occurrences if needed and
 then goes through each node $u \in \mathcal{N}(v)$.
 For each node $u$ in the neighborhood, if the node $u$ is not marked as visited,
 it adds $u$ to $F_{i+1}$. After having exhausted all the nodes of $F_i$, the algorithm
 swaps $F_i$ with $F_{i+1}$ and then clears $F_{i+1}$.


\section{Results and Discussion}
\label{sec:Results_and_Discussion}
This section contains lists of all important results and summarizes the most important things.

\begin{table}[H]
	\centering
	\renewcommand{\arraystretch}{1.3}
	\begin{tabular}{r||c|c|c}
		& \textbf{Measured} ($\mu$m) & \textbf{True Value} ($\mu$m) & \textbf{Deviation} (\%) \\
		\hline\hline
		\textbf{Slit 1} & 39.41 $\pm$ 0.93 & 40 & -1.5 \\
		\textbf{Slit 2} & 101.26 $\pm$ 6.77 & 100 & +1.3 \\ \hline
		\textbf{Anti-Slit 1} & 239.10 $\pm$ 23.34 & 230 & +4.0 \\
		\textbf{Anti-Slit 2} & 123.39 $\pm$ 6.80 & 124 & -0.5 \\ \hline
		\textbf{Circular Aperture 1} & 151.39 $\pm$ 10.24 & 150 & +0.9 \\
		\textbf{Circular Aperture 2} & 101.62 $\pm$ 4.60 & 100 & +1.6 \\ \hline
		\textbf{Cross-Grid 1} & 28.53 $\pm$ 0.57 & 28 & +1.9 \\
		\textbf{Cross-Grid 2} & 50.22 $\pm$ 0.30 & 50 & +0.44 \\ \hline
	\end{tabular}
	\caption{Summary of all Results}
	\label{tab:results}
\end{table}

Table \ref{tab:results} shows that all the calculated mean values are really close to their true values (all values are within < 4 \% deviation). The other important thing is to check, wheter their true value lies between the measured value and its uncertainty. This is shown in the following figure \ref{fig:Graphical_Comparison}:

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.94]{Graphical_Comparison}
	\caption{Graphical Comparison}
	\label{fig:Graphical_Comparison}
\end{figure}

Figure \ref{fig:Graphical_Comparison} shows a graphical comparison between the calculated values (black cross with red uncertainty bar) and their respective true values (blue cross). The display order is the same as in the above table \ref{tab:results}. Although it is difficult to see for the values with a small error bar, \textbf{all their true values lie between their calculated values and their uncertainties}.


\documentclass{beamer}

\usepackage{beamerthemevictor,comment,verbatim,graphicx,rotating}

\input slidemacs
\input{tutmacs}
\input idxmacs
\input logicmacs

\begin{document}

\title{Logic and lambda calculus in \TeX}
\author{Victor Eijkhout}
\date{Notes for CS 594 -- Fall 2004}

\frame{\titlepage}

\section{Introduction}
\subsection{Markup}

\frame[containsverbatim]{
  \frametitle{}
\begin{itemize}
\item Expansion is very powerful
\item Implement logic, numbers, lambda calculus
\end{itemize}
}

\def\Ignore#1{}
\def\Identity#1{#1}
\def\First#1#2{#1}
\def\Second#1#2{#2}

\frame[containsverbatim]{
  \frametitle{auxiliaries}
\begin{inputwithcode}
\def\Ignore#1{}
\def\Identity#1{#1}
\def\First#1#2{#1}
\def\Second#1#2{#2}
\end{inputwithcode}
}

\let\True=\First
\let\False=\Second
\def\And#1#2{#1{#2}\False}
\def\Or#1#2{#1\True{#2}}
\def\Twiddle#1#2#3{#1{#3}{#2}}
\let\Not=\Twiddle

\frame[containsverbatim]{
  \frametitle{Truth}
\begin{inputwithcode}
\let\True=\First
\let\False=\Second
\end{inputwithcode}
and logical operators:
\begin{inputwithcode}
\def\And#1#2{#1{#2}\False}
\def\Or#1#2{#1\True{#2}}
\def\Twiddle#1#2#3{#1{#3}{#2}}
\let\Not=\Twiddle
\end{inputwithcode}
}

\frame[containsverbatim]{
  \frametitle{Truth test}
\begin{quote}
\test{True takes first of TF}{\True}
\test{False takes second of TF}{\False}
\test{Not true is false}{\Not\True}

\test{And truth table TrueTrue}{\And\True\True}
\test{And truth table TrueFalse}{\And\True\False}
\test{And truth table FalseTrue}{\And\False\True}
\test{And truth table FalseFalse}{\And\False\False}

\test{Or truth table TrueTrue}{\Or\True\True}
\test{Or truth table TrueFalse}{\Or\True\False}
\test{Or truth table FalseTrue}{\Or\False\True}
\test{Or truth table FalseFalse}{\Or\False\False}
\end{quote}
}

\sectionframe{Lists}

\frame[containsverbatim]{
  \frametitle{Definition}
We implement a list as an operator with two arguments:
\begin{itemize}
\item If the list is not empty, the first argument is applied to the
  head, and the tail is evaluated;
\item If the list is empty, the second argument is evaluated.
\end{itemize}
In other words
\[ L \, a_1 \, a_2 =
      \left\{\begin{array}{rl}a_2&\mbox{if $L=()$}\\
             a_1(x) \, Y&\mbox{if $L=(x,Y)$}
      \end{array}\right. \]
}

\let\Nil=\Second
% \Cons <head> <tail> <arg1> <arg2>
\def\Cons#1#2#3#4{#3{#1}{#2}}
\def\Error{{ERROR}}
\def\Head#1{#1\First\Error}
\def\Tail#1{#1\Second\Error}

\frame[containsverbatim]{
  \frametitle{Construction}
\begin{inputwithcode}
\let\Nil=\Second
% \Cons <head> <tail> <arg1> <arg2>
\def\Cons#1#2#3#4{#3{#1}{#2}}
\def\Error{{ERROR}}
\def\Head#1{#1\First\Error}
\def\Tail#1{#1\Second\Error}
\end{inputwithcode}
}

\def\Singleton#1{\Cons{#1}\Nil}

\frame[containsverbatim]{
  \frametitle{List examples}
\begin{inputwithcode}
\def\Singleton#1{\Cons{#1}\Nil}
\end{inputwithcode}
\begin{quote}
\test{Head of a singleton}{\Head{\Singleton\True}}
\test{Head of a tail of a 2-elt list}%
     {\Head{\Tail{\Cons\True{\Singleton\False}}}}
\end{quote}
}

\def\Transcribe#1{#1\TranscribeHT\gobbletwo}
\def\TranscribeHT#1#2{1\Transcribe{#2}}

\frame[containsverbatim]{
  \frametitle{Visualization}
\begin{inputwithcode}
\def\gobbletwo#1#2{}
\def\Transcribe#1{#1\TranscribeHT\gobbletwo}
\def\TranscribeHT#1#2{1\Transcribe{#2}}
\end{inputwithcode}
}

\def\ListApply#1#2#3{#3{\ListApplyp{#1}{#2}}{#2}}
\def\ListApplyp#1#2#3#4{#1{#3}{\ListApply{#1}{#2}{#4}}}

\frame[containsverbatim]{
  \frametitle{Functions on lists}
Given function~$f$,
initial argument~$e$, and list~$X$, then
\[ \mathtt{Apply}\, f\, e\, X \Rightarrow
     f\, x_1\,(f\, x_2\, (\ldots (f\, x_n\, e)\ldots)) \]
\begin{inputwithcode}
% #1=function #2=initial arg #3=list
\def\ListApply#1#2#3{#3{\ListApplyp{#1}{#2}}{#2}}
\def\ListApplyp#1#2#3#4{#1{#3}{\ListApply{#1}{#2}{#4}}}
\end{inputwithcode}
}

\def\Cat#1#2{\ListApply\Cons{#2}{#1}}

\frame[containsverbatim]{
  \frametitle{Concatenate}
\begin{inputwithcode}
\def\Cat#1#2{\ListApply\Cons{#2}{#1}}
\end{inputwithcode}
For example:
\begin{quote}
\test{Cat two lists}%
  {\Transcribe{\Cat{\Singleton\Nil}{\Cons\Nil{\Singleton\Nil}}}}
\end{quote}
}

\sectionframe{Numbers}
\subsection{Definition}

\let\Zero\Nil
\def\AddOne#1{\Cons\Nil{#1}}

\frame[containsverbatim]{
  \frametitle{Adding one}
\begin{inputwithcode}
\let\Zero\Nil
\def\AddOne#1{\Cons\Nil{#1}}
\end{inputwithcode}
Examples:
\begin{quote}
\ttest{Transcribe zero}{\Zero}
\ttest{Transcribe one}{\AddOne\Zero}
\ttest{Transcribe three}{\AddOne{\AddOne{\AddOne\Zero}}}
\end{quote}
}

\newtoks\dtoks\newcount\nn
\def\ndef#1#2{\nn=#2 \dtoks={\Zero}\nndef#1}
\def\nndef#1{
  \ifnum\nn=0 \edef\tmp{\def\noexpand#1{\the\dtoks}}\tmp
  \else \edef\tmp{\dtoks={\noexpand\AddOne{\the\dtoks}}}\tmp
        \advance\nn by -1 \nndef#1
  \fi}
\ndef\One1 \ndef\Two2 \ndef\Three3 \ndef\Four4 \ndef\Five5
%\show\Three
\ndef\Seven7\ndef\Six6

\def\Sub#1#2{#1{\SubFrom{#2}}{#2}}
\def\SubFrom#1#2#3{#1{\SubMinOne{#3}}\Error}
\def\SubMinOne#1#2#3{\Sub{#1}{#3}}
\def\SubOne#1{#1\Second\Error}

\frame[containsverbatim]{
  \frametitle{Subtracting one}
\begin{inputwithcode}
\def\SubOne#1{#1\Second\Error}
\end{inputwithcode}
\begin{quote}
\ttest{Predecessor of two}{\SubOne{\AddOne{\AddOne\Zero}}}
\end{quote}
}

\subsectionframe{Arithmetic}

\frame[containsverbatim]{
  \frametitle{Addition}
\begin{inputwithcode}
\let\Add=\Cat
\end{inputwithcode}
\begin{quote}
\ttest{Adding numbers}{\Add{\Three}{\Five}}
\end{quote}
}

\def\GreaterThan#1#2{#2{\GreaterThanp{#1}}\False}
\def\GreaterThanp#1#2#3{#1{\GreaterThanx{#3}}\True}
\def\GreaterThanx#1#2#3{\GreaterThan{#1}{#3}}

\frame[containsverbatim]{
  \frametitle{Comparison}
\begin{inputwithcode}
\def\GreaterThan#1#2{#2{\GreaterThanp{#1}}\False}
\def\GreaterThanp#1#2#3{#1{\GreaterThanx{#3}}\True}
\def\GreaterThanx#1#2#3{\GreaterThan{#1}{#3}}
\end{inputwithcode}
\begin{quote}
\test{Greater (true result)}{\GreaterThan\Two\Five}
\test{Greater (false result)}{\GreaterThan\Three\Two}
\test{Greater (equal case)}{\GreaterThan\Two\Two}
\test{Greater than zero}{\GreaterThan\Two\Zero}
\test{Greater than zero}{\GreaterThan\Zero\Two}
\end{quote}
}

\frame[containsverbatim]{
\begin{quote}
\ttest{Use true result}{\GreaterThan\Two\Five\Three\One}
\ttest{Use false result}{\GreaterThan\Three\Two\Three\One}
\end{quote}
\begin{quote}
\test{$3<(5-1)$}{\GreaterThan\Three{\Sub\One\Five}}
\test{$3<(5-4)$}{\GreaterThan\Three{\Sub\Four\Five}}
\end{quote}
}

\frame[containsverbatim]{
  \frametitle{Integers}
\begin{inputwithcode}
% \StreamOp <operator> <initial value>
\def\StreamOp#1#2{\Cons{#2}{\StreamOp{#1}{#1{#2}}}}
\def\Integers{\StreamOp\AddOne\Zero}
\end{inputwithcode}
\begin{quote}
\ttest{Integers}{\Head{\Tail{\Integers}}}
\ttest{Integers}%
  {\Head{\Tail{\Tail{\Tail{\Tail{\Tail{\Integers}}}}}}}
\end{quote}
}

\end{document}
\frame[containsverbatim]{
  \frametitle{}
}

\frame[containsverbatim]{
  \frametitle{}
}

\frame[containsverbatim]{
  \frametitle{}
}

\end{document}

\frame[containsverbatim]{
  \frametitle{}
\begin{itemize}
\item
\end{itemize}
}


\section{Preliminaries}
\label{sect:ressat-preliminaries}

A random-exist quantified SSAT formula $\Qf$ has the form $\random{} X,\exists Y.\pf(X,Y)$,
where $X$ and $Y$ are two disjoint sets of Boolean variables,
and $\pf(X,Y)$ is a CNF formula.

\subsection{Generalization of SAT/UNSAT minterms}
\label{sect:ressat-generalize}

Given an assignment $\as$ over $X$,
if $\pcf{\pf(X,Y)}{\as}$ is satisfiable (resp. unsatisfiable),
$\as$ is called a SAT (resp. an UNSAT) minterm of $\pf$ over $X$.
The generalization process of a SAT or an UNSAT minterm $\as$ aims at expanding it to a cube $\as^+$,
while maintaining the satisfiability of $\pcf{\pf(X,Y)}{\as^+}$ the same as $\pcf{\pf(X,Y)}{\as}$.
\begin{example}
    \label{ex:ressat-assign}
    Consider formula $\pf(x_1,x_2,y_1,y_2)=x_1 \land (\lnot x_2 \lor y_1 \lor y_2)$.
    The complete assignment $\as = x_1 x_2$ over $X$, i.e., $\as(x_1)=\top, \as(x_2)=\top$,
    is a SAT minterm of $\pf$ over $X$ because $\pcf{\pf}{\as}$ is satisfiable by the assignment $\mu = y_1y_2$.
    On the other hand, the partial assignment $\as^+ = \lnot x_1$, i.e., $\as^+(x_1)=\bot$,
    is an UNSAT cube of $\pf$ as $\pcf{\pf}{\as^+}$ is unsatisfiable.
\end{example}

\subsubsection{Minimum satisfying assignment}
For a CNF formula $\pf(X,Y)$,
let $\as$ be a SAT minterm over $X$ and let $\mu$ be a satisfying complete assignment for the induced formula $\pcf{\pf(X,Y)}{\as}$ over $Y$.
To generalize $\as$ into a cube, one can find a subset of literals from $\as$ and $\mu$ that are able to satisfy all clauses in $\pf$ while the number of literals taken from $\as$ is as few as possible.
If some literals in $\as$ are irrelevant to the satisfiability,
they can be dropped from $\as$, thus expanding $\as$ to a SAT cube $\as^+$.
The generalized cube $\as^+$ is called a \textit{minimum satisfying assignment} if the number of literals taken from $\as$ is minimized.
The process of finding a minimum satisfying assignment is also known as finding a \textit{minimum hitting set}.

\subsubsection{Minimum conflicting assignment}
Given an UNSAT minterm $\as$ of a formula $\pf$,
modern SAT solvers, e.g., \minisat~\cite{Een2003Solver,Een2003Incremental},
are able to compute a conjunction of literals from $\as$ that is responsible for the conflict.
If some literals in $\as$ are irrelevant to the conflict,
they are dropped from $\as$,
thus expanding $\as$ to an UNSAT cube $\as^+$.
If the number of literals in an UNSAT cube $\as^+$ is minimized,
$\as^+$ is called a \textit{minimum conflicting assignment}.
The process of finding a minimum conflicting assignment is also known as finding a \textit{minimum UNSAT core}.


\chapter{Predicates and Connectives}
\label{chapter:predicates}
\marginurl{%
  Connectives and Propositions:\\\noindent
  Introduction to Mathematical Reasoning \#5
}{youtu.be/0unvlq2OTaE}
\section{Propositions and Predicates}
In the previous chapters we used the word ``statement'' without any even
relatively formal definition of what it means. In this chapter we are going to
give a semi-formal definition and discuss how to create complicated statements
from simple statements.

It is difficult to give a formal definition of what a mathematical statement is,
hence, we are not going to do it; the goal of this section is to
enable the reader to recognize mathematical statements.

A \emph{proposition} or a mathematical statement is a declarative sentence
which is either true or false but not both. Consider the following list of
sentences.
\begin{enumerate}
  \item $2 \times 2 = 4$
  \item $\pi = 4$
  \item $n$ is even
  \item 32 is special
  \item The square of any odd number is odd.
  \item The sum of any even number and one is prime.
\end{enumerate}
Of those, the first two are propositions; note that this says nothing about
whether they are true or not. Actually, the first is true and the second is
false. However, the third sentence becomes a proposition only when the value
of $n$ is fixed. The fourth is not a proposition. Finally, the last
two are propositions (the fifth is true and the sixth is false).

The third statement is somewhat special, because there is a simple way to make
it a proposition: one just needs to fix the value of the variable. Such
sentences are called predicates and the variables that need to be specified are
called free variables of these predicates.

Note that the fourth sentence is also interesting, since if we define what it
means to be special, the phrase becames a proposition.
As it is illustrated by the last two statements mathematicians tend to do such
things to give mathematical meanings to everyday words.

\section{Connectives}

Mathematicians often need to decide whether a given proposition is true or
false. Many statements are complicated and constructed from simpler statements
using \emph{logical connectives}. For example we may consider the following
statements:
\begin{enumerate}
  \item $3 > 4$ and $1 < 1$;
  \item $1 \times 2 = 5$ or $6 > 1$.
\end{enumerate}

\paragraph{Logical connective ``OR''.}
The second statement is an example of usage of this connective. The statement
``P or Q'' is true if and only if at least one of P and Q is true. We may
define the connective using the truth table of it.
\begin{center}
    \begin{tabular}{l l l}
        \toprule
        P & Q & P or Q \\
        \midrule
        T & T & T \\
        T & F & T \\
        F & T & T \\
        F & F & F \\
        \bottomrule
  \end{tabular}
\end{center}

The or connective is also called \emph{disjunction} and the disjunction of $P$
and $Q$ is often denoted as $P \lor Q$.

\nomenclature[L]{$P \lor Q$}{denotes the statement saying that at least one of
$P$ and $Q$ is true}

\begin{warning}
  Note that in everyday speech ``or'' is often used in the exclusive case, like
  in the sentence ``we need to decide whether it is an insect or a spider''.
  In this case the precise meaning of ``or'' is made clear by the context.
  However, mathematical language should be formal, hence, we always use ``or''
  inclusively.
\end{warning}

\paragraph{Logical connective ``AND''.}
The first statement is an example of this connective. The statement ``P and Q''
is true if and only if both P and Q are true. We may define the
connective using the truth table of it.
\begin{center}
  \begin{tabular}{l l l}
      \toprule
      P & Q & P and Q \\
      \midrule
      T & T & T \\
      T & F & F \\
      F & T & F \\
      F & F & F \\
      \bottomrule
  \end{tabular}
\end{center}

The and connective is also called \emph{conjunction} and the conjunction of
$P$ and $Q$ is often denoted as $P \land Q$.

\nomenclature[L]{$P \land Q$}{denotes the statement saying that $P$ and $Q$
are both true}

\begin{warning}
  Not all the properties of ``and'' from everyday speech are captured by
  logical conjunction. For example, ``and'' sometimes implies order. For
  example, ``They got married and had a child'' in common language means that
  the marriage came before the child. The word ``and'' can also imply a
  partition of a thing into parts, as ``The American flag is red, white, and
  blue.'' Here it is not meant that the flag is at once red, white, and blue,
  but rather that it has a part of each color.
\end{warning}

\paragraph{Logical connective ``NOT''.}
The last connective is called \emph{negation} and examples of usage of it are
the following:
\begin{enumerate}
  \item 5 is not greater than 8;
  \item Does not exist an integer $n$ such that $n^2 = 2$.
\end{enumerate}

Note that it is not straightforward where to put the negation in these
sentences.

The negation of a statement $P$ is denoted as $\lnot P$ (sometimes it is also
denoted as $\sim P$).
\nomenclature[L]{$\lnot P$}{denotes the statement saying that $P$ is false}

\begin{chapterendexercises}
  \exercise Construct truth tables for the statements
    \begin{itemize}
      \item not ($P$ and $Q$);
      \item (not $P$) or (not $Q$);
      \item $P$ and (not $Q$);
      \item (not $P$) or $Q$;
    \end{itemize}
  \exercise[recommended] Consider the statement ``All gnomes like cookies''. Which of
    the following statements is the negation of the above statement?
    \begin{itemize}
      \item All gnomes hate cookies.
      \item All gnomes do not like cookies.
      \item Some gnomes do not like cookies.
      \item Some gnomes hate cookies.
      \item All creatures who like cookies are gnomes.
      \item All creatures who do not like cookies are not gnomes.
    \end{itemize}
  \exercise Using truth tables show that the following statements are
    equivalent:
    \begin{itemize}
      \item $P \implies Q$,
      \item $(P \lor Q) \iff Q$
        ($A \iff B$ is the same as $(A \implies B) \land (B \implies A)$),
      \item $(P \land Q) \iff P$
    \end{itemize}
  \exercise Prove that three connectives ``or'', ``and'', and ``not'' can
    all be written in terms of the single connective ``notand'' where ``$P$
    notand $Q$'' is interpreted as ``not ($P$ and $Q$)'' (this operation is
    also known as Sheffer stroke or NAND).
  \exercise Show the same statement about the connective ``notor'' where
    ``$P$ notor $Q$'' is interpreted as ``not ($P$ or $Q$)'' (this operation is
    also known as Peirce's arrow or NOR).
\end{chapterendexercises}


\problemname{Beautiful Primes}

\noindent John Nash is a talented mathematician at Princeton. Due to his prolific contributions in academia, he was even recruited to the Pentagon at a young age to crack enemy encrypted telecommunication. In his first task, John was able to decipher the code mentally, much to the astonishment of other decrypters. In his everyday life, he is constantly looking for patterns in magazines to newspapers to keep his senses sharp.\\

Recently, he has been cracking away at a cryptography problem that involves prime numbers. Given a positive integer $N$, the puzzle needs him to produce a ``beautiful" list of $N$ primes. A list of $N$ primes numbers is considered beautiful if each prime is at most $1\,000\,000$, and their product has exactly $N$ digits.\\

For example, if $N = 1$, then the list $[5]$ is beautiful because its length is $1$, and its product $5$ has $1$ digit.\\

For $N = 2$, the list $[3, 7]$ is beautiful because its product $3 \times 7 = 21$ has the required digit count of $2$.\\

For $N = 3$, the list $[5, 5, 7]$ is beautiful because its product $5 \times 5 \times 7 = 175$ has the required digit count of $3$.\\

John wants to practice his mental math and impress his colleagues. He needs you to write a program that helps him practice this interesting task. John Nash has a beautiful mind, so won't you help him find some beautiful primes?

\section*{Input}
The first line of input consists of a single integer $T$ ($1 \leq T \leq 50$), the number of test cases.\\
$T$ lines follow, each of which is a test case consisting of a single integer $N$ ($1 \leq N \leq 1\,000$).

\section*{Output}
For each test case, print, on a separate line, a list of $N$ space-delimited beautiful primes that are each no greater than $1\,000\,000$. The primes do not have to be distinct, and may be printed in any order. If there are multiple answers, you may print any of them.\\