\documentclass{article}
\input kvmacros
\sloppy
\begin{document}
\title{Typesetting Karnaugh Maps and Veitch Charts with \LaTeX}
\author{Andreas W. Wieland\\eMail: \texttt{awwieland@gmx.de}}
\date{January 7th, 2002}
\maketitle

\section{Abstract}

Karnaugh maps and Veitch charts\footnote{In previous releases of this document
 I referred to Karnaugh maps as Karnaugh-Veitch-Maps. This was definitely not
 correct. Thanks to F.~M.~Brown for pointing this error out to me.} are used
 to simplify logic equations. The  drawing of them used to be a boring,
 annoying and error-prone task. With the included macros this is no longer a
 problem. They can typeset Karnaugh maps and Veitch charts with up to ten
 variables, which is more than you might likely need. You only have to provide
 a list of variable identifiers plus the function table of your logic
 function(s). The macros also allow to mark the simplifications of your logic
 function directly within a Karnaugh map or Veitch chart.

\section{Introduction}

Karnaugh maps and Veitch charts are used to simplify logic equations. They are
map representations of logic functions, and in that they are equivalent. The
difference between the two kinds of diagrams is the way in which the variables
of the functions are located within the diagrams: ``The Karnaugh map \ldots{}
displays a function's discriminants according to the reflected binary (Gray)
code. The Veitch chart \ldots{} displays the discriminants in natural binary
order.'' (F.~M.~Brown)

However, the drawing of either kind of them used to be a boring, annoying and
error-prone task. Since I  had to typeset a 50+~page collection of exercises
for a basic computer-science lecture with plenty of Karnaugh maps in it, I
decided to write  some macros that would do this task for me. Let us start
first with an introduction on how to use these Macros:

The first thing you have to do is to put the macro file \verb|kvmacros.tex|
into a directory where \TeX{} will find it, i.e. you have to put it into a
directory where your \texttt{TEXINPUTS} environment variable points to. You
can then load them by typing
\verb|\input kvmacros| somewhere in the preamble of your document.

Suppose now you have a logic function~$f$ with the following function table:

\begin{center}

\begin{tabular}{lr}
  \begin{tabular}[t]{r|cccc|c}
Index&$a$&$b$&$c$&$d$&$f$\\
\hline
0&0&0&0&0&1\\
1&0&0&0&1&1\\
2&0&0&1&0&1\\
3&0&0&1&1&0\\
4&0&1&0&0&0\\
5&0&1&0&1&1\\
6&0&1&1&0&1\\
7&0&1&1&1&0\\
  \end{tabular}
&
  \begin{tabular}[t]{r|cccc|c}
Index&$a$&$b$&$c$&$d$&$f$\\
\hline
8&1&0&0&0&0\\
9&1&0&0&1&1\\
10&1&0&1&0&1\\
11&1&0&1&1&0\\
12&1&1&0&0&0\\
13&1&1&0&1&1\\
14&1&1&1&0&1\\
15&1&1&1&1&0\\
  \end{tabular}
\end{tabular}
\end{center}

This logic function can easily be put into a Karnaugh map by using the
\verb|\karnaughmap|-macro\footnote{Users of older versions of the macro
package will notice that the name has changed. Below you will find a
discussion of the changes between versions.}. It has five parameters: The
number of variables in the  map, an identifier for the function, a list of
variable identifiers for the variables, and the list of  values of $f$ for
each line in the function table. The variable identifiers in the third
parameter are ordered from highest to lowest significance (the same way as in
the function table, with $a$ having a significance of $2^3=8$ and $d$ having a
significance of $2^0=1$). The list of values of $f$ was read from lowest to
highest index. The fifth parameter remains empty in this example, it will be
discussed below:

\begin{verbatim}
\karnaughmap{4}{f(a,b,c,d):}{abcd}{1110011001100110}{}
\end{verbatim}

This produces the following Karnaugh map, where the indices in the lower left
corner of each box correspond to the indices in the function
table:\footnote{The indices can easily be calculated from the variable values
  in the function table, i.e. line 11: the index equals $a\cdot 2^3 + b\cdot
  2^2 + c \cdot 2^1 + d \cdot 2^0=1\cdot 8 + 0\cdot 4 + 1 \cdot 2 + 1 \cdot
  1=11$.}

\begin{center}
\karnaughmap{4}{f(a,b,c,d):}{abcd}{1110011001100110}{}
\end{center}

The macros work similar for Veitch charts:

\begin{verbatim}
\veitchchart{4}{f(a,b,c,d):}{abcd}{0110011001100110}{}
\end{verbatim}

\begin{center}
\veitchchart{4}{f(a,b,c,d):}{abcd}{0110011001100110}{}
\end{center}

Notice the difference in the variable location in the diagrams. In my opinion
Karnaugh maps are much easier to use if you need to simplify a logic function;
therefore Veitch charts will not be discussed any further in this
document. Except otherwise noticed, the macros' syntax and functionality are
exactly the same for Karnaugh maps and Veitch charts.

The macros that read the variable list and the list of logic values
(i.e. parameters \#3 and \#4) work
recursively. Therefore, you have to take special care to supply the
correct number of tokens to print: If you supply a list of variable
identifiers or a list of logic values that contains fewer elements than needed
the macros will cause error messages similar to the following:

\begin{verbatim}
! Argument of \kvgetonechar has an extra }.
<inserted text>
                \par
l.201 }{}

?
\end{verbatim}

On the contrary, if any of the two lists is longer than
needed, \emph{you will not be notified!}  Moreover, each entry has to be one
character long, otherwise --- like a variable identifier enclosed in \$s ---
you have to put it into braces:

\begin{verbatim}
\karnaughmap{4}{$f(a,b,c,d):$}{{$a$}{$b$}{$c$}{$d$}}{0110011001100110}{}
\end{verbatim}

This produces the following Karnaugh map:

\begin{center}
\karnaughmap{4}{$f(a,b,c,d):$}{{$a$}{$b$}{$c$}{$d$}}{0110011001100110}{}
\end{center}

\section{Marking simplifications}

The already mentioned fifth parameter can be used if you want to draw
something inside the Karnaugh map. For example this is  useful if you want to
show how you simplified a logic function:

\begin{verbatim}
\karnaughmap{4}{$f(a,b,c,d):$}{{$a$}{$b$}{$c$}{$d$}}%
{0110011001100110}%
{%
\put(0,2){\oval(1.9,1.9)[r]}
\put(4,2){\oval(1.9,1.9)[l]}
\put(2,0){\oval(1.9,1.9)[t]}
\put(2,4){\oval(1.9,1.9)[b]}
}
\end{verbatim}

The corresponding Karnaugh map looks like this:

\begin{center}
\karnaughmap{4}{$f(a,b,c,d):$}{{$a$}{$b$}{$c$}{$d$}}%
{0110011001100110}%
{%
\put(0,2){\oval(1.9,1.9)[r]}
\put(4,2){\oval(1.9,1.9)[l]}
\put(2,0){\oval(1.9,1.9)[t]}
\put(2,4){\oval(1.9,1.9)[b]}
}
\end{center}

You can use any of \LaTeX's graphics macros for this purpose. The Karnaugh map
has its pivot point at the lower left point\footnote{This is not exactly true,
but sufficient if you do not want to modify the macros.} and a unitlength that
is equal to the length of a single box within the Karnaugh map. Sometimes you
may find that the \verb|\oval|s that you want to draw inside a Karnaugh map are
slightly shifted to the right. This occurs if you use the \verb|eepic|-Package
in your document. In this case, make a copy of the \verb|eepic.sty| file,
rename it to something like \verb|myeepic.sty| and comment out the definition
of the \verb|\oval|-macro in your local copy. If you put this new
\verb|myeepic.sty| file somewhere into your \TeX's search path so that \TeX{}
can find it and you load it properly with e.g. \verb|\usepackage{myeepic}|,
you shouldn't experience any more trouble.

\section{Other features}

There are some more features that you can use. Possibly the most important is
that  you can change the size of the diagrams by changing the size of the
boxes within the map, simply by typing:

\begin{verbatim}
\kvunitlength=15mm
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{verbatim}

This results in the following Karnaugh map. The setting of the
\verb|\kvunitlength| remains active until you change it again;\footnote{Or, of
  course, until you leave the group in which you redefined the value. This
  applies to all changeable parameters and macro definitions in this section!}
the default \verb|\kvunitlength| is 8\,mm:

\begin{center}
\kvunitlength=15mm
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{center}

Another feature is that you can switch off the indices inside the map by
typing:

\begin{verbatim}
\kvnoindex
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{verbatim}

\begin{center}
\kvunitlength=8mm
\kvnoindex
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{center}

This setting also remains active until you switch indexing on again using the
\verb|\kvindex|-macro:

\begin{verbatim}
\kvindex
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{verbatim}

\begin{center}
\kvindex
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{center}

Usually, the font size of the map's contents and indices should be
suitable (the defaults are \verb|\tiny| for \verb|\kvindexsize| and
\verb|\normalsize| for \verb|\kvcontentsize|). If you want to change them, you
can do this by redefining the \verb|\kvcontentsize|- and
\verb|\kvindexsize|-macros (Preferably, you should do this in the preamble of
your document):

\begin{verbatim}
\renewcommand\kvindexsize{\footnotesize}
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{verbatim}

\begin{center}
\renewcommand\kvindexsize{\footnotesize}
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{center}

In the same way you can also change the font family (Although I doubt that
this is sensible):

\begin{verbatim}
\renewcommand\kvindexsize{\footnotesize\it}
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{verbatim}

\begin{center}
\renewcommand\kvindexsize{\footnotesize\it}
\karnaughmap{4}{$f:$}{abcd}{0110011001100110}{}
\end{center}

These macros are named \verb|\kvfoo|, because they work both for Karnaugh maps
and Veitch charts.

\section{If you use an older version of the macros\ldots}

\ldots{} you will certainly have noticed a number of changes. The most
important one is that I have changed the name of the macro that draws Karnaugh
maps from \verb|\kvmap| to \verb|\karnaughmap|. I suggest that you use the new
name in documents that you newly create. However, I introduced an alias so
that the old macro name still works:

\begin{verbatim}
\def\kvmap{\karnaughmap}
\end{verbatim}

Also, in some older versions tokens in the variable list or function table
that were longer than one character had to be enclosed in \emph{double} braces
(If you have used any of these versions you will certainly remember this
annoying  feature). This is no longer necessary   --- however, it does no
harm.

If you need to know more about the exact changes, please consult the revision
history in \verb|kvmacros.tex|.

\section{Final remarks}

This is all you need to know about the usage of my macros. I have tried them
out and I haven't yet found any serious bugs, but I'm pretty sure there are
plenty. In this case, or if you have comments or suggestions,  please send me
an eMail. Anyway, I would very much appreciate if you would notify me when you
use my macros; I would like to know if they are of any use to somebody.

The maximum size map I could produce was a Karnaugh map with 10~variables;
with bigger maps I only exceeded \TeX's main memory. This is due to the
macros' recursive algorithm. Quite likely you will exceed \TeX's capacity with
even smaller maps if they occur in large documents, but I think no~one in his
right mind will ever use Karnaugh maps of more than 6\,variables, so I didn't
care about this problem.

\section{More examples}

Below I have given some more examples of Karnaugh maps produced with my
macros:

\begin{verbatim}
\karnaughmap{1}{}{a}{01}{}

\karnaughmap{2}{$f:$}{{$a$}{$b$}}{0110}{}

\karnaughmap{3}{$f:$}{{$a$}{$b$}{$c$}}{01100110}{}

\karnaughmap{4}{$f:$}{{$a$}{$b$}{$c$}{$d$}}{0110011001100110}{}

\karnaughmap{4}{$f:$}{abcd}{abcdefghijklmnop}{}

\karnaughmap{5}{$f:$}{{$a$}{$b$}{$c$}{$d$}{$e$}}%
{0123456789abcdef0123456789abcdef}{}

\karnaughmap{6}{$f_i^t:$}{abcdef}%
{0123456789{10}{11}{12}{13}{14}{15}%
{16}{17}{18}{19}{20}{21}{22}{23}%
{24}{25}{26}{27}{28}{29}{30}{31}%
{32}{33}{34}{35}{36}{37}{38}{39}%
{40}{41}{42}{43}{44}{45}{46}{47}%
{48}{49}{50}{51}{52}{53}{54}{55}%
{56}{57}{58}{59}{60}{61}{62}{63}}{}%

\kvunitlength=6mm
\kvnoindex
\karnaughmap{8}{$q_2^4:$}{{$a$}{$b$}{$c$}{$d$}{$e$}%
{$f$}{$g$}{$h$}}{%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
}{}
\kvunitlength=8mm
\kvindex
\end{verbatim}

\begin{flushleft}
\karnaughmap{1}{}{a}{01}{}

\karnaughmap{2}{$f:$}{{$a$}{$b$}}{0110}{}

\karnaughmap{3}{$f:$}{{$a$}{$b$}{$c$}}{01100110}{}

\karnaughmap{4}{$f:$}{{$a$}{$b$}{$c$}{$d$}}{0110011001100110}{}

\karnaughmap{4}{$f:$}{abcd}{abcdefghijklmnop}{}

\karnaughmap{5}{$f:$}{{$a$}{$b$}{$c$}{$d$}{$e$}}%
{0123456789abcdef0123456789abcdef}{}

\karnaughmap{6}{$f_i^t:$}{abcdef}%
{0123456789{10}{11}{12}{13}{14}{15}%
{16}{17}{18}{19}{20}{21}{22}{23}%
{24}{25}{26}{27}{28}{29}{30}{31}%
{32}{33}{34}{35}{36}{37}{38}{39}%
{40}{41}{42}{43}{44}{45}{46}{47}%
{48}{49}{50}{51}{52}{53}{54}{55}%
{56}{57}{58}{59}{60}{61}{62}{63}}{}%

\kvunitlength=6mm
\kvnoindex
\karnaughmap{8}{$q_2^4:$}{{$a$}{$b$}{$c$}{$d$}{$e$}%
{$f$}{$g$}{$h$}}{%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
0011001111001100%
}{}
\kvunitlength=8mm
\kvindex
\end{flushleft}

\section{Sourcecode}

Here now you will find the current sourcecode of my macros. I should have
commented it more extensively, but failed due to lack of time. Sorry.

\small
\begin{verbatim}
%% This is file `kvmacros.tex',
%% Version of January 7th, 2002
%%
%% Copyright (C) 1998-2002 by Andreas W. Wieland, awwieland@gmx.de
%%
%% This program can be redistributed and/or modified under the terms
%% of the LaTeX Project Public License distributed from CTAN
%% archives in directory macros/latex/base/lppl.txt; either
%% version 1 of the License, or (at your option) any later version,
%% with `The Program' referring to the software `kvmacros.tex' and its
%% accompanying documentation and `The Copyright Holder' referring to the
%% person Andreas W. Wieland.
%%
%%
%%
%% IMPORTANT NOTICE:
%%
%% For error reports, comments or suggestions in case of UNCHANGED
%% versions send mail to:
%% awwieland@gmx.de
%%
%% Anyway, if you use my macros, send me an eMail, too. I would like to know
%% if they are useful to somebody out there.
%%
%% Please do not request updates from me directly. Distribution is
%% done through Mail-Servers and TeX organizations.
%%
%% You are allowed to distribute this file under the condition that
%% it is distributed together with `kvdoc.tex', `kvdoc.dvi' and `kvdoc.ps'.
%%
%% If you receive this file alone from someone, complain!
%%
\typeout{}
\typeout{Macros for typesetting Karnaugh maps and Veitch charts}
\typeout{Version of January 7th, 2002}
\typeout{by Andreas W. Wieland, awwieland@gmx.de}
\typeout{}
%%
%% Change History:
%% August 04th, 1998: Original Version
%%
%% August 19th, 1998: Minor changes to make the lines within the maps look
%% better, also moved the variable identifiers from the right to the left and
%% added an identifier for the logic function; since then \kvmap has 5
%% instead of 4 parameters. I also included the documentation in an additional
%% Postscript-file.
%%
%% September 23rd, 1998: Fixed the problem with double braces by introducing
%% the \compdummy and \ende macros in the \ifx-comparisons (see below):
%% The parameters that are longer than one character do not have to be
%% enclosed in double braces any longer --- single braces are
%% sufficient. However, double braces will still be processed correctly.
%%
%% May 19th, 1999: Changed the documentation (which was months overdue) after
%% F. M. Brown pointed me to the incorrectness of the term
%% "Karnaugh-Veitch-map". Actually, the macros itself haven't
%% changed. Probably I should introduce macros for typesetting Veitch charts
%% as well (which would be a minor task). This version was actually never
%% released.
%%
%% May 25th, 1999: Introduced macros for Veitch charts
%% (\veitchfoo) and renamed the macros that are solely related to
%% Karnaugh maps from \kvfoo to \karnaughfoo. Introduced aliases for those
%% macros that are user-callable to maintain compatibility with older versions:
%% \kvmap -> \karnaughmap. However, \kvindex, \kvnoindex and \kvunitlength
%% haven't changed their names as they are related to both Karnaugh maps and
%% Veitch charts. Changed the (plain stupid) algorithm that processes the
%% variable-length arguments so that it takes much less time to produce large
%% maps. Several macros so became redundant and are no longer included. Also I
%% introduced \kvindexsize and \kvcontentsize to adjust the font size of the
%% indices and the contents of a diagram. They default to \tiny and
%% \normalsize.
%%
%% January 17th, 2001: Changed the eMail-address in the macro file and the
%% accompanying documentation and made minor changes to the documentation.
%%
%% January 7th, 2002: Exchanged the \xdef to \gdef in the definition of
%% \kvargumentstring and \kvgetonechar so that things like {\textbf 1} in the
%% argumentlist of \karnaughmap do not cause error messages any longer.
%% Thanks to Michal Medveck{\'y} for pointing me to this error.
%%
%%
%%
%% We need a fixed dimension for a single field in a Karnaugh map:
%%
\newdimen\kvunitlength
\kvunitlength=8mm
%%
%% We need a default font size for the indices:
%%
\newcommand{\kvindexsize}{\tiny}
%%
%% And we need a default size for the contents and variable identifiers:
%%
\newcommand{\kvcontentsize}{\normalsize}
%%
%% First, we have to introduce some counters:
%%
%% \kvrecursiondepth is used to control the recursion of the
%% \karnaughmakemap- and \veitchmakechart-macro.
%%
\newcount\kvrecursiondepth
%%
%% The \kvindexcounter is needed for the indices in the fields of the
%% diagrams.
%%
\newcount\kvindexcounter
%%
%% \kvxsize and \kvysize store the dimensions of an entire diagram.
%%
\newcount\kvxsize
\newcount\kvysize
%%
%% Some counters are necessary to compute the marks for the variable
%% identifiers:
%%
\newcount\kvvarno
\newcount\kvxvarno
\newcount\kvyvarno
\newcount\kvmarkstart
\newcount\kvmarklength
\newcount\kvmarknum
\newcount\kvmarkmove
%%
%% And we need a savebox to store the variable marks:
%%
\newsavebox\kvsavebox
%%
%% Single fields in a diagram should be indexed, which makes the map easier to
%% use. This is the default. If you don't want indices, simply call
%% \kvnoindex. If you want indices back, call \kvindex:
%%
\def\kvnoindex{%
\def\kvcurrentindex{}}
%%
\def\kvindex{%
\def\kvcurrentindex{%
\the\kvindexcounter\global\advance\kvindexcounter by 1}%
}
%%
\kvindex
%%
%% We need a macro that computes the powers of two:
%%
\def\kvpoweroftwo#1#2{% Computes #1=2^#2, both of which have to be counters
{\ifnum#2>0
\global\multiply#1 by 2
\advance#2 by -1
\kvpoweroftwo{#1}{#2}
\fi}}
%%
%% The macros \kvargumentstring, \kvgetchar and \kvgetonechar are needed to
%% process the variabe-length parameters in \karnaughmap and \veitchchart:
%%
\def\kvargumentstring#1{\gdef\kvdummystring{#1{}\noexpand\end}}
%%
\def\kvgetchar{\expandafter\kvgetonechar\kvdummystring}
%%
\def\kvgetonechar#1#2\end{{#1}\gdef\kvdummystring{#2\noexpand\end}}%
%%
%% The Macro \karnaughmakemap calls itself recursively until the parameter #1
%% equals 1, whereupon it returns a single token from the list of arguments,
%% enclosed in a \makebox plus the index (if enabled) in a smaller \makebox:
%%
\def\karnaughmakemap#1#2{{%
\kvrecursiondepth=\number#1
\ifnum\kvrecursiondepth>1
\divide\kvrecursiondepth by 2
\unitlength=\kvunitlength
\multiply\unitlength by \kvrecursiondepth
%%
\ifcase#2
%%
%% The parameter #2 of \karnaughmakemap is needed because the inner Karnaugh
%% maps need to be mirrored. This is achieved by the following case-statement,
%% which orders the inner Karnaugh maps properly:
%%
%% Case 0: top-left Karnaugh map
\begin{picture}(2,2)%
\put(0,1){\karnaughmakemap{\kvrecursiondepth}{0}}%
\put(1,1){\karnaughmakemap{\kvrecursiondepth}{1}}%
\put(0,0){\karnaughmakemap{\kvrecursiondepth}{2}}%
\put(1,0){\karnaughmakemap{\kvrecursiondepth}{3}}%
\end{picture}%
\or
%% Case 1: top-right Karnaugh map
\begin{picture}(2,2)%
\put(1,1){\karnaughmakemap{\kvrecursiondepth}{1}}%
\put(0,1){\karnaughmakemap{\kvrecursiondepth}{0}}%
\put(1,0){\karnaughmakemap{\kvrecursiondepth}{3}}%
\put(0,0){\karnaughmakemap{\kvrecursiondepth}{2}}%
\end{picture}%
\or
%% Case 2: bottom-left Karnaugh map
\begin{picture}(2,2)%
\put(0,0){\karnaughmakemap{\kvrecursiondepth}{2}}%
\put(1,0){\karnaughmakemap{\kvrecursiondepth}{3}}%
\put(0,1){\karnaughmakemap{\kvrecursiondepth}{0}}%
\put(1,1){\karnaughmakemap{\kvrecursiondepth}{1}}%
\end{picture}%
\or
%% Case 3: bottom-right Karnaugh map
\begin{picture}(2,2)%
\put(1,0){\karnaughmakemap{\kvrecursiondepth}{3}}%
\put(0,0){\karnaughmakemap{\kvrecursiondepth}{2}}%
\put(1,1){\karnaughmakemap{\kvrecursiondepth}{1}}%
\put(0,1){\karnaughmakemap{\kvrecursiondepth}{0}}%
\end{picture}%
\fi
\else
\unitlength=\kvunitlength
\begin{picture}(1,1)
\put(0,0){\makebox(1,1){\kvcontentsize\kvgetchar}}%
\put(0.05,0.05){\makebox(0.9,0.9)[bl]{\kvindexsize\kvcurrentindex}}%
\end{picture}
\fi}}%
%%
%% \karnaughmaketopmark typesets the variable marks of a Karnaugh map that are
%% located on top of the diagram:
%%
\def\karnaughmaketopmark{%
  \unitlength\kvunitlength
  \begin{picture}(\kvxsize,1)
    \kvmarkstart=1
    \kvpoweroftwo{\kvmarkstart}{\kvxvarno} % \kvymarkstart is the start
                                % position for the \multiput
    \kvmarklength=\kvmarkstart
    \multiply\kvmarklength by 2 % \kvmarklength is the length of a mark
    \kvmarkmove=\kvmarkstart
    \multiply\kvmarkmove by 4 % This is the move distance for the \multiput.
    \kvmarknum=\kvxsize
    \divide\kvmarknum by \kvmarkmove % This is the number of repetitions for
                                % the \multiput.
    %The highest-order variable mark needs a special treatment:
    \ifnum\kvmarknum=0\kvmarknum=1\divide\kvmarklength by 2\fi
    \savebox\kvsavebox(\kvmarklength,1){%
      \begin{picture}(\kvmarklength,1)
      \put(0,0.3){\makebox(\kvmarklength,0.7){\kvcontentsize\kvgetchar}}
      \put(0,0.1){\line(0,1){0.4}}
      \put(\kvmarklength,0.1){\line(0,1){0.4}}
      \put(0,0.3){\line(1,0){\kvmarklength}}
      \end{picture}}
    \multiput(\kvmarkstart,0)(\kvmarkmove,0){\kvmarknum}{\usebox\kvsavebox}
  \end{picture}
}
%%
%% \karnaughmakeleftmark typesets the variable marks of a Karnaugh map that are
%% located on the left of the diagram:
%%
\def\karnaughmakeleftmark{%
  \unitlength\kvunitlength
  \begin{picture}(-1,\kvysize)(0,-\kvysize)
    \kvmarkstart=1
    \kvpoweroftwo{\kvmarkstart}{\kvyvarno} % \kvmarkstart is the start
                                % position for the \multiput
    \kvmarklength=\kvmarkstart
    \multiply\kvmarklength by 2 % \kvmarklength is the length of a mark
    \kvmarkmove=\kvmarkstart
    \multiply\kvmarkmove by 4 % This now is the move distance for the
                              % \multiput.
    \kvmarknum=\kvysize
    \divide\kvmarknum by \kvmarkmove % This now is the number of
                                % repetitions for the \multiput.
    %The highest-order variable mark needs a special treatment:
    \ifnum\kvmarknum=0\kvmarknum=1\divide\kvmarklength by 2\fi
    \advance\kvmarkstart by \kvmarklength
    \savebox\kvsavebox(1,\kvmarklength){%
      \begin{picture}(1,\kvmarklength)
        \put(-0.3,0){\makebox(-0.7,\kvmarklength){\kvcontentsize\kvgetchar}}
        \put(-0.1,0){\line(-1,0){0.4}}
        \put(-0.1,\kvmarklength){\line(-1,0){0.4}}
        \put(-0.3,0){\line(0,1){\kvmarklength}}
      \end{picture}}
    \multiput(0,-\kvmarkstart)(0,-\kvmarkmove){\kvmarknum}{\usebox\kvsavebox}
  \end{picture}
}
%% \karnaughmakemarks calls \karnaughmaketopmark or \karnaughmakeleftmark
%% depending on whether \kvvarno is odd or even.
%%
\def\karnaughmakemarks{%
\ifnum\kvvarno>0
  \let\next=\karnaughmakemarks
  \ifodd\kvvarno % We have to make a mark at the top
    \advance\kvxvarno by -1
    \put(0,\kvxvarno){\karnaughmaketopmark}
  \else % We have to make a mark at the left
    \advance\kvyvarno by -1
    \put(-\kvyvarno,-\kvysize){\karnaughmakeleftmark}
  \fi
  \advance\kvvarno by -1
\else
  \let\next=\relax
\fi
\next
}
%%
%% \karnaughmap is the macro that a user calls if he wants to draw a
%% Karnaugh map:
%%
\def\karnaughmap#1#2#3#4#5{%
%%
%% #1 is the number of variables in the Karnaugh map
%% #2 is the identifier of the function
%% #3 is the list of identifiers of those variables
%% #4 is the list of tokens that have to be written into the map
%% #5 is something that you want to draw inside the Karnaugh map
%%
\kvvarno=#1  % \kvvarno is the total number of variables
\kvyvarno=#1 % \kvyvarno is the number of variable marks at the left
\divide\kvyvarno by 2
\kvxvarno=#1 % \kvxvarno is the number of variable marks on top
\advance\kvxvarno by -\kvyvarno
\kvxsize=1
\kvpoweroftwo{\kvxsize}{\kvxvarno}
\kvysize=1
\kvpoweroftwo{\kvysize}{\kvyvarno}
\advance\kvxsize by \kvyvarno
\advance\kvxvarno by \kvysize
\unitlength\kvunitlength
\begin{picture}(\kvxsize,\kvxvarno)(-\kvyvarno,-\kvysize)
\advance\kvxsize by -\kvyvarno
\advance\kvxvarno by -\kvysize
\put(0,-\kvysize){%
\begin{picture}(\kvxsize,\kvysize)
\multiput(0,0)(0,1){\kvysize}{\line(1,0){\kvxsize}}
\multiput(0,0)(1,0){\kvxsize}{\line(0,1){\kvysize}}
\put(0,\kvysize){\line(1,0){\kvxsize}}
\put(\kvxsize,0){\line(0,1){\kvysize}}
#5
\end{picture}}
\put(-\kvyvarno,0){\makebox(\kvyvarno,\kvxvarno){#2}}
\kvindexcounter=0
\kvargumentstring{#4}
\put(0,-\kvysize){\karnaughmakemap{\kvysize}{0}}
\ifodd\kvvarno
{\divide\kvxsize by 2
\put(\kvxsize,-\kvysize){\karnaughmakemap{\kvysize}{1}}}
\fi
\kvargumentstring{#3}
\karnaughmakemarks
%%
\end{picture}
}%
%%
%% The definition of \kvmap is necessary to maintain compatibility with older
%% versions of this macro package:
%%
\def\kvmap{\karnaughmap}%
%%
%%
%% The Macro \veitchmakechart calls itself recursively until the parameter #1
%% equals 1, whereupon it returns a single token from the list of arguments,
%% enclosed in a \makebox plus the index (if enabled) in a smaller \makebox:
%%
\def\veitchmakechart#1{{%
\kvrecursiondepth=\number#1
\ifnum\kvrecursiondepth>1
\divide\kvrecursiondepth by 2
\unitlength=\kvunitlength
\multiply\unitlength by \kvrecursiondepth
%%
\begin{picture}(2,2)%
\put(0,1){\veitchmakechart{\kvrecursiondepth}}%
\put(1,1){\veitchmakechart{\kvrecursiondepth}}%
\put(0,0){\veitchmakechart{\kvrecursiondepth}}%
\put(1,0){\veitchmakechart{\kvrecursiondepth}}%
\end{picture}%
\else
\unitlength=\kvunitlength
\begin{picture}(1,1)
\put(0,0){\makebox(1,1){\kvcontentsize\kvgetchar}}%
\put(0.05,0.05){\makebox(0.9,0.9)[bl]{\kvindexsize\kvcurrentindex}}%
\end{picture}
\fi}}%
%%
\def\veitchmaketopmark{%
  \unitlength\kvunitlength
  \begin{picture}(\kvxsize,1)
    \kvmarkstart=1
    \kvpoweroftwo{\kvmarkstart}{\kvxvarno} % \kvymarkstart is the start
                                % position for the \multiput
    \kvmarklength=\kvmarkstart % \kvmarklength is the length of a mark
    \kvmarkmove=\kvmarkstart
    \multiply\kvmarkmove by 2 % This is the move distance for the \multiput.
    \kvmarknum=\kvxsize
    \divide\kvmarknum by \kvmarkmove % This is the number of repetitions for
                                     % the \multiput.
    \savebox\kvsavebox(\kvmarklength,1){%
      \begin{picture}(\kvmarklength,1)
      \put(0,0.3){\makebox(\kvmarklength,0.7){\kvcontentsize\kvgetchar}}
      \put(0,0.1){\line(0,1){0.4}}
      \put(\kvmarklength,0.1){\line(0,1){0.4}}
      \put(0,0.3){\line(1,0){\kvmarklength}}
      \end{picture}}
    \multiput(\kvmarkstart,0)(\kvmarkmove,0){\kvmarknum}{\usebox\kvsavebox}
  \end{picture}
}
%%
\def\veitchmakeleftmark{%
  \unitlength\kvunitlength
  \begin{picture}(-1,\kvysize)(0,-\kvysize)
    \kvmarkstart=1
    \kvpoweroftwo{\kvmarkstart}{\kvyvarno} % \kvmarkstart is the start
                                % position for the \multiput
    \kvmarklength=\kvmarkstart
    \kvmarkmove=\kvmarkstart
    \multiply\kvmarkmove by 2 % This now is the move distance for the \multiput.
    \kvmarknum=\kvysize
    \divide\kvmarknum by \kvmarkmove % This now is the number of
                                     % repetitions for the \multiput.
    \advance\kvmarkstart by \kvmarklength
    \savebox\kvsavebox(1,\kvmarklength){%
      \begin{picture}(1,\kvmarklength)
        \put(-0.3,0){\makebox(-0.7,\kvmarklength){\kvcontentsize\kvgetchar}}
        \put(-0.1,0){\line(-1,0){0.4}}
        \put(-0.1,\kvmarklength){\line(-1,0){0.4}}
        \put(-0.3,0){\line(0,1){\kvmarklength}}
      \end{picture}}
    \multiput(0,-\kvmarkstart)(0,-\kvmarkmove){\kvmarknum}{\usebox\kvsavebox}
  \end{picture}
}
%%
\def\veitchmakemarks{%
\ifnum\kvvarno>0
  \let\next=\veitchmakemarks
  \ifodd\kvvarno % We have to make a mark at the top
    \advance\kvxvarno by -1
    \put(0,\kvxvarno){\veitchmaketopmark}
  \else % We have to make a mark at the left
    \advance\kvyvarno by -1
    \put(-\kvyvarno,-\kvysize){\veitchmakeleftmark}
  \fi
  \advance\kvvarno by -1
\else
  \let\next=\relax
\fi
\next
}
%%
\def\veitchchart#1#2#3#4#5{%
%%
%% #1 is the number of variables in the Veitch chart
%% #2 is the identifier of the function
%% #3 is the list of identifiers of those variables
%% #4 is the list of tokens that have to be written into the chart
%% #5 is something that you want to draw inside the Veitch chart
%%
\kvvarno=#1  % \kvvarno is the total number of variables
\kvyvarno=#1 % \kvyvarno is the number of variable marks at the left
\divide\kvyvarno by 2
\kvxvarno=#1 % \kvxvarno is the number of variable marks on top
\advance\kvxvarno by -\kvyvarno
\kvxsize=1
\kvpoweroftwo{\kvxsize}{\kvxvarno}
\kvysize=1
\kvpoweroftwo{\kvysize}{\kvyvarno}
\advance\kvxsize by \kvyvarno
\advance\kvxvarno by \kvysize
\unitlength\kvunitlength
\begin{picture}(\kvxsize,\kvxvarno)(-\kvyvarno,-\kvysize)
\advance\kvxsize by -\kvyvarno
\advance\kvxvarno by -\kvysize
\put(0,-\kvysize){%
\begin{picture}(\kvxsize,\kvysize)
\multiput(0,0)(0,1){\kvysize}{\line(1,0){\kvxsize}}
\multiput(0,0)(1,0){\kvxsize}{\line(0,1){\kvysize}}
\put(0,\kvysize){\line(1,0){\kvxsize}}
\put(\kvxsize,0){\line(0,1){\kvysize}}
#5
\end{picture}}
\put(-\kvyvarno,0){\makebox(\kvyvarno,\kvxvarno){#2}}
\kvindexcounter=0
\kvargumentstring{#4}
\put(0,-\kvysize){\veitchmakechart{\kvysize}}
\ifodd\kvvarno
{\divide\kvxsize by 2
\put(\kvxsize,-\kvysize){\veitchmakechart{\kvysize}}}
\fi
\kvargumentstring{#3}
\veitchmakemarks
%%
\end{picture}
}%
%%

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:
\end{verbatim}

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:


\documentclass[a4paper]{article}

\usepackage{fullpage} % Package to use full page
\usepackage{parskip} % Package to tweak paragraph skipping
\usepackage{tikz} % Package for drawing
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amsthm}
\usepackage{booktabs}
\usepackage{hyperref}
\usepackage{graphicx}
\usepackage{courier}
\usepackage{float}
\usepackage{filecontents}% <-- useful for embedding external files in the main file

\theoremstyle{definition}
\newtheorem{example}{Example}[section]
\newtheorem{theorem}{Theorem}[section]

\title{Extending General Recurrences over Finite Fields}
\author{Robert Lech}
\date{2015/12/07}

\begin{document}

\maketitle

\section{Introduction}

Recurrences relations act as a powerful tool for simplifying many real world and mathematical problems.
They also come up naturally in finding bounds for the average or worst case scenario for algorithms in
the field of computer science. A key algorithm for deciding whether an element $k$ is in some sorted
list $L$ with $n$ elements is the Binary Search method. This method looks at an element found at index
$\lfloor\frac{n}{2}\rfloor$ in $L$. If $L[i]<k$ we repeat the algorithm on the former half of the list;
otherwise, we repeat the algorithm on the later half of the list. If the comparison of the terms took
one unit of time, then we can say the worst case scenario for the Binary Search method takes
$T(n)=T\left(\left\lfloor\frac{n}{2}\right\rfloor\right)+1$ where $T(1)=1$. On a separate note,
historically speaking, they seem to simply garner a mathematical curiosity. The Fibonacci recursion is
one of the oldest recurrence relations to date. This is because its simple pattern, yet complex proof
for a solution, demonstrates its importance to their study.

However, the above mentioned examples are examples of ``unconditional recurrence relations''. That is,
the $n^{th}$ term of any sequence depends on one set of previous terms. However, we are also
interested in recurrences whose dependency is conditional on the residue of $n$ mod $r$, where $r\in
\mathbb{N}, r>1$. For example, sequence [A068911], found on Sloane's \textit{On-Line Encyclopedia of
Integer Sequences}, describes ``the number of $n$-step walks (each step $\pm$ 1 starting from 0) which
are never more than 2 or less than -2''\cite{bib:gen_cond_rec}. The reader can convince themselves that
if $q_n$ describes this relationship, then:

\begin{align*}
q_n=
\begin{cases}
2q_{n-1}+0q_{n-2} & \equiv 0 \mod 2 \\
1q_{n-1}+1q_{n-2} & \equiv 1 \mod 2 \\
\end{cases}
\end{align*}

where $q_0=1$ (as there is only one $0$-step walk) and $q_1=2$ (as there are only two $1$-step walks --
a step forward, and a step backward). Moreover, it's also interesting to note that our previous
interpretation of $T(n)$ is also conditional on the parity of $n$. It can be defined piece-wise as:

\begin{align*}
T(n)=
\begin{cases}
T\left(\frac{n  }{2}\right) & \equiv 0 \mod 2 \\
T\left(\frac{n-1}{2}\right) & \equiv 1 \mod 2 \\
\end{cases}
\end{align*}

Lastly, we're interested in understanding how to extend these recurrence relations to finite fields. One
application of this occurs in Linear-Feedback-Shift-Registers. [They] are an efficient way of describing
and generating certain sequences in hardware implementations~\cite{bib:lfsr} and are defined over
various fields of the form $\mathbb{F}_{2}$.

For the purpose of this paper, we'll be focusing on conditional and unconditional linear recurrences.
We'll be explaining their general structure over various fields -- focusing on finite fields and
approaches to finding their solutions. If their solutions cannot be found using those techniques, we'll
at least note some observations about their structures.

\section{Solving linear recurrences over any Field}

\subsection{Explanation}
Let's go back to the Fibonacci recursion $f_n=f_{n-1}+f_{n-2}$ where $f_0=0$ and $f_1=1$. Then the
output for the sequence can be seen in Table~\ref{tab:fib-output}. Moreover, if we let
$f(n)=\frac{\phi^n-\overline{\phi}^n}{\sqrt{5}}, \phi=\frac{1+\sqrt{5}}{2}, \overline{\phi}=\frac{1-\sqrt{5}}{2}$,
then we can make the observation that $f_n=f(n)$. We say that $f(n)$ is the closed-form solution to the
linear recurrence relation $f_n$.

Similarly, we can define the Fibonacci recursion over a different field. Suppose we're interested in the
sequence output over the field $\mathbb{F}_5$. Then let $g_n \equiv f_n \pmod 5$ and $g(n)=2n3^n$. Then
the outputs for the sequence and function can be seen in Table~\ref{tab:fib-output} and we see that
$g(n) \equiv f(n) \pmod 5$.

\begin{table}[ht]
\centering
\begin{tabular}{lllllllllllllllll}
\toprule
$n$ & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15                             \\
\midrule
$f_n$ over $\mathbb{R}$ & 0 & 1 & 1 & 2 & 3 & 5 & 8 & 13 & 21 & 34 & 55 & 89 & 144 & 233 & 377 & 610  \\
$f(n)$ over $\mathbb{R}$ & 0 & 1 & 1 & 2 & 3 & 5 & 8 & 13 & 21 & 34 & 55 & 89 & 144 & 233 & 377 & 610 \\
$g_n$ over $\mathbb{F}_5$ & 0 & 1 & 1 & 2 & 3 & 0 & 3 & 3 & 1 & 4 & 0 & 4 & 4 & 3 & 2 & 0             \\
$g(n)$ over $\mathbb{F}_5$ & 0 & 1 & 1 & 2 & 3 & 0 & 3 & 3 & 1 & 4 & 0 & 4 & 4 & 3 & 2 & 0            \\
\bottomrule
\end{tabular}
\caption{The output for $f_n$, $f(n)$, $g_n$, $g(n)$}
\label{tab:fib-output}
\end{table}

We're interested in deriving the connection between the $f_n$ and $f(n)$. The author notes that this
process is heavily derived from Conrad~\cite{bib:solve-lin-rec-field}. To do so, we'll first generalize
our problem. Suppose our linear recurrence relation is of the form:

\begin{equation}
a_n=c_1a_{n-1}+c_2a_{n-2}+\cdots+c_{d}a_{n-d}, a_i, c_i \in \mathbb{F}
\label{eq:general-linear-recursion}
\end{equation}

where $\mathbb{F}$ is some field and $a_0, a_1, \ldots, a_{d-1} \in \mathbb{F}$ are also given. Then
we're looking for a basis of solutions in a $d$-dimensional vector space over $\mathbb{F}$. It's known
that a solution to the sequence is an exponential of the form $\lambda^n$\cite{bib:solve-lin-rec-field}.
Therefore, we're looking to solve the equation
$\lambda^n=c_1\lambda^{n-1}+c_2\lambda^{n-2}+\cdots+c_d\lambda^{n-d}$. Since $0$ would not contribute to
a basis of solutions, we factor about a $\lambda^{n-d}$ from the equation and we're left with solving:

\begin{equation}
\lambda^d-c_1\lambda^{d-1}-c_2\lambda^{d-2}-\cdots-c_d=0
\label{eq:char-poly}
\end{equation}

The reader can note that a similar method can be used to derive the characteristic polynomial. An linear
operator, denoted $E$, is used in some methods to solve linear relations (see
\cite{bib:successor-explained} for more information). It's defined as such: let $t_n$ be a sequence
defined by a linear recurrence relation with constant coefficients. Then this operator is defined by
$Et_n=t_n+1$ and $E^{j}t_n=t_{n+j}$\cite{bib:gen_cond_rec}. If we rewrite Equation
\ref{eq:general-linear-recursion}, then we'll see that:

\begin{align*}
0
&= a_n-c_1a_{n-1}-c_2a_{n-2}-\cdots-c_{d}a_{n-d} \\
&= E^{d}a_{n-d}-c_1E^{d-1}a_{n-d}-c_2E^{n-d}a_{n-2}-\cdots-c_{d}a_{n-d} \\
&= a_{n-d}(E^d-c_1E^{d-1}-c_2E^{d-2}-\cdots-c_d)
\end{align*}
Substituting $E$ with $\lambda$ gives us the same characteristic polynomial (this will be helpful in the next
section). We use the solutions of Equation~\ref{eq:char-poly} to obtain $r$ solutions $\lambda_1$,
$\lambda_2$, \ldots, $\lambda_r$, where $0<r\le d$. If there are not repeated roots, then our closed-form
solution is of form in Equation~\ref{eq:closed-form-no-repeated-roots}.
\begin{equation}
f_n=\sum_{i=1}^r C_{i}\lambda_j
\label{eq:closed-form-no-repeated-roots}
\end{equation}
Otherwise, we use a proof for Theorem~\ref{thm:repeated-roots} (given and proven in
\cite{bib:solve-lin-rec-field}) to indicate how to handle repeated roots.
\\
\begin{theorem}
Let $a_n = c_1a_{n-1} + c_2a_{n-2} + \cdots + c_{d}a_{n-d}$ be a linear recursion of order $d$ with
$c_i \in K$. Assume $1 - c_1x - c_2x^2 - \cdots - c_{d}x^d$ factors in $K[x]$ over its reciprocal roots - the
$\lambda$ such that $1/\lambda$ is a root - as $(1-\lambda_{1}x)^{e_1} \ldots (1-\lambda_{r}x)^{e_r}$ where
the $\lambda_i$ are distinct and $e_i \ge 1$. A basis for the solutions of the linear recursion in $K$ is
given by the $e_i$ sequences
$\{\lambda_1^n\}, \{\binom{n}{1}\lambda_i^n\}, \{\binom{n}{2}\lambda_1^n\}, \ldots, \{\binom{n}{e_i-1}\lambda_1^n\}$.
\label{thm:repeated-roots}
\end{theorem}
This implies that a general solution to these recurrence relations is:
\begin{equation}
f_n=\sum_{i=1}^r\sum_{j=0}^{m_i-1} C_{i,j}\binom{n}{j}\lambda_j
\label{eq:closed-form-repeated-roots}
\end{equation}

\subsection{Examples and Applications}

Below are some examples demonstrating the theorems mentioned earlier. Interesting facts are also
observed regarding the sequences over various finite fields. Examples~\ref{ex:fib-sol-R} and
\ref{ex:fib-sol-F_5} showcase nice applications of theory mentioned earlier.
\\

\begin{example}
If we're being to asked to solve $f(n)$, then we'll be asked to find the solutions over a 2-dimensional space
in $\mathbb{R}$ satisfying $\lambda^2-\lambda-1=0$. We see that that solutions are
$\phi=\frac{1+\sqrt{5}}{2},\overline{\phi}=\frac{1-\sqrt{5}}{2}$. Therefore, we can conclude that
$f(n)= C_1\phi^n-C_1\overline{\phi}^n$ where $\phi=\frac{1+\sqrt{5}}{2}$ and
$\overline{\phi}=\frac{1-\sqrt{5}}{2}$. Solving for the initial conditions get us that
$C_1=\frac{1}{\sqrt{5}}$ and $C_2=-\frac{1}{\sqrt{5}}$.
\label{ex:fib-sol-R}
\end{example}

However, the math turns out quite different under different fields as we see in Example
\ref{ex:fib-sol-F_5}.
\\

\begin{example}
If we're being to asked to solve $g(n)$, then we'll be asked to find the solutions over a 2-dimensional space
in $\mathbb{F}_5$ satisfying $\lambda^2-\lambda-1=0$ which is equivalent to
$\lambda^2+4\lambda+4=(\lambda+2)^2=(\lambda-3)^2=0$. Therefore, $3$ is a solution with multiplicity 2.
Therefore, we use Equation~\ref{eq:closed-form-repeated-roots} to conclude that $f(n)= C_1 3^n-C_2n 3^n$.
Solving for the same initial conditions as we have for $f(n)$, we get that $C_1=0$ and $C_2=2$. Therefore,
$g(n)=2n3^n$.
\label{ex:fib-sol-F_5}
\end{example}

The reader can find some sequence outputs in Table~\ref{tab:fib-out} and in Figures~\ref{fig:fib_F2}
\ref{fig:fib_F3}~\ref{fig:fib_F5} and~\ref{fig:fib_F7} below.

\begin{table}[!ht]
\begin{tabular}{lllllllllllllllllllll}
\toprule
Term \#: & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 \\
\midrule
Field=2: & 0 & 1 & 1 & 0 & 1 & 1 & 0 & 1 & 1 & 0 & 1  & 1  & 0  & 1  & 1  & 0  & 1  & 1  & 0  & 1  \\
Field=3: & 0 & 1 & 1 & 2 & 0 & 2 & 2 & 1 & 0 & 1 & 1  & 2  & 0  & 2  & 2  & 1  & 0  & 1  & 1  & 2  \\
Field=5: & 0 & 1 & 1 & 2 & 3 & 0 & 3 & 3 & 1 & 4 & 0  & 4  & 4  & 3  & 2  & 0  & 2  & 2  & 4  & 1  \\
Field=7: & 0 & 1 & 1 & 2 & 3 & 5 & 1 & 6 & 0 & 6 & 6  & 5  & 4  & 2  & 6  & 1  & 0  & 1  & 1  & 2  \\
\bottomrule
\end{tabular}
\caption{Fibonacci sequence output for various finite fields}
\label{tab:fib-out}
\end{table}

\begin{figure}[!ht]
  \centering
  \includegraphics[width=\textwidth]{images/fib_field2.png}
  \caption{Sequence for Fibonacci in $\mathbb{F}_2$ with period 3}
  \label{fig:fib_F2}
\end{figure}
\begin{figure}[H]
  \centering
  \includegraphics[width=\textwidth]{images/fib_field3.png}
  \caption{Sequence for Fibonacci in $\mathbb{F}_3$ with period 8}
  \label{fig:fib_F3}
\end{figure}
\begin{figure}[!ht]
  \centering
  \includegraphics[width=\textwidth]{images/fib_field5.png}
  \caption{Sequence for Fibonacci in $\mathbb{F}_5$ with period 20}
  \label{fig:fib_F5}
\end{figure}
\begin{figure}[!ht]
  \centering
  \includegraphics[width=\textwidth]{images/fib_field7.png}
  \caption{Sequence for Fibonacci in $\mathbb{F}_7$ with period 16}
  \label{fig:fib_F7}
\end{figure}

If the reader turns their attention to Figures~\ref{fig:fib_F2} and~\ref{fig:fib_F5}, they'll notice the
pattern that appears every 3 and 20 terms, respectively. These pattern are not a coincidence and are
proven in the next example.
\\

\begin{example}
Looking at $f_n=f_{n-1}+f_{n-2}$ over $\mathbb{F}_2$, we'll see that
$f_{n+3}=f_{n+2}+f_{n+1}=(f_{n+1}+f_{n})+f_{n+1}=f_{n}$.

Recall that $g(n)=2n3^n$ is the closed form solution for the Fibonacci sequence over $\mathbb{F}_5$.
Then computing $g(n+20)$ we get:

\begin{align*}
g(n+20)
&=2(n+20)3^{n+20} \\
&=2(n+20)3^n3^{20} \\
&=2n(3^n)(3^{20})+2(20)(3^n)(3^{20}) \\
&=2n(3^n)(3^{4^{5}})+2(20)(3^n)(3^{4^{5}}) \\
\end{align*}

However, the $ord(3)=4$, so $3^{4^{5}}=1$, and so this simplifies to $2n3^n$.
\label{ex:period_fib_F5}
\end{example}

The author notes that these were ad-hoc approaches to verifying the period. However, the reader can note
that having a closed-form solution was helpful in verifying a solution. Though we find out in the next
subsection that a closed-form solution cannot always be found.

\subsection{Irreducibility of the Characteristic Polynomial}

The characteristic polynomial for the Fibonacci sequence was able to be factored over $\mathbb{F}_5$.
However, this need not always be the case. A simple explanation is that a problem arises when your roots
to the characteristic equation are not in your field. We see this happens in Example
\ref{ex:cubic-irred}.
\\

\begin{example}
If we're being to asked to solve $h(n)=h(n-3)$ over $\mathbb{F}_5$ where $h(0)=0$, $h(1)=1$, and $h(2)=2$,
then we'll be asked to find the solutions over a 3-dimensional space in $\mathbb{F}_5$ satisfying
$\lambda^{3}-1=(\lambda-1)(\lambda^2+\lambda+1)=0$. But under the $\mathbb{F}_5$, the $h_1(x)=x^2+x+1$ is
irreducible since it has $\deg(h)=2$ and $h(x)\ne 0, \forall x\in \mathbb{F}_5$.
\label{ex:cubic-irred}
\end{example}

Moreover, it can be calculated that $x^2-x-1$ is irreducible over $\mathbb{F}_2$, $\mathbb{F}_3$,
$\mathbb{F}_7$ as well. To the best of the author's knowledge, little is known between the connection
between the irreducible factors of a characteristic polynomial and the solutions to the basis. Having
knowledge that these polynomials must factor in some field extension seems helpful. However,
interpreting these problems in such a way is outside the scope of this paper.

In conclusion, it's clear that there is much more to learn about defining recursions over a finite
field. Understanding their patterns is important, as well. However, understanding how irreducibility
plays a role in this scenario should be a priority to understanding this problems.

\section{Solving a Conditional Linear Recurrence}

Up until now, the topic has been about finding a closed-form solution for a linear recurrence relation.
However a method exists for solving conditional recurrences -- though it's a little more complex. The
author would like to note that this process is taken directly from~\cite{bib:gen_cond_rec} as it
conveniently explains the process in perfect detail. The reader can note that this process can be
extended to any field as the operations are not necessarily limited to $\mathbb{R}$ or $\mathbb{C}$.

We start by defining a general conditional recurrence relation. Let $\{a_{i,j}\}$ be real numbers for
$0 \le i \le r-1$ and $1 \le j \le s$, and define a sequence ${q_n}$ with given terms $q_i$,
$0 \le i \le s-1$, and for $n \ge s$:

\begin{align*}
q_n=
\begin{cases}
a_{0,1}q_{n-1}+a_{0,2}q_{n-2}+\cdots+a_{0,s}q_{n-s}       & \equiv 0   \mod r \\
a_{1,1}q_{n-1}+a_{1,2}q_{n-2}+\cdots+a_{1,s}q_{n-s}       & \equiv 1   \mod r \\
\vdots                                                                        \\
a_{r-1,1}q_{n-1}+a_{r-1,2}q_{n-2}+\cdots+a_{r-1,s}q_{n-s} & \equiv r-1 \mod r \\
\end{cases}
\end{align*}

We call such a sequence a \textit{general conditional recurrence sequence} with \textit{associated
coefficient matrix}.

\begin{align*}
A=
\begin{bmatrix}
    a_{0,1}   & a_{0,2}   & \cdots  & a_{0,n} \\
    a_{1,1}   & a_{1,2}   & \cdots  & a_{1,n} \\
    \vdots    & \vdots    & \ddots & \vdots  \\
    a_{r-1,1} & a_{r-1,2} & \cdots  & a_{r-1,n}
\end{bmatrix}
\end{align*}

We note that sequence [A068911] is an example of general conditional recurrence sequence where $r=s=2$
and $(a_{0,1},a_{0,2},a_{1,1},a_{1,2})=(2,0,1,1)$. For the sake of this simply understanding the
material, we'll explain the process for when we're given ${a_{i,j}}$ $r \le 3$ and $s \le 3$. Therefore,
we're interested in solving the sequence $q_n$ with initial values $q_0$, $q_1$, $q_2$ for when
$n \ge 3$ by:

\begin{align*}
q_n=
\begin{cases}
a_{0,1}q_{n-1}+a_{0,2}q_{n-2}+a_{0,3}q_{n-3} & \equiv 0 \mod 3 \\
a_{1,1}q_{n-1}+a_{1,2}q_{n-2}+a_{1,3}q_{n-3} & \equiv 1 \mod 3 \\
a_{2,1}q_{n-1}+a_{2,2}q_{n-2}+a_{2,3}q_{n-3} & \equiv 2 \mod 3 \\
\end{cases}
\end{align*}

Our goal is to the sequence as different subsequences that are related by the successor operator, and
then to solve a homogeneous system. To do this, we bring $q_n$ to the other side of the equation, we can
rewrite this as:

\begin{align*}
0=
\begin{cases}
-a_{0,0}q_{n}+a_{0,1}q_{n-1}+a_{0,2}q_{n-2}+a_{0,3}q_{n-3} & \equiv 0 \mod 3 \\
-a_{1,0}q_{n}+a_{1,1}q_{n-1}+a_{1,2}q_{n-2}+a_{1,3}q_{n-3} & \equiv 1 \mod 3 \\
-a_{2,0}q_{n}+a_{2,1}q_{n-1}+a_{2,2}q_{n-2}+a_{2,3}q_{n-3} & \equiv 2 \mod 3 \\
\end{cases}
\end{align*}
We can rewrite these conditional statements by re-indexing their terms. This gives us:
\begin{align*}
-a_{0,0}q_{(n+1)3+0}+a_{0,1}q_{(n+1)3-1}
+a_{0,2}q_{(n+1)3-2}+a_{0,3}q_{(n+1)3-3} = 0 \\
-a_{1,0}q_{(n+1)3+1}+a_{1,1}q_{(n+1)3+0}
+a_{1,2}q_{(n+1)3-1}+a_{1,3}q_{(n+1)3-2} = 0 \\
-a_{2,0}q_{(n+1)3+2}+a_{2,1}q_{(n+1)3+1}
+a_{2,2}q_{(n+1)3-0}+a_{2,3}q_{(n+1)3-1} = 0
\end{align*}

Now, let $Q_n^{(t)}=q_{n}r+t$ for each $0 \le t \le r-1$. We can rewrite the example as:
\begin{align*}
-a_{0,0}Q_{n+1}^{(0)}+a_{0,1}Q_{n}^{(2)}
+a_{0,2}Q_{n}^{(1)}+a_{0,3}Q_{n}^{(0)} = 0 \\
-a_{1,0}Q_{n+1}^{(1)}+a_{1,1}Q_{n+1}^{(0)}
+a_{1,2}Q_{n}^{(2)}+a_{1,3}Q_{n}^{(1)} = 0 \\
-a_{2,0}Q_{n+1}^{(2)}+a_{2,1}Q_{n+1}^{(1)}
+a_{2,2}Q_{n+1}^{(0)}+a_{2,3}Q_{n}^{(2)} = 0
\end{align*}
Therefore, we now have 3 subsequences given by:
\begin{align*}
\left\{Q_n^{(0)}\right\}_{n=0}^{\infty}
=\left\{q_{3n}\right\}_{n=0}^{\infty}   \\
\left\{Q_n^{(1)}\right\}_{n=0}^{\infty}
=\left\{q_{3n+1}\right\}_{n=0}^{\infty} \\
\left\{Q_n^{(2)}\right\}_{n=0}^{\infty}
=\left\{q_{3n+2}\right\}_{n=0}^{\infty}
\end{align*}

which are called the $3$ decimation sequences of $\{q_{n}r+t\}$. At this point, we apply the successor
operator for the sequence $\{Q_n^{(t)}\}_{n=0}^{\infty}$ since $E^{\mu}Q_{n}^{(t)}=Q_{n+\mu}^{(t)}$ for
any $0 \le \mu \le k$, $0 \le t \le r-1$, we rewrite equation as:

\begin{align*}
-a_{0,0}EQ_{n}^{(0)}+a_{0,1}Q_{n}^{(2)}
+a_{0,2}Q_{n}^{(1)}+a_{0,3}Q_{n}^{(0)} = 0 \\
-a_{1,0}EQ_{n}^{(1)}+a_{1,1}EQ_{n}^{(0)}
+a_{1,2}Q_{n}^{(2)}+a_{1,3}Q_{n}^{(1)} = 0 \\
-a_{2,0}EQ_{n}^{(2)}+a_{2,1}EQ_{n}^{(1)}
+a_{2,2}EQ_{n}^{(0)}+a_{2,3}Q_{n}^{(2)} = 0
\end{align*}

However, this can be written as a homogeneous system:

\begin{align*}
\begin{bmatrix}
    a_{0,3}-a_{0,0}E & a_{0,2}          & a_{0,1}          \\
    a_{1,1}E         & a_{1,3}-a_{1,0}E & a_{1,2}          \\
    a_{2,2}          & a_{2,1}E         & a_{2,3}-a_{2,0}E \\
\end{bmatrix}
\begin{bmatrix}
    Q_{n}^{(0)} \\
    Q_{n}^{(1)} \\
    Q_{n}^{(2)}
\end{bmatrix}
=
\begin{bmatrix}
    0 \\
    0 \\
    0
\end{bmatrix}
\end{align*}
This is of the form:
$
[P_{ij}(E)]_{3 \times 3}
\begin{bmatrix}
    Q_{n}^{(0)} \\
    Q_{n}^{(1)} \\
    Q_{n}^{(2)}
\end{bmatrix}
=0
$

At this point, we use a Theorem 2 from~\cite{bib:gen_cond_rec}. We'll declare it below.
\\

\begin{theorem}
If $D=D(E)=detP$, then $\{q_n\}$  satisfies the recurrence relation whose characteristic polynomial is
$D(\lambda^r)$
\label{thm:det-is-char-poly-dxr}
\end{theorem}

Therefore:

\begin{align*}
D
&=detP \\
&=E^3 \\
&- (a_{0,1}a_{1,1}a_{2,1}+a_{0,1}a_{2,2}+a_{0,2}a_{1,1}+a_{1,2}a_{2,1}+a_{0,3}+a_{1,3}+a_{2,3})E^2 \\
&+ (a_{0,3}a_{1,2}a_{2,1}+a_{0,1}a_{1,3}a_{2,2}+a_{0,2}a_{1,1}a_{2,3}+a_{1,3}a_{2,3}+a_{0,3}a_{2,3}+a_{0,3}a_{1,3}-a_{0,2}a_{1,2}a_{2,2})E \\
&-(a_{0,3}a_{1,2}a_{2,1})
\end{align*}

Since $r=3$, by Theorem~\ref{thm:det-is-char-poly-dxr}, we get that when the determinant equals zero,
substituting $\lambda^3$ in for $E$ gives us the characteristic polynomial:

\begin{align*}
\lambda^9
&= (a_{0,1}a_{1,1}a_{2,1}+a_{0,1}a_{2,2}+a_{0,2}a_{1,1}+a_{1,2}a_{2,1}+a_{0,3}+a_{1,3}+a_{2,3})\lambda^6 \\
&- (a_{0,3}a_{1,2}a_{2,1}+a_{0,1}a_{1,3}a_{2,2}+a_{0,2}a_{1,1}a_{2,3}+a_{1,3}a_{2,3}+a_{0,3}a_{2,3}+a_{0,3}a_{1,3}-a_{0,2}a_{1,2}a_{2,2})\lambda^3 \\
&+(a_{0,3}a_{1,2}a_{2,1})
\end{align*}

\subsection{Examples and Observations}

\begin{example}

Suppose $q_n$ is defined like so:
\begin{align*}
q_n=
\begin{cases}
1q_{n-1}+1q_{n-2}+1q_{n-3} & \equiv 0 \mod 3 \\
1q_{n-1}+1q_{n-2}+0q_{n-3} & \equiv 1 \mod 3 \\
2q_{n-1}+1q_{n-2}+0q_{n-3} & \equiv 2 \mod 3 \\
\end{cases}
\end{align*}
Then we follow the previous steps to obtain that:
\begin{align*}
P=
\begin{bmatrix}
    1-E & 1  & 1  \\
    E   & -E & 1  \\
    E   & 2E & -E \\
\end{bmatrix}
\end{align*}
Calculating the determinant, we find that:
\begin{align*}
D=(-E)(E^2-7E+1)
\end{align*}
Substituting $E=\lambda^3$ implies we need to solve $p(\lambda)=\lambda^6-7\lambda^3+1$ -- a degree 6
polynomial whose solutions are our basis for the 6-dimensional vector space that satisfies both
$\{q_n\}$ and ${p_n}$ where $p_n=7p_{n-3}-p_{n-6}$.
\end{example}

The next example showcases the characteristic polynomial can be factored over finite field
$\mathbb{F}_2$ and $\mathbb{F}_4$, but no other tested field. However, a precaution needs to be taken
since the initial conditions need to be altered to satisfy the newly obtained linear recursion.
\\
\begin{example}
Suppose $q_n$ is defined like so:
\begin{align*}
q_n=
\begin{cases}
2q_{n-1}+0q_{n-2} & \equiv 0 \mod 2 \\
1q_{n-1}+1q_{n-2} & \equiv 1 \mod 2 \\
\end{cases}
\end{align*}
Then, once again, we follow the previous steps to obtain that:
\begin{align*}
P=
\begin{bmatrix}
   -E &    2 \\
    E & -E+1 \\
\end{bmatrix}
\end{align*}
Calculating the determinant, we find that:
\begin{align*}
D=(-E)(-E+1)-(E)(2)=\cdots=E(E-3)
\end{align*}
Substituting $E=\lambda^2$ implies we need to solve $p(\lambda)=\lambda^2-3$ -- a degree 2 polynomial
whose solutions are our basis for the 2-dimensional vector space that satisfies both $\{q_n\}$ and
${p_n}$ where $p_n=3p_{n-2}$. In this case the closed form solution is
$q_n=\left(\frac{2+\sqrt{3}}{3}\right)(\sqrt{3})^n+\frac{2+\sqrt{3}}{3}(-\sqrt{3})^n$. However, for this
to hold, the $q_0$ must be set to $q_0=\frac{4}{3}$ since $q_2={4}=3q_0$.

Similarly, the reader can note that if factoring $\lambda^2-3$ over $\mathbb{F}_2$ and $\mathbb{F}_4$ is
possible. Similarly, since the the sequence outputs all zeros, and so the initial conditions needed to
be modified as well.

It's output can be seen in the table below.

\begin{table}[ht]
\centering
\begin{tabular}{lllllllllllllllll}
\toprule
Term \#:  & 0 & 1 & 2 & 3 & 4  & 5  & 6  & 7  & 8   & 9   & 10  & 11  & 12  & 13   & 14   & 15                \\
\midrule
Field=$\mathbb{R}$:  & 1 & 2 & 4 & 6 & 12 & 18 & 36 & 54 & 108 & 162 & 324 & 486 & 972 & 1458 & 2916 & 4374   \\
Field=$\mathbb{F}_2$:  & 1 & 0 & 0 & 0 & 0  & 0  & 0  & 0  & 0   & 0   & 0   & 0   & 0   & 0    & 0    & 0    \\
Field=$\mathbb{F}_3$:  & 1 & 2 & 1 & 0 & 0  & 0  & 0  & 0  & 0   & 0   & 0   & 0   & 0   & 0    & 0    & 0    \\
Field=$\mathbb{F}_4$:  & 1 & 0 & 0 & 0 & 0  & 0  & 0  & 0  & 0   & 0   & 0   & 0   & 0   & 0    & 0    & 0    \\
Field=$\mathbb{F}_5$:  & 1 & 2 & 4 & 1 & 2  & 3  & 1  & 4  & 3   & 2   & 4   & 1   & 2   & 3    & 1    & 4    \\
Field=$\mathbb{F}_7$:  & 1 & 2 & 4 & 6 & 5  & 4  & 1  & 5  & 3   & 1   & 2   & 3   & 6   & 2    & 4    & 6    \\
Field=$\mathbb{F}_8$:  & 1 & 0 & 0 & 0 & 0  & 0  & 0  & 0  & 0   & 0   & 0   & 0   & 0   & 0    & 0    & 0    \\
Field=$\mathbb{F}_9$:  & 1 & 2 & 1 & 0 & 0  & 0  & 0  & 0  & 0   & 0   & 0   & 0   & 0   & 0    & 0    & 0    \\
Field=$\mathbb{F}_{11}$: & 1 & 2 & 4 & 6 & 1  & 7  & 3  & 10 & 9   & 8   & 5   & 2   & 4   & 6    & 1    & 7  \\
Field=$\mathbb{F}_{13}$: & 1 & 2 & 4 & 6 & 12 & 5  & 10 & 2  & 4   & 6   & 12  & 5   & 10  & 2    & 4    & 6  \\
\bottomrule
\end{tabular}
\caption{Output of $q_n$ of type (2,0,1,1) over various fields}
\label{my-label}
\end{table}

However, over other tested fields, no closed form solution can be found since $\lambda^2-3$ is irreducible.
\end{example}

\section{Conclusion}

Therefore, it can be concluded that there there are many applications of finite fields to the study of linear
recurrences. From the study of periods to the more important study of irreducibles in characteristic
polynomials, for conditional or unconditional recurrences, these will play a role in understanding recurrences
altogether.

\begin{thebibliography}{9}

\bibitem{bib:solve-lin-rec-field}
  K. Conrad,
  \emph{Solving Linear Recursion over all Fields},
  Expository Paper, \textit{http://www.math.uconn.edu/~kconrad/blurbs/linmultialg/linearrecursion.pdf}

\bibitem{bib:successor-explained}
  D. Detemple, W. Webb,
  \emph{Combinatorial Reasoning},
  (Chapter 5.2.1 - 5.2.2),
  2014. Online at \texttt{https://goo.gl/E7VT7m} %used a URL shortener to eliminate a bug

\bibitem{bib:gen_cond_rec}
  D. Panario, M. Sahin, Q. Wang, W. Webb,
  \emph{General conditional recurrences},
  Applied Mathematics and Computation 243
  (2014) 220-231.

\bibitem{bib:lfsr}
  The University of Sydney
  \emph{Linear Feedback Shift Registers}
  Math3024 Elementary Cryptography and Protocols
  Online at \texttt{http://goo.gl/RMFLh3}

\end{thebibliography}

\end{document}

Extending Conditional Recurrences over Finite Fields/paper.tex


\problemname{Paper Snowflakes}

To make a paper snowflake, you fold a sheet of paper in various places
and then cut some parts out of the folded sheet. When you unfold the sheet,
it can make a very nice pattern. That is, if the folds and cuts are chosen well.

Samantha has recently taken up this hobby but with a ``modern art'' twist.
To get started, she explores folding a strip of paper that is $L$ picometres long (Samantha likes to measure her folds and cuts very precisely).
She places it on the real line with one end at $0$ and the other at $L$. The
left end at point $0$ is affixed to this point, the other endpoint at position $L$
is the {\em loose} endpoint.

She then performs a series of folds. For the first fold, Samantha creases the paper
$f_1$ picometres from the loose end and folds the loose end over this fold.
The loose end is now pointing towards the left.
For the second fold, she then creases the top portion of the paper $f_2$ picometres
from the loose end ($f_2 < f_1$) and folds the top portion of the paper over this point
back to the right over this crease point. The loose end is now pointing towards the right.

She alternates folding back-and-forth this way. At each step, she creases the top portion of the paper $f_i$ picometres from the loose end ($f_i < f_{i-1}$) and folds the loose end over the crease.

She will now cut the paper at $M$ distinct locations, which will split the paper into $M+1$ piles. Each of the piles will have zero or more layers of paper in it. The figure below depicts the folded paper from the first sample input, the cuts (solid lines), and the $x$-locations of where the paper was folded (dashed lines).

What is the total length of paper in each of the $M+1$ piles?

\begin{figure}[h]
\begin{center}
 \includegraphics[width=0.8\textwidth]{cut.pdf}
\end{center}
% \caption{Illustration of the first sample.}
\end{figure}

\section*{Input}
The first line of input consists of three integers $N$ ($1 \leq N \leq 10^5$),
which is the number of folds, $M$ ($1 \leq M \leq 10^5$), which is the number
of cuts, and $L$ ($2 \leq L \leq 10^{18}$), which is the length of the paper
in picometres.

The second line describes the folds. This line contains $N$ integers
$f_1, f_2, \ldots, f_N$, indicating that the $i^\textrm{th}$ fold occurred $f_i$ picometres from the loose end. These values satisfy $1 \leq f_N < f_{N-1} < \cdots < f_1 < L$.

The third line describes the cuts. This line contains $M$ integers
$c_1, c_2, \ldots, c_M$, indicating that the $i^\textrm{th}$ cut is $c_i$ picometres from the affixed point. These values satisfy $-10^{18} \leq c_1 < c_2 < \cdots < c_M \leq 10^{18}$.

\section*{Output}
Output the total length of paper in each of the $M+1$ piles, in order from left to right.


\chapter{Foundations}\label{chap:foundations}

Before diving into the \emph{Cast Calculus} we introduce the foundation, the \emph{Label Dependent Lambda Calculus} (LDLC) and its implementation LDGV.

\section{Label Dependent Lambda Calculus}\label{sec:ldlc}

The LDLC is the foundation of this work. Its main aspect is the gain of additional simplicity in context of session types. The introduction of labels results in decoupled operations when sending and receiving functions, hence being more lightweight regarding its semantics. See \cite{thiemann2019}. However, session types are not of special relevance when introducing casts. For brevity, we will omit the handling of session types, focusing on labels instead.

A list of language constructs is found in figures~\ref{fig:ldlc-expressions}~to~\ref{fig:ldlc-values}. There is support for common functionality like variables, expressions and types,\footnote{
Variable names for expressions have to start with a lowercase letter, e.g. \texttt{\valb x = ()}; for types its an uppercase letter: \texttt{\typeb X : Unit}.} functions and pairs as well as numerical operations and values. In general---as implied by its name---it is based on \emph{Simply Typed Lambda Calculus} (details can be found in most introductory literature, e.g. \cite{pierce2002}). As in many functional languages, there is also the unit type $\Unit$ encompassing its only value ``$()$''.

Another two language concepts are more interesting: First and foremost, the support for labels $\ell$. Labels can have arbitrary names. A mathematical set of distinct labels forms a type. Moreover, there is a recursor over natural numbers $\rec V~M~x.f.N$. This allows for recursively constructing expressions by using base expression $M$ for $n=0$ and otherwise expression $N$ with appropriate substitutions for $x$ and $f$.

\begin{figure}
\begin{align*}
 M,N,P ::=
    & \enspace x \enspace|\enspace
      () \enspace|\enspace
      \ell \enspace|\enspace
      x \in \mathbb{R} \\
    & |\enspace M \circ N & \circ \in \{+,-,\times,\div\} \\
    & |\enspace \case M \{\overline{\ell : N_\ell}^{\ell \in L} \} & \text{label expression matching} \\
    & |\enspace \rec V~M~x.f.N & \mathbb{N}\text{ recursor} \\
    & |\enspace \lambda (x : A).M & \text{abstraction} \\
    & |\enspace M~N & \text{application}\\
    & |\enspace \letb x = M \inb N & \text{bind in $N$}\\
    & |\enspace \letb \langle x, y \rangle = M \inb N & \text{bind pair in $N$} \\
    & |\enspace \langle x = M, N \rangle & \text{pair construction}\\
    & |\enspace \fstb M \enspace|\enspace \sndb M & \text{pair elimination}
\end{align*}
\caption{Expressions in LDLC}
\label{fig:ldlc-expressions}
\end{figure}

\begin{figure}
\begin{align*}
 A, B ::=
    & \enspace t \enspace|\enspace
      \Unit
    \\ &  |\enspace \Int \enspace|\enspace
      \Nat \enspace|\enspace
      \Double \\
    & |\enspace \{ \ell_1, \dots, \ell_n \} & \text{finite label set} \\
    & |\enspace \Sigma(x:A)B & \text{pair type} \\
    & |\enspace \Pi(x:A)B & \text{function type} \\
    & |\enspace \case M \{\overline{\ell : A_\ell}^{\ell \in L} \} & \text{label type matching} \\
    & |\enspace \rec V~A~t.B & \text{recursor type}
\end{align*}
\caption{Types in LDLC}
\label{fig:ldlc-types}
\end{figure}

\begin{figure}
\begin{align*}
    V, W ::=
    & \enspace () \enspace|\enspace
      \ell \enspace|\enspace
      x \in \mathbb{R} \enspace
     |\enspace \langle V, W \rangle
\end{align*}
\caption{Values in LDLC}
\label{fig:ldlc-values}
\end{figure}

\subsection{Labels and Label Sets}

The main feature of LDLC is its use of labels. A label evaluates to itself, thus it forms its own value. But what about its type? Any finite non-empty set of labels $L$ is a type. For instance, it is sufficient to declare a boolean type as seen in equation~\ref{eqn:bool}.

The minimal type is the singleton type of its corresponding label. For label $\ell$ this is $\{\ell\}$. Apart from that there might be a bottom type $\bot$ which corresponds to a hypothetical empty label set. Neither type $\bot$ nor the empty label set are valid types in LDLC.

Predominantly, labels appear in context of \case terms. These may occur as expressions or as types and act as eliminators for labels. They provide a mapping from each label of the corresponding label set to an expression or a type. Hence the name of the calculus, \emph{Label Dependent} Lambda Calculus. The type of an expression may depend on a label value.

\subsection{Recursor over Natural Numbers}\label{sec:ldgv-recursor}

In addition to label dependency, there is another construct used for modeling dependency on natural numbers: $\rec V~M~x.f.N$

Value $V$ must be a natural number value which can also be written recursively using the constructors $Z$ (for zero) and $S(V)$ for the successor of $V$. An encoding for a natural number is given by $\overline{n} = S(\dots S(Z))$. When evaluating a recursor, there is a case differentiation by value $V$.

If $V=Z$ the whole expression is reduced to $M$, discarding its latter term. Otherwise, for $V=S(V')$, the \rec expression is reduced to expression $N$ with the following two substitutions: variable $x$ in $N$ is substituted by $V'$, the predecessor of $S(V')$; variable $f$ by $\rec V'~M~x.f.N$, the result of the ``previous'' evaluation of the recursor.

\begin{figure}
 \begin{align*}
 \rec Z~&M~x.f.N \longrightarrow M \\
 \rec S(V)~&M~x.f.N \longrightarrow N [V/x] [\rec V~M~x.f.N/f] \\
 \rec Z~&A~t.B \longrightarrow A \\
 \rec S(V)~&A~t.B \longrightarrow B [\rec V~A~t.B/t]
\end{align*}
\caption{Nat. recursor expression reduction and type reduction}
\label{fig:ldlc-rec-exp}
\end{figure}

On the type level it is similar when evaluating a recursor type $\rec V~A~t.B$. For $V=Z$, the resulting type is simply $A$. As for $V=S(V')$, the resulting type is given by $B$ after substituting type identifier $t$ in $B$ with $\rec V'~A~t.B$. Both reductions are concisely listed in figure~\ref{fig:ldlc-rec-exp}.

\subsection{Subtyping}

Without subtyping, a type system lacks flexibility. Assuming a lambda expression $\lambda ( x: \Int ).M$, what will happen when applying an expression of type \textbf{Nat}? Obviously, there is a difference between natural numbers and integers. But at the same time, every natural number is also an integer. ($\mathbb{N} \subset \mathbb{Z}$) By formulating consistent rules---not necessarily involving subset relations---a type system will accept a wider range of types. Especially in object-oriented languages supporting inheritance this is practically a necessary feature.\footnote{A common example is class \emph{Dog} inheriting from class \emph{Animal}; then methods accepting arguments of type \emph{Animal} will also accept type \emph{Dog}.} Subtyping for dependent types entails some peculiarities that were  studied in various papers during the last three decades, e.g. by \cite{aspinall2001}.

In figure~\ref{fig:ldgv-subtyping} we give an excerpt of relevant subtyping rules of LDLC. Handling of function types (\textsc{A-Sub-Pi}) and pair types (\textsc{A-Sub-Sigma}) is of special relevance since they are composite types, thus they need specification on how to recursively apply subtyping to their component types. For CCLDLC these rules gain additional relevance since they are necessary not only for type checking but now for type casts during runtime, too.

Since a label type is a set of labels we can use set comparisons for subtyping. If one label type $L$ is a subset of another label type $L'$, then $L$ is a subtype of $L'$. Thus, there is no $L$ that is a subtype of the empty set $\emptyset$ and equivalently of bottom type $\bot$. Subtyping in LDLC is closed under transitivity.

\begin{figure}
\begin{mathpar}
\inferrule[A-Sub-Unit]
  {\Gamma \Vdash \Unit \leq \Unit}{}
\and
\inferrule[A-Sub-Label]
  {L \subseteq L'}{\Gamma \Vdash L \leq L'}
\\
\inferrule[A-Sub-Pi]
  {\Gamma \Vdash A' \leq A \and \Gamma,x:A' \Vdash B \leq B'}{\Gamma \Vdash \Pi(x:A)B \leq \Pi(x:A')B'}
\\
\inferrule[A-Sub-Sigma]
  {\Gamma \Vdash A \leq A' \and \Gamma, x:A \Vdash B \leq B'}
  {\Gamma \Vdash \Sigma(x:A)B \leq \Sigma(x:A')B'}
\\
\Gamma ::= \cdot \enspace | \enspace \Gamma, x:A
\end{mathpar}
\caption[Subtyping rules in LDGV (excerpt)]{Subtyping rules in LDGV (excerpt) w.\,r.\,t. type environment $\Gamma$}
\label{fig:ldgv-subtyping}
\end{figure}

\section{LDGV Interpreter}

LDGV stands for ``Label Dependency'' and ``Gay \& Vasconcelos'', the authors of multiple papers about Session Types, e.\,g. \cite{gayvasconcelos2010}. In this work's context, it is the name of an interpreter for LDLC and its extension CCLDLC. It is written in the Haskell programming language.

Its syntax is similar to the calculus from the previous section. We give an excerpt in listing~\ref{lst:ldgv-expressions}. In general, keywords and structure are identical safe for labels. To uniquely identify and tokenize a label it needs to be a combination of alphanumeric characters, prefixed by an apostrophe. Furthermore, as opposed to the underlying LDLC, there is basic string support. A combination of characters enclosed by quotation marks \texttt{"} is read as string expression.

\begin{lstlisting}[float,language=ldgv,
  caption={LDGV: Expressions (excerpt) with expressions \texttt{M,N,P}, \\ variable \texttt{x} and type \texttt{A}},
  label=lst:ldgv-expressions]
()          -- unit
M + N       -- and other arithmetics
10          -- numbers
"foo bar"   -- strings
x           -- variables
'foo        -- labels
case M {'foo: N, 'bar: P}
fn(x: A) M  -- lambda abstraction
<x = M, N>  -- pair
\end{lstlisting}

The syntax for types is given in listing~\ref{lst:ldgv-types}. Writing out function and pair types differs from the calculus' notation. Function types of multiple arguments are built by recursion, e.g. \texttt{(x:A) -> (y:B) -> C}.

\begin{lstlisting}[float,language=ldgv,
  caption={LDGV: Types (excerpt) with expression \texttt{M}, variable \texttt{x}, \\ type identifier \texttt{T} and types \texttt{A,B}},
  label=lst:ldgv-types]
Unit
Int
Nat
Double
String
T             -- type identifier
{'foo, 'bar}  -- label type
case M {'foo: A, 'bar: B}
(x: A) -> B   -- function type
[x: A, B]     -- pair type
\end{lstlisting}

For an actual program there need to be statements, especially declarations. They create the global environment, binding expressions to variables and types to type identifiers.\footnote{For type identifiers, the programmer has to supply a \emph{kind}. For brevity, we omit the introduction of kinds, generally assuming kind \texttt{\textasciitilde un} in declarations.} When running the interpreter on a given program, it outputs the evaluation result of the expression bound to variable \texttt{main}. Furthermore, there are type assertions. The full list of statements is given in listing~\ref{lst:ldgv-statements}.

\begin{lstlisting}[float,language=ldgv,
  caption={LDGV: Statements with expression \texttt{M} and types \texttt{A,B}},
  label=lst:ldgv-statements]
val x = M         -- variable declaration
val x : A         -- variable signature declaration
type T : ~un = A  -- type declaration
A <: B            -- subtype assertion
A =: B            -- type equivalence assertion
\end{lstlisting}

Translating equation~\ref{eqn:ldlc} into a valid LDGV program results in the sample program in figure~\ref{lst:ldgv-program}. The variable's type signatures are optional.
Variable \texttt{main} gives an example application and does fully evaluate to value \texttt{'F} (representing boolean \emph{False}).

\begin{lstlisting}[float,language=ldgv,numbers=left,
  caption=LDGV: Sample program,
  label=lst:ldgv-program]
type Bool : ~un = {'T, 'F}

val not : (a: Bool) -> Bool
val not   (a: Bool) = (case a {'T: 'F, 'F: 'T})

val f : (x: Bool)
         -> (y: case x {'T: Int, 'F: Bool})
             -> case x {'T: Int, 'F: Bool}
val f = fn(x: Bool)
          fn(y: case x {'T: Int, 'F: Bool})
            case x {'T: 17+y, 'F: not y}

val main = f 'F 'T
\end{lstlisting}


\mychapter{17}{Lesson 17} %181123

\section{Construction of a \textsc{cca}-secure \textsc{pke}}

This section exposes a construction of a \textsc{cca}-secure \textsc{pke} scheme, using hash-proof systems, membership-hardness, and the $t$-universality property.

Let $\Pi_1, \Pi_2$ be two distinct hash-proof systems for some \textsc{np} language $L$ and the range of $Prove_2$ supports labels ($L'=L||\binary^\ell$).

Construct the \textsc{cca} scheme as follows: $\Pi := (\mathcal{KG}en, Enc, Dec)$
\begin{itemize}
    \item $ (\overbrace{(\omega_1,\omega_2)}^{pk}, \overbrace{(\tau_1,\tau_2)}^{sk}) \pickUAR \mathcal{KG}en(1^\lambda)\;,\;\;\;\;(\omega_1, \tau_1) \pickUAR Setup_1(1^\lambda), (\omega_2, \tau_2) \pickUAR Setup_2(1^\lambda)$
    \item Encryption routine: $Enc((\omega_1, \omega_2), m)$
    \begin{itemize}
        \item $ (y, x) \pickUAR Sample_1(1^\lambda)$
        \item $ \pi_1 \pickUAR Prove_1(\omega_1, y, x)$
        \item $ l := \pi_1 \cdot m$
        \item $ \pi_2 \pickUAR Prove_2(\omega_2, (y, l), x)$
        \item $ c := (c_1, c_2) = ((y, l), \pi_2)$
    \end{itemize}
    \item Decryption routine: $Dec((\tau_1, \tau_2), (c_1, c_2))$
    \begin{itemize}
        \item $\hat{\pi}_2 = Verify_2(\tau_2, c_1))$
        \item $\textsc{if } \hat{\pi}_2 \neq c_2 \textsc{ then output false}$
        \item Recall: $c_1 = (y, l)$
        \item $\hat{\pi}_1 = Verify_1(\tau_1, y)$
        \item $\textsc{output } l \cdot \hat{\pi}_1^{-1}$
    \end{itemize}
\end{itemize}

Correctness (assume $\hat{\pi}_i = \pi_i \forall i$):
\begin{align*}
    \hat{m} &= Dec(sk, Enc(pk, m)) \\
    &= Dec((\tau_1, \tau_2), Enc((\omega_1, \omega_2), m)) \\
    &= Dec((\tau_1, \tau_2), ((y, l), \pi_2)) \\
    &= l \cdot \hat{\pi}_1^{-1} \\
    &= \pi_1 \cdot m \cdot \hat{\pi}_1^{-1} \\
    &= m
\end{align*}

Some additional notes (may be incorrect):
\begin{itemize}
    \item The message space of the second prover is the range of the first prover.
    \item The message space of the first prover is a multiplicative group
    \item The message space of the second prover is a polylogarithmic language in ($\lambda$)
\end{itemize}

\begin{theorem}
    Assuming $\pi_1$ is 1-universal, $\pi_2$ is 2-universal and $L$ is a mem\-bership-hard language; then the above scheme is \textsc{cca}-secure.
\end{theorem}

\begin{proof}
    Five different games will be defined, from $\cryptog{0}$ up to $\cryptog{4}$; the first game will be an analogous formalization of how the above \textsc{pke} scheme works. It shall be proven that, for arbitrarily fixed $b$ in $\binary$:
    \begin{align*}
        \cryptog{0}(\lambda, b) &\equiv \cryptog{1}(\lambda, b)         \\
                                &\compindist \cryptog{2}(\lambda, b)    \\
                                &\statindist \cryptog{3}(\lambda, b)    \\
                                &\equiv \cryptog{4}(\lambda, b)
    \end{align*}
    and finally that $\cryptog{4}(\lambda, 0) = \cryptog{4}(\lambda, 1)$, therefore concluding that $\cryptog{0}(\lambda, 0) \compindist \cryptog{0}(\lambda, 1)$, and proving this scheme is \textsc{cca}-secure.

    \todo{Non sono per niente sicuro riguardo all'origine di $x$ ed $y$, né tantomeno dove sia definito il sampler per essi}

    The games are defined as follows:

    % Game 0
    \begin{cryptogame}{pkecca0}{Original \textsc{cca} game}{pke-cca}

        % Challenger generates key pair and publishes the public key
        \receive{$((\omega_1, \omega_2), (\tau_1, \tau_2)) \pickUAR \mathcal{S}etup(1^\lambda)$}
        {$(\omega_1, \omega_2)$}
        {}

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary asks for a challenge
        \send{}{$m_0, m_1$}{}
        %Challenger replies with an encrypted message
        \receive{\shortstack[l]{
            $(x, y) \pickUAR Sample_1$ \\
            $\pi_1 \pickUAR Prove_1(\omega_1, y, x)$ \\
            $b \pickUAR \binary$ \\
            $\pi_2 \pickUAR Prove_2(\omega_2, (y, (\pi_1 \cdot m_b)), x)$ }}
        {$c = ((y, (\pi_1 \cdot m_b)), \pi_2)$}
        {}

        \cseqdelay

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary guesses which message has been encrypted
        \send{}{$b'$}{\textsc{Output} 1 \textsc{iff} $b=b'$}

    \end{cryptogame}

    % Game 1: Use verifiers instead of provers
    \begin{cryptogame}{pkecca1}{Use verifiers}{1}

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary asks for a challenge
        \send{}{$m_0, m_1$}{}
        %Challenger replies with an encrypted message
        \receive{\shortstack[l]{
            $(x, y) \pickUAR Sample_1$ \\
            $\pi_1 \pickUAR Verify_1(\tau_1, y)$ \\
            $b \pickUAR \binary$ \\
            $\pi_2 \pickUAR Verify_2(\tau_2, (y, (\pi_1 \cdot m_b)))$ }}
        {$c = ((y, (\pi_1 \cdot m_b)), \pi_2)$}
        {}

        \cseqdelay

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary guesses which message has been encrypted
        \send{}{$b'$}{\textsc{Output} 1 \textsc{iff} $b=b'$}

    \end{cryptogame}

    % Game 2: Sample (y, x(?)) outside the language instead of inside
    \begin{cryptogame}{pkecca2}{Sample statements outside the language}{2}

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary asks for a challenge
        \send{}{$m_0, m_1$}{}
        %Challenger replies with an encrypted message
        \receive{\shortstack[l]{
            $(x, y) \pickUAR \overline{Sample}_1$ \\
            $\pi_1 \pickUAR Verify_1(\tau_1, y)$ \\
            $b \pickUAR \binary$ \\
            $\pi_2 \pickUAR Verify_2(\tau_2, (y, (\pi_1 \cdot m_b)))$ }}
        {$c = ((y, (\pi_1 \cdot m_b)), \pi_2)$}
        {}

        \cseqdelay

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary guesses which message has been encrypted
        \send{}{$b'$}{\textsc{Output} 1 \textsc{iff} $b=b'$}

    \end{cryptogame}

    \todo{ Non è stato chiaro sull'origine di x ed y, inoltre mi manca da scrivere le query di decifratura}

    % Game 3: Decryption queries return false whenever y is not in the language
    \begin{cryptogame}{pkecca3}{Modify decryption queries}{3}

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary asks for a challenge
        \send{}{$m_0, m_1$}{}
        %Challenger replies with an encrypted message
        \receive{\shortstack[l]{
            $(x, y) \pickUAR \overline{Sample}_1$ \\
            $\pi_1 \pickUAR Verify_1(\tau_1, y)$ \\
            $b \pickUAR \binary$ \\
            $\pi_2 \pickUAR Verify_2(\tau_2, (y, (\pi_1 \cdot m_b)))$ }}
        {$c = ((y, (\pi_1 \cdot m_b)), \pi_2)$}
        {}

        \cseqdelay

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary guesses which message has been encrypted
        \send{}{$b'$}{\textsc{Output} 1 \textsc{iff} $b=b'$}

    \end{cryptogame}

    % Game 4: pi1 is chosen UAR
    \begin{cryptogame}{pkecca4}{$\pi_1$ is chosen \textsc{uar}}{4}

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary asks for a challenge
        \send{}{$m_0, m_1$}{}
        %Challenger replies with an encrypted message
        \receive{ \shortstack[l]{
            $\pi_1 \pickUAR Im(Prove_1)$ \\
            $b \pickUAR \binary$ \\
            $\pi_2 \pickUAR Prove_2(\omega_2, (y, (\pi_1 \cdot m_b)), x)$
        }}
        {$c = ((y, (\pi_1 \cdot m_b)), \pi_2)$}{}

        \cseqdelay

        % Adversary can query the challenger for polynomially-many decryptions
        \send{}{}{}
        \receive{}{}{}

        \cseqdelay

        % Adversary guesses which message has been encrypted
        \send{}{$b'$}{\textsc{Output} 1 \textsc{iff} $b=b'$}

    \end{cryptogame}

\end{proof}

%==================================================

\begin{lemma}
    \[
        \forall b, G_{0}(\lambda, b) \equiv G_{1}(\lambda, b)
    \]
\end{lemma}

\begin{proof}
    This follows by the correctness of $\pi_1$ and $\pi_2$
    \begin{align*}
        \pi_1 &= \tilde{\pi}_1 = Ver_1(\tau_1, y) \\
        \pi_2 &= \tilde{\pi}_2 = Ver_2(\tau_2, y)
    \end{align*}

    with probability 1 over the choice of $((\omega_1, \omega_2), (\tau_1, \tau_2)) \pickUAR \mathcal{S}etup(1^\lambda)$

    \begin{align*}
        \pi_1 &\pickUAR \mathcal{P}rove_1(\omega, y, x) \\
        (\omega_{2}, \tau_{1}) &\pickUAR \mathcal{S}etup_{2}(1^{\lambda}) \\
        \pi_2 &\pickUAR \mathcal{P}rove_2(\omega_{2}, (y, l), x) \quad \forall y \in L , L \in \mathcal{P}roof_1
    \end{align*}

\end{proof}

\begin{lemma}
    \[
        \forall b, G_{1}(\lambda, b) \compindist G_{2}(\lambda, b)
    \]
\end{lemma}
\begin{proof}
    Straightforward reduction from membership hardness.

    \todo{Transcription: Recall we're using verifiers, so $y$ can be outside $L$: $y \pickUAR \overline{Sample}$}
\end{proof}

\begin{lemma}
    \[
        \forall b, G_{2}(\lambda , b) \compindist G_{3}(\lambda, b)
    \]
\end{lemma}
\begin{proof}
    \todo{I'm not completely sure this proof is complete}
    Use 2-universality of $\pi_2$. Recall that the difference between $G_{2}$ and $G_{3}$ is that
    \[
        (g^{(i)}, l^{(i)}, \Pi_{2}^{(i)})\text{ such that }y^{(i)}\not\in L
    \]
    are answered $\perp$ in $G_{3}$, instead in $G_{2}$
    \[
        \perp \text{ comes out as output} \Leftrightarrow
        \tilde{\Pi}^{(i)}_{2}=Ver(\tau, y^{(i)}\not=\Pi^{(i)}_{2})
    \]

    It's possible to distinguish two cases, looking at $c = (y, l, \Pi_2)$:
\begin{enumerate}
    \item if $(y^{(i)}, l^{(i)})=(y,l)$ and $\tilde{\Pi}^{(i)}_{2}=\Pi^{(i)}_{2}$, it outputs $\perp$ if in the decryption scheme ($\Pi^{(i)}_{2} \not= \tilde{\Pi}^{(i)}_{2}$) it outputs $\perp$.

    \item \footnote{when decryption oracle doesn't output the challenge} otherwise $(y^{(i)}, l^{(i)})\not= (y,l)$ if $y^{(i)}\not\in L$ we want that $\Pi^{(i)}_{2}$ doesn't output exactly $Ver_{2}(\tau, (y^{(i)}, l^{(i)}))$, but it should output $\perp$.
\end{enumerate}

\textbf{EVENT BAD:} From \adversary{}'s perspective, the only information he knows is:
\[
    (\omega_{2}, \tilde{\Pi}_{2}=Ver_{2}(\tau_{2}, y))
\]
for $y \not\in L$. The value
\[
    Ver_{2}(\tau_{2}, (y^{(i)}, x^{(i)}))
\]
for $y^{(i)} \in L$ and $(y^{(i)}, l^{(i)}) \neq (y, l)$ is random. Therefore:
\[
    \Pr[BAD] = 2^{-|\mathcal{P}_{2}|}
\]

\end{proof}

\begin{lemma}
    \[
        \forall b , G_{3}(\lambda, b)\equiv G_{4}(\lambda, b)
    \]
\end{lemma}

\begin{proof}
    If we look at the view of $\adversary$, the only information known about $\tau_{1}$ is $\omega_{1}$, since the decryption oracle only computes for $y^{(i)} \in L$:
    \[
        Ver_{1}(\tau, y^{(i)})=Prove_{1}(\omega_{1}, y^{(i)}, x^{(i)})
    \]

    By 1-universality, $\Pi = Ver_{1}(\tau ,y)$ for any $y \in L$ is random.
\end{proof}

\begin{lemma}
    \[
        G_{4}(\lambda, 0)\equiv G_{4}(\lambda, 1)
    \]
\end{lemma}
\begin{proof}
    The challenge ciphertext is independent of $b$.
\end{proof}

%==================================================
\todo{referencing something from another part of lesson 17}

\subsection{Instantiation of \textsc{u-hps} (Universal Hash Proof System)}

We will define a membership-hard language using the \ddh{} assumption

\begin{definition}
    A language $L_\ddh$ is deemed a \emph{\ddh-tuple language} iff:
    \[
        L_\ddh = \{(c_1, c_2) :  \exists r \implies c_1 = g_1^r, c_2 = g_2^r\} \qedhere
    \]
\end{definition}

Observe that, given a group $G$ of order $q$ with $(g_1, g_2)$ as generators, we will have $(g_1, g_2, c_1, c_2)$ but if we impose $g_1 = g$ and $g_2=g^a$ then the previous construction becomes $(g, g^a, c_1, c_2)$. By definition, $c_1 = g_1^{r_1}$ and $c_2 = g_2^{r_2}$, thus I can write $(g, g^a, g^r, g^{ar})$.

Now we can define our system $\Pi := (Setup, Prove, Verify)$:

\begin{itemize}
    \item $Setup(1^\lambda)$: Pick $x_1,x_2 \pickUAR \integer_q$ and define:
    \begin{align*}
        \omega  &= h_1 = (g_1^{x_1}, g_2^{x_2}) \\
        \tau    &= (x_1, x_2)
    \end{align*}
    \item $Prove(\omega, \underbrace{(c_1,c_2)}_y, r)$ will output $\pi = \omega^2$
    \item $Verify(\tau, \underbrace{(c_1,c_2)}_y)$ will output $\widetilde{\pi} = c_1^{x_1} c_2^{x_2}$
\end{itemize}

\textbf{Correctness:} $\pi = \omega^2 = (g_1^{x_1} g_2^{x_2})^r = g_1^{rx_1} g_2^{rx_2} = c_1^{x_1} c_2^{x_2} = \widetilde{\pi}$

\begin{theorem}
    Above construction defines a 1-universal \textsc{dv-nizk} scheme for $L_\ddh$.
\end{theorem}

\begin{proof}
    We want to prove that if we take any $(c_1,c_2) \notin L_\ddh$, the distribution $(\omega = h_1, \widetilde{\Pi} = Verify(\tau, (c_1, c_2)))$ is uniform.

    Define a map $\mu(x_1, x_2) \mapsto (\omega, \pi) = (g_1^{x_1}, g_2^{x_2}, c_1^{x_1}, c_2^{x_2})$ it suffices to prove that $\mu$ is injective. This can easily be done with some constrains:

    \[
        \mu'(x_1, x_2) = \log_{g_1}(\mu(x_1, x_2)) = (log_{g_1}(\omega), log_{g_1}(\pi))
    \]

    For $r_1\neq r_2$ then $c_1=g_1^{r_1},c_2=g_2^{r_2}=g^{\alpha r_2}$. For $\alpha=log_{g_2}g_1$ then $\Pi=c_1^{x_1}c_2^{x_2}=g_1^{r_1x_1}g_2^{r_1x_1+\alpha r_2x_2}$.

    \[\mu'(x_1,x_2)=
        \begin{pmatrix}
            z_1\\
            z_2
        \end{pmatrix}
        =
        \begin{pmatrix}
            1 & \alpha \\
            r_1 & r_2\alpha
        \end{pmatrix}
        \cdot
        \begin{pmatrix}
            x_1\\
            x_2
        \end{pmatrix}
    \]

    \[ \text{Since Det}
    \begin{pmatrix}
        1 & \alpha \\
        r_1 & r_2\alpha
    \end{pmatrix}=
    \alpha(r_2-r_1)\neq 0
    \text{ the map is injective.}
    \]

\end{proof}

\begin{itemize}
    \item $Setup(1^\lambda)$: \begin{itemize}
        \item Pick $x_3,x_4,x_5,x_6 \pickUAR \integer_q$ and define:
        \begin{itemize}
            \item $\omega=(h_2,h_3,s)=(g_1^{x_3},g_2^{x_4},g_1^{x_5},g_2^{x_6},s)$ where $s$ is a \textbf{seed} for a CRH$\rightarrow H=\{H_s\}$ %\item $\tau=(x_3,x_4,x_5,x_6)$
        \end{itemize}
    \end{itemize}
    \item $Prove(\omega, (c_1,c_2,l), r)$ \begin{itemize}
        \item Compute $\beta=H_s(c_1,c_2,l)\in \integer_p$
        \item Output $\Pi=h_2^rh_3^{r\beta}$
    \end{itemize}
    \item $Verify(\tau, (c_1,c_2,l))$\begin{itemize}
        \item Compute $\beta=H_s(c_1,c_2,l)\in \integer_q$
        \item Output $\widetilde{\Pi}=c_1^{x_3+\beta x_5}c_2^{x_4+\beta x_6}$
    \end{itemize}
\end{itemize}

\noindent\textbf{Correctness:}\\ $\Pi=h_2^rh_3^{r\beta}=(g_1^{x_3}g_2^{x_4})^r(g_1^{x_5}g_2^{x_6})^r=c_1^{x_3}c_2^{x_4}c_1^{\beta x_5}c_2^{\beta x_6}=c_1^{x_3+\beta x_5}c_2^{x_4+\beta x_6}=\widetilde{\Pi}$

\begin{theorem}
    The above construction define a 2-universal DV-NIZK for $L_{DDH}$
\end{theorem}
\pagebreak
\begin{proof}
    \textit{Same goal and procedure as before}\\
    - Take any $(c_1,c_2) \notin L_{DDH}$\\
    - Fix $(c_1,c_2,l)\neq (c_1',c_2',l')$ s.t. $(c_1,c_2),(c_1',c_2')\notin L_{DDH}$ which means:
    \begin{itemize}
        \item $(c_1, c_2) = (g_1^{r_1}, g_2^{r_2}) \qquad r_1 \neq r_2$
        \item $(c_1', c_2') = (g_1^{r_1'}, g_2^{r_2'}) \qquad r'_1 \neq r'_2$
        \item $\beta=H_s(c_1,c_2,l)$
        \item $\beta'=H_s(c'_1,c'_2,l')$
    \end{itemize}

    - Let's define a MAP
    \begin{gather*}
        \mu'(x_3,x_4,x_5,x_6)=(\omega, \widetilde{\Pi}=Ver(\tau,(c_1,c_2,l)),\widetilde{\Pi'}=Ver(\tau,(c_1',c_2',l')))= \\
        =(\underbrace{(h_2,h_3)}_{\omega},c_1^{x_3+\beta x_5}c_2^{x_4+\beta x_6},c_1'^{x_3+\beta'x_5}c_2'^{x_4+\beta'x_6}= \\
        =((g_1^{x_3}g_2^{x4},g_1^{x_5}g_2^{x_6}),g_1^{r_1x_3+\beta r_1x_5}g_2^{r_2x_4+\beta r_2x_6},g_1^{r'_1x_3+\beta' r_1'x_5}g_2^{r_2'x_4+\beta'r_2'x_6})
    \end{gather*}
    But I can rewrite $g_2$ as $g_2=g_1^{\alpha}$ since they are generators. So:
    \begin{gather*}
        ((g_1^{x_3+\alpha x_4},g_1^{x_5+\alpha x_6}),g_1^{r_1x_3+\beta r_1x_5}g_1^{\alpha(r_2x_4+\beta r_2x_6)},g_1^{r'_1x_3+r'_1\beta' x_5}g_1^{\alpha(r'_2x_4+\beta' r'_2x_6)})=\\
        = ((g_1^{x_3+\alpha x_4},g_1^{x_5+\alpha x_6}),g_1^{r_1x_3+\alpha r_2x_4+\beta r_1x_5 +\alpha\beta r_2x_6},g_1^{r'_1x_3+ \alpha r'_2x_4 +r'_1\beta' x_5 + \alpha\beta' r'_2x_6})=
    \end{gather*}
    \[
        \begin{pmatrix}
            z_1\\
            z_2\\
            z_3\\
            z_4
        \end{pmatrix}
        =
        \begin{pmatrix}
            1 & \alpha & 0 & 0 \\
            0 & 0 & 1 & \alpha \\
            r_1 & \alpha r_2 & \beta r_1 & \alpha\beta r_2 \\
            r'_1 & \alpha r'_2 & \beta' r'_1 & \alpha\beta' r'_2
        \end{pmatrix}
        \cdot
        \begin{pmatrix}
            x_3\\
            x_4\\
            x_5\\
            x_6
        \end{pmatrix}
    \]

    \[ \text{Since Det}
    \begin{pmatrix}
        .&.&.&. \\
        .&.&.&.\\
        .&.&.&.\\
        .&.&.&.
    \end{pmatrix}=
    \alpha^2(r_2-r_1)(r'_2-r'_1)(\beta-\beta')\neq 0
    \]
    \centering\textbf{IFF:}\\
    $\overbrace{r_2\neq r_1 ,r'_2\neq r'_1}^{\text{for construction}},\beta \neq \beta' \rightarrow$ this last condition is true because we picked $H_s$ collision resistant.\\
    Otherwise $H_s$ computed on different elements($(c_1,c_2,l)$ and $(c'_1,c'_2,l')$) will have to output the same $\beta( = \beta')$.
\end{proof}


\documentclass[12pt]{article}
\input{physics1}
\begin{document}

\section*{NYU Physics I---radial orbits in gravity}

\paragraph{\theproblem}\refstepcounter{problem}%
If you have an object that is a distance $r$ from the center of mass
of the Earth (but still subject to it's gravitational pull) and you
let it go from rest (with respect to the Earth), what does it's
``orbit'' or trajectory look like?

\paragraph{\theproblem}\refstepcounter{problem}%
How do you reconcile your answer to the above with the statement that
all orbits in gravity are ellipses (or conic sections)?  What kind of
ellipse is your trajectory?

\paragraph{\theproblem}\refstepcounter{problem}%
What is the magnitude of the gravitational force on an object of mass
$m$ a distance $r$ from a much larger object of mass $M$?

\paragraph{\theproblem}\refstepcounter{problem}%
If you lift the object of mass $m$ a tiny additional distance $\dd r$,
so it goes a tiny bit higher, how much work $\dd W$ do you do?
Treat the displacement as so small that you can treat the
gravitational force as constant through the change.

\paragraph{\theproblem}\refstepcounter{problem}%
Integrate your answer to the previous question to get the \emph{total}
work $\Delta W$ it takes to lift the object of mass $m$ from one
radius $R_1$ to a significantly larger radius $R_2$.  If you get the
wrong \emph{sign} for your integral, don't worry---the signs are
confusing and not very illuminating.  The important thing is to get
the magnitude correct.

\paragraph{\theproblem}\refstepcounter{problem}%
Now imagine that you do that work, and then \emph{let go} of the
object from rest.  It will fall back down from large radius $R_2$ to
small radius $R_1$.  At what speed $v$ will it be moving when it gets
back to $R_1$?  Ignore all other forces, such as air resistance.

\paragraph{\theproblem}\refstepcounter{problem}%
Now take $R_2$ (the large radius) to infinity.  Does the speed $v$ go
to infinity?  If not, what is the limiting speed $v_\mathrm{escape}$?

\paragraph{\theproblem}\refstepcounter{problem}%
Evaluate the limiting speed $v_\mathrm{escape}$ for the Earth, where
$R_1$ is the radius of the Earth and $M$ is the mass of the Earth.  If
you get something within a factor of two of $10\,\km\,\s^{-1}$, you
are okay; if you don't you must have an error.

\paragraph{\theproblem}\refstepcounter{problem}%
Why do we call this speed ``escape speed''?

\end{document}