%\section{Discussion}

\subsection{Comparison of beading schemes}
We can see from \cref{TEST_naive_accuracy}(top) and~\ref{over_underfill} that the uniform technique causes a lot of overfills and underfills: on average \revise{approximately}{} \revise{\SI{1}{\percent}}{\SI{1.6}{\percent}} of the total target area is covered by underfill and likewise for overfill.
To our knowledge, the uniform beading scheme, as well as the outer beading scheme, is of little use to FDM printers.

The constant bead count scheme effectively deals with underfills, but generates orders of magnitude more overfills compared to the other schemes.
Also, the scheme comes at the cost of greatly varying bead widths and an average bead width that is not close to the preferred bead width.
Note that most overfill areas occur near regions of alternating bead width.
\revise{}{While the scheme results in short toolpaths, as indicated by the idealized print time, it also results in a wide range of bead widths, which cause the back pressure compensation print time to be very large.
See \cref{statisticsfig}.}
For an input outline shape which contains both very small and very large features, the constant bead count scheme produces bead widths which can fall outside of the range of manufacturable bead widths.
Moreover the centrality marking is not robust against small perturbations in the outline; adding a small chamfer in a corner causes the unmarked ST to be very small at that location, which results in tiny bead widths.
\revise{}{See top right of \cref{TEST_Constant_accuracy}.}

In \cref{TEST_Center_accuracy} we can see that
the centered beading scheme effectively deals with \revise{both }{}overfill \revise{and underfill }{}and produces desired bead widths in all locations, except for the extrusion paths in the center, where the bead widths \revise{are within a factor 2 off from the desired bead width.}{range between $0.25 w^*$ and $1.8w^*$.}
\revise{}{However, it does produce some narrow underfill regions.}
\revise{%gs
According to \cref{over_underfill} the overfill and underfill for the centered, the evenly distributed and the inward distributed scheme are all approximately \SI{0.2}{\percent}, which is a considerable improvement over the uniform technique.
}{%sg
Compared to the uniform technique the centered technique increases the (open) path count, but considerably reduces over- and underfill and decimates the number of toolpath angles below \SI{45}{\degree}.
See \cref{statisticsfig}.%afs
}%zgds

However, according to \cref{widthHistogram} the centered scheme exhibits a wider range of bead widths than the distributed schemes:
the standard deviation of the bead widths in the centered scheme is approximately \revise{\SI{39}{\micro\meter}}{\SI{53}{\micro\meter}}, while that of the distributed schemes is approximately \revise{\SI{14}{\micro\meter}}{\SI{23}{\micro\meter}}.%_
\revise{}{\footnote{\revise{}{Although the standard deviation $\sigma$ of the inward distributed scheme is slightly higher than that of the evenly distributed scheme, the mean absolute deviation is lower (i.e. \SI{9}{\micro\meter} versus \SI{11}{\micro\meter}), because its distribution is more peaked.}}}
\revise{}{Moreover, because the quantization operator rounds to the nearest number of beads, in the worst case where we switch from a single to two beads the widths switch from $0.75w^*$ to $1.5w^*$, which is a considerably smaller range than in the centered scheme.}
We therefore conclude that the distributed schemes \revise{result in bead widths closer to the preferred widths}{exhibit a lower bead width variation and lower (open) path count} compared to the centered scheme.
%This is desirable for the manufacturability of the beads and can therefore have a positive effect on the mechanical properties and surface quality of the 3D prints.

\revise{It is hard to visually identify the difference between the evenly and the inward distributed scheme in \cref{visualized_accuracy}, because that particular example shape does not have wide features.}
{\Cref{distributed_comparison,TEST_Distributed_accuracy,TEST_InwardDistributed_accuracy} show that in the inward distributed scheme the outer toolpaths have the preferred width more often than in the evenly distributed scheme, which means that the outline accuracy of the inward distributed beading is less affected by inaccuracies in the adaptive width control system.}
%{\Cref{TEST_InwardDistributed_accuracy} shows that in the inward distributed scheme the outer beads are more often equal to the preferred width compared to the evenly distributed scheme in \cref{TEST_Distributed_accuracy}, but that effect is more pronounced for wider geometry such as in \cref{distributed_comparison}.}
%While the difference between the evenly and inward distributed scheme in \cref{visualized_accuracy} results only in the outer bead being the preferred width in some locations, the effect of the inward distributed scheme is more pronounced in larger geometry, as can be seen in \cref{distributed_comparison}.}
\revise{However, \cref{distributed_comparison} and  \cref{widthIndexedHistogram} confirm that the outer toolpaths have the preferred bead width more often.}{}% _
Furthermore, \revise{from \cref{smoothness} }{}we find that compared to evenly distributed, the inward distributed scheme produces \revise{smoother toolpaths overall}{less corners with angles above \SI{130}{\degree} and less overfill, because the area of influence that bead count transitions have is limited in the inward distributed scheme}.
Thus the inward distributed scheme prevents over- and underfill, generates smooth toolpaths with more homogeneous width and affects smaller more centered parts of the print than the other schemes\revise{}{, while incurring little to no extra print time}.

\revise{}
{
\subsection{Limitations}
% design considerations
Because the performance of the various toolpathing techniques depends on the geometry of a model, they have ramifications for the practice of design for additive manufacturing.
Because the naive method produces under- or overfill for parts of an outline with a constant diameter $d \neq 2 i w^*$ it is best practice to design a model such that horizontal cross-sections have a feature diameter of an even integer multiple $i$ of the bead width.
For the center\revise{ed} scheme and for the current state of the art one should only avoid parts for which $(2i + 1.8) w^* < d < (2i + 0.25) w^*$ in order to avoid underfill.
For the distributed schemes however, there is no diameter at which the framework produces under- or overfill for a part with a constant diameter $d$.
The design consideration therefore reduces to limiting the diameter of your parts to be within the range $[w_\text{min}, \infty)$,
where $w_\text{min}$ is a configurable parameter when using the widening meta-scheme.

% single line segments & continuity
The default limit bisector angle $\alpha_\text{max} = \SI{135}{\degree}$ ensures that we don't employ transitioning in shallow wedge regions, which would result in a lot of short odd single bead polylines, which would break up the semi-continuous nature of polygonal extrusion paths;
$\alpha_\text{max} = \SI{135}{\degree}$ corresponds to $w^* / \cos \nicefrac12 \alpha_\text{max} \approx \SI{0.4}{\milli\meter}$ long segments
and under-/overfill areas of $\nicefrac14 (w^*)^2 \left( \tan ( \alpha / 2) - \alpha / 2 \right) \approx \SI{0.05}{\milli\meter\squared}$.
However, future work might be aimed at reducing under-/overfill in regions with a low bisector angle without the introduction of short single polyline extrusion segments.
If the over-/underfill problem is also solved for non-significant regions we might be able to increase $\alpha_\text{max}$ and reduce the discontinuity introduced by short extrusion segments.

% single beads
Another limitation of our method is that in a location $v$ with locally maximal $R(v) \approx (i + \nicefrac12) w^*$ the odd bead count will result in a single polyline extrusion segment consisting of only a single point.
This can be viewed in the bottom right of \cref{TEST_InwardDistributed_accuracy} for example.
In order to print such a dot, we make it into a \SI{10}{\micro\meter} long extrusion segment, with an altered width such that the total volume remains correct.
A more principled way of dealing with such a situation remains future work.

% emulation troubles
Finally it should be noted that although our framework can accurately emulate the constant bead count approach by \citeauthor{Ding2016a}, its emulation of the centered approach by \citeauthor{Jin2017JMS} is imperfect.
The transitions resulting from out framework introduce sharper corners and there is more width variation in those corners.
Whereas the width of the connecting segment in the approach by \citeauthor{Jin2017JMS} is the preferred width $w^*$, the bead widths closer to the center resulting from our framework will be twice the local radius, which is larger than $w^*$.
However, this inflated bead width variation is expected to have an insignificant impact on the measured bead width variation.
}

\input{10_applications}

\revise{
\subsection{Discussion on implications}
Note that the current industry standard in FDM printing employs little to no bead width variation.
Properly performing bead width variation calls for adaptations and developments in printers and firmware.
In the beading schemes we set a transition length of $t(n) = w^*$.
That will demand changes in cross-sectional area of the bead up to \SI{200}{\percent} over a small distance that is comparable to the nozzle size, which is challenging for some hardware systems.
Varying the movement speed can be utilized to change the cross-sectional area, but this approach is limited, since the movement speed is constrained by acceleration considerations near bends in the toolpath~\cite{Ertay2018,Kuipers2018}.
Our schemes require a more accurate control of the volumetric flow rate in \si{\milli\meter\cubed\per\second}.
Using a filament feeder directly mounted on the print head (a.k.a. direct drive) can control the flow more dynamicaly then FDM printers where the material is fed through a Bowden tube from a feeder mounted on the frame.
Still direct drive printers require some control system in order to accurately change the volumetric flow rate such as pressure advance algorithms~\cite{tronvoll2019investigating}.
Yet inaccuracies in direct drive systems employing advance algorithms might arise due to the changes in back-pressure required by changing bead size.
We expect that developments in printing hardware and firmware will address these challenges in the future.

Another limiting factor for adopting adaptive bead width is the format of G-code which stores machine instructions.
G-code does not support moves with varying cross-sectional area.
A typical extrusion move \lstinline!G1 X$x$ Y$y$ E$v$! only specifies the total amount of volume $v$ to be extruded in the move, not how that total amount should be distributed along the extrusion move.
A workaround is to approximate a variable width extrusion segment by smaller segments with constant width.
However, this introduces errors nevertheless.
Ideally the G-code language would be expanded in some way to allow for extrusion segments with varying cross-sectional area.
}{}

% Taking a broader perspective, we note that our proposed inward distributed scheme is a pragmatic solution.
% Rather than deriving some optimal beading scheme from a clear specification of the objective, we propose some arbitrary inward distributed beading scheme and show that it is better than the other beading schemes.
% An optimal beading scheme can be derived if the objective is formalized terms of a unambiguous fitness function, but that would depend on the specific hardware setup and application for which toolpaths are generated.
% This manuscript is therefore limited to showing the flexibility and versatility of the framework, rather than deriving an optimal beading scheme.


\subsection{Policy iteration for POMDPs}


\subsection{Fishing Mortality in Stock Synthesis}

The implementation and reporting of fishing mortality rate, $F$, in SS3 has some aspects that can be confusing.  This description provides an overview of the ways in which $F$ is calculated, used, and reported.

\myparagraph{Rationale}
Fishery management systems expect to have a measure of annual fishing mortality that describes the intensity of the fishery such that an optimal level of $F$ can be articulated and accountability measures can be invoked if $F$ is too high, e.g., overfishing.  This concept is simple and straightforward if the model is a simple biomass dynamics such that a single annual $F$ value operates on the entirety of a non-age structured population. It also is simple for age-structured models that have a single fishing fleet and knife-edge selectivity beginning at some specified age.

The simplicity of $F$ disappears quickly as models invoke a variety of realistic complexities such as: allowing the $F$ to differ among ages or to be based on size; using a collection of fleets with different $F$ levels and different age patterns for $F$; spreading the population across areas and allowing different fleets with different $F$ among the areas.  An unambiguous measure of annual fishing intensity that represents the cumulative effect of all that complexity has not been defined.  This problem has not been solved with SS, but some logical alternatives have been made available.

\myparagraph{Nomenclature}
The nomenclature below ignores sex, morphs and areas for simplicity. The quantities associated with $F$ calculations are defined as:

$f$ is fleet.

$t$ is a time step; continuous across years $y$ and seasons $s$; equivalent to year if only 1 season.

$a$ is age.

$C_{t,f}$ is fleet-specific catch in a time step.

$B_{t,f}$ is fleet specific available biomass, e.g., total biomass filtered by fleet-specific age selectivity, $s_{t,f,a}$.

$s_{t,f,a}$ is age-specific selectivity for a fleet. If selectivity is length-specific, then age-specific selectivity is calculated as the dot product across length bins of length selectivity and the normal (or lognormal) distribution of length-at-age.  If selectivity is both length- and age-based, which is an entirely normal concept in SS, then age selectivity due to length selectivity is calculated first, then multiplied by the direct age selectivity.  This compound age selectivity is used in the mortality calculations and is reported as asel2 in report file.  See appendix to \citet{methotstock2013} for more detail on this.

$F_{t,f}'$ is the apical fishing mortality for a fleet. This means that it is the rate for the age that has selectivity equal to 1.0. If your model is using $F'$s as parameters, then the parameter values are for $F'$.

$F_{t,f,a}$ is age and fleet-specific fishing mortality rate equal to $F_{t,f}' * s_{t,f,a}$. Note that it is possible for no age to have a selectivity equal to 1.0. In this case, $F'$ is still the rate for the hypothetical age that has selectivity equal to 1.0. The reported $F'$ values are not rescaled to be an $F$ for the age with peak selectivity. Users need to take this into account if they are comparing reported $F'$ values to reported vector of $F_{t,f,a}$ values.

$\text{ann}F_y$ is a measure of the total fishing intensity for a year, based on one of several user-specified options (see below).

$F\text{std}_y$ is a standardized measure of the total fishing intensity for a year and is reported in the derived quantities, so variance is calculated for this quantity. See below for how it relates to $annF$.

Terminology and reporting of $\text{ann}F$ and $F\text{std}$ has been slightly revised for clarity in 3.30.15.00 and the description here follows the new conventions.

\myparagraph{$F$ Calculation}
SS3 allows for three approaches to estimate the $F'$ that will match the input values for retained catch. Note that SS3 is calculating the $F'$ to match the retained catch conditional on the fraction of total catch that is retained, e.g., the total catch is partitioned into retained and discarded portions.

\begin{enumerate}
	\item Pope’s method decays the numbers-at-age to the middle of the season, calculates a harvest rate for each fleet, $H_{t,f}$, that is the ratio of $C_{t,f}$ to $B_{t,f}$, then decays the survivors to the end of the season. the total mortality, $Z_{t,a}$, from the ratio of survivors to initial numbers, is then calculated. The $Z$ is subsequently used for in-season interpolation to get expected values for observations.

	\item $F$ as parameters uses the standard Baranov catch equation and lets ADMB find the $F'$ parameter values that produce the lowest negative log-likelihood, which includes fit to the input catch data. $F$ as parameters method tends to work better than Pope’s or hybrid in high $F$ situations because it allows for some lack of fit to catch levels in early iterations and can later improve this fit as it closes in on the best solution.

	\item Hybrid $F$ starts by calculating a harvest rate, $H$, using Pope’s, then converts these $H$ values, which have units of fractional harvest rate, into an approximate of $F'$ in exponential units, tuning these $F'$ values over a few iterations to get a better match to each fleet’s catch.
\end{enumerate}

Items to note:
\begin{itemize}
	\item SS3 includes a permutation on the $F$ as parameters method. In the first few phases, SS3 uses hybrid, then between phases it converts these directly calculated $F'$ values into parameters and proceeds in subsequent phases and MCMC to use the parameter approach. This variation on the parameter method is the recommend approach in high $F$ situations.

	\item With Pope’s method, the $H$ values are fraction caught, so duration of the season does not matter. Parameter and hybrid treat $F'$ identically and multiply the $F'$ values by season duration (which has units of fraction of a year) as it is used. Each of the $F$ methods ends up with a $Z_{t,f}$ that is used for in-season interpolation.
\end{itemize}

\myparagraph{Relative $F$ and $F$mult}
The $F'$ is fleet-specific, so it is useful to have a concept of relative $F$, $\text{rel}F_f$, among fleets. In SS, $\text{rel}F_f= F_{t,f}'/\sum_{f}^{}F_{t,f}'$ for a single time period $t$. In the benchmark and forecast routines, SS3 can calculate $\text{rel}F_f$ using $F_{t,f}'$ over a range of years, or the user can input custom $\text{rel}F$ values for benchmark and forecast in the forecast.ss file. Note that in a multi-season model setup, $\text{rel}F_f$ is implemented as $\text{rel}F_{s,f}$ where $s$ is the season. These get multiplied by season duration as they are used.

In the benchmark section of the code, SS3 searches for an $F$mult to achieve various management reference points (often referred to as benchmarks). In this search, SS3 calculates a benchmark $F$ as  $F_{ben,f}' = F\text{mult} * \text{rel}F_f$, then calculates equilibrium yield and spawning biomass per recruit (SPR). SS3 searches for the $F$mult that satisfies the search conditions, first for user-specified SPR, then for user-specified spawning biomass at a management target (B\textsubscript{TGT} or $F_{0.1}$), then for MSY. The resultant benchmark quantities are reported in the derived quantities, but $F$mult and $F_{ben,f}'$ are only reported in the Forecast\_report.sso file. SS3 stores the benchmark $F$mult values so that user can invoke them for the forecast.

\myparagraph{Annual $F$}
The $\text{ann}F$ is a single annual value across all fleets and areas according to F\_report\_units, which is specified by users in the starter file. If there are many fleets, across several areas and with very different selectivity patterns, $\text{ann}F$ can have a complicated relationship to apical $F$. The F\_report\_units specification in the starter.ss file, see example line below, allows user to calculate it using $F'$ directly, use exploitation rate, or be derived from $Z$-at-age.

Example $F$ reporting unit specification in the starter.ss file:

\begin{center}
	\begin{longtable}{p{2cm} p{12cm}}
		\hline
		5 & \# F\_report\_units:\Tstrut\\
		  & 0 = skip; \\
		  & 1 = exploitation(Bio); \\
		  & 2 = exploitation(Num); \\
		  & 3 = sum(Frates); \\
		  & 4 = true F for range of ages; \\
		  & 5 = unweighted avg. F for range of ages. \Bstrut\\
		\hline
		3 7 & \# min and max age over which average F will be calculated \Tstrut\Bstrut\\
		\hline
	\end{longtable}
\end{center}

For options 4 and 5 of F\_report\_units, the $F$ is calculated as $Z-M$ where $Z$ is calculated as $ln(N_{t+1,a+1}/N_{t,a})$, thus $Z$ subsumes the effect of $F$.

The ann$F$ is calculated for each year of the estimated time series and of the forecast. Additionally, an ann$F$ is calculated in the benchmark calculations to provide equilibrium values that have the same units as ann$F$ from the time series. In versions previous to 3.30.15, it was labeled inaccurately as $F$std in the output, not ann$F$. For example, in the Management Quantities section of derived quantities prior to 3.30.15, there is a quantity labeled Fstd\_Btgt. This is more accurately labeled as the annual $F$ associated with the biomass target, ann\_F\_Btgt, in 3.30.15.

\myparagraph{$F$std}
$F$std is a single annual value based on ann$F$ and the relationship to ann$F$ is specified by F\_report\_basis in the starter.ss file. The benchmark ann$F$ may be used to rescale the time series of ann$F$s to become a time series of standardized values representing the intensity of fishing, $F$std. The report basis is selected in the starter file as:

\begin{center}
	\begin{longtable}{p{2cm} p{12cm}}
		%\multicolumn{2}{l}{The starter file line:}\\
		\hline
		0 & \# F\_report\_basis: \Tstrut\\
		& 0 = raw F report; \\
		& 1 = F / F\textsubscript{SPR}; \\
		& 2 = F / F\textsubscript{MSY}; \\
		& 3 = F / F\textsubscript{BTGT}.\Bstrut\\
		\hline
	\end{longtable}
\end{center}

For example, if user selects option 1, $F$ / $F_\text{SPR}$, the time series of ann$F$ will be divided by each value by the ann$F$ calculated in benchmark.

\myparagraph{Units for Stock Synthesis inputs related to $F$}
Below is a list of items to consider in terms of units for $F$ in SS:
\begin{itemize}
	\item If F\_ballpark is specified in the control.ss file, its units are the same as ann$F$, so is not fleet-specific.

	\item $F$ as parameter values has units of fleet-specific apical $F'$.

	\item In the forecast.ss file there is an option to input a vector of rel$F$ values. These are dimensionless and will be rescaled to sum to 1.0.

	\item In the forecast.ss file there is an option to specify an $F$ scalar for the forecast.  The units of $F$ scalar are the same as the $F$mult values calculated in benchmark.  There are a full set of options for forecast $F$ scalar that can be selected in the forecast file
	%(-1 = none; 0 = simple; 1 = F\textsubscript{SPR}; 2 = F\textsubscript{MSY} 3 = F\textsubscript{BTGT} or F\textsubscript{0.1}; 4 = Ave F (uses first-last relative F years); and 5 = input annual F scalar).
	If the forecast $F$ scalar is set as $F_\text{SPR}$, then SS3 will use SPR\_Fmult calculated in benchmark and reported in Forecast-report.sso.  If user selects the option to input an annual $F$ scalar, option 5, then the value is input on a following line.  Whichever method the user selects for forecast $F$ scalar ($F$mult), SS3 will start the forecast by creating a fleet-specific vector of apical $F$ values from $F$mult*rel$F_f$.

	\item Also in the forecast.ss file, the last section of inputs allows for input of time and fleet specific apical $F_{t,f}'$ values that override the basic forecast $F$ specification described above.
\end{itemize}


\chapter{To verify truth table for XOR gate}

\section{Apparatus}
%\label{sec:objectives}
	\begin{itemize}
		\tightlist
		\item Kit for realization of gates
		\item Connecting Leads
	\end{itemize}

\section{Theory}
	The 'Exclusive-OR' gate is a circuit which will give a high output if either, but not both of its two inputs are high. An encircled plus sign ($\oplus$) is used to show the Ex-OR operation.
	\begin{figure}[h]
		\centering
		\includegraphics{img/exp6/1}
		\caption{Symbol for XOR gate}
		\label{fig:6:1}
	\end{figure}
	\begin{figure}[h]
		\centering
		\includegraphics{img/exp6/2}
		\caption{Truth Table for XOR gate}
		\label{fig:6:2}
	\end{figure}

	Ex-OR gate is created from AND, NAND and OR gates.The output is high only when both the inputs are different.

	\begin{figure}[h]
		\centering
		\includegraphics{img/exp6/3}
		\caption{Circut for making XOR gate}
		\label{fig:6:3}
	\end{figure}

\section{Procedure}
	\subsubsection{Simulator 1}
	\begin{itemize}
		\tightlist
		\item Connect the supply(+5V) to the circuit.
		\item Press the switches for inputs "A" and "B".
		\item The bulb glows if one of the switches is ON and one of the switches is OFF else it won't glow.
		\item Repeat step-2 and step-3 for all state of inputs.
	\end{itemize}

	\subsubsection{Simulator 2}
	\begin{itemize}
		\tightlist
		\item Enter the Boolean input "A" and "B".
		\item Enter the Boolean output for your corresponding inputs.
		\item Click on "Check" Button to verify your output.
		\item Click "Print" if you want to get print out of Truth Table.
	\end{itemize}

\section{Observations}
	\begin{figure}[h]
		\centering
		\includegraphics[width=0.9\linewidth]{img/exp6/4}
		\caption{}
		\label{fig:6:4}
	\end{figure}
		\begin{figure}[h]
		\centering
		\includegraphics[width=0.9\linewidth]{img/exp6/5}
		\caption{}
		\label{fig:6:5}
	\end{figure}
		\begin{figure}[h]
		\centering
		\includegraphics[width=0.9\linewidth]{img/exp6/6}
		\caption{}
		\label{fig:6:6}
	\end{figure}
		\begin{figure}[h]
		\centering
		\includegraphics[width=0.9\linewidth]{img/exp6/7}
		\caption{}
		\label{fig:6:7}
	\end{figure}

\section{Conclusion}
XOR gate basically is a special version of OR gate which gives a low even when both the inputs of OR gate are high.

\section{Precautions}
	\begin{enumerate}
		\tightlist
		\item Make the connections when power supply is OFF.
		\item Ensure that the connections are tight.
		\item Change the status of inputs only when power supply is OFF.
	\end{enumerate}


% Chapter 2

\chapter{Conclusion} % Main chapter title

\label{Chapter6} % For referencing the chapter elsewhere, use \ref{Chapter2}

We have reviewed some of the algorithms used for sampling a uniform spanning tree. The main impetus for going into the details of \citet{harvey2016generating} is due to the fact that it uses the Sherman-Morrison-Woodbury identity for updating the laplacian pseudoinverse. Recently \citet{DBLP:journals/corr/abs-2004-12739} also used the same identity for showing that \textbf{REACHABILITY} problem is in \texttt{DynFO} + \texttt{Mod} $2(\leq, +, \times)$. Hence we explored the possibility of using the same framework for sampling spanning trees in the dynamic setting. But it turns out that there are a lot of subtleties in coming up with a proper formulation.

%----------------------------------------------------------------------------------------

%----------------------------------------------------------------------------------------


\chapter{EPLD and PAL Programs}

These are the programs used in the different EPLDs and PALS in the computer.

\section{Control EPLD Program}

This is the  Moore Machine to control instruction execution and memory accesses.
It can fit upon an  EP610 or EP600.
The state machine is illustrated in figure~\ref{fig:statemc}.

\begin{verbatim}

Steve Loughran
Edinburgh University
29/3/89
1
B
EP600
The Control EPLD -v3.0
OPTIONS:TURBO = ON
PART:EP600
INPUTS:
        %clock%
        CLK@1
%go run- active low%
        GO@11
%load registers%
        LOAD@23
%l/s - select read or write operation%
        LS@14

%halt - sent from the address decoders%
        HALT@2
OUTPUTS:

%read/write line%
        RW@10

%memory select - active high%
        MS@21

%load Memory Address Register%
        LOADM@6

%load Data register%
        LOADD@4

%load Instruction register%
        LOADI@20

%plus of course all the state outputs%
        STATE0@19
        STATE1@18
        STATE2@17
        STATE3@16
        STATE4@15

%source/destination select%
        SOURCE@9

%Increment the PC%
        INCPC@7

%load the SSR Pc register%
        LOADPCR@5

%operand output enable%
        OEOP@22

NETWORK:
        %Define the outputs%
        RW=CONF(RWc,)
        MS=CONF(MSc,)
        LOADM=CONF(LOADMc,)
        LOADI=CONF(LOADIc,)
        LOADD=CONF(LOADDc,)
        SOURCE=CONF(SOURCEc,)
        INCPC=CONF(INCPCc,)
        LOADPCR=CONF(LOADPCRc,)
        OEOP=CONF(OEOPc,)

MACHINE:        control
CLOCK:        CLK

STATES: [STATE4 STATE3 STATE2 STATE1 STATE0]
PU	[0 	0	0	0	0  ]
S1	[0	0	0	0	1  ]
S2	[0	0	0	1	0  ]
S3	[0	0	0	1	1  ]
S4	[0	0	1	0	0  ]
S5	[0	0	1	0	1  ]
S6	[0	0	1	1	0  ]
S7	[0	0	1	1	1  ]
S8	[0	1	0	0	0  ]
S9	[0	1	0	0	1  ]
S10	[0	1	0	1	0  ]
I0	[1	0	0	0	0  ]
I1	[1	0	0	0	1  ]
I2	[1	0	0	1	0  ]
I3	[1	0	0	1	1  ]
I4	[1	0	1	0	0  ]
I5	[1	0	1	0	1  ]
I6	[1	1	1	0	0  ]
I7	[1	1	1	0	1  ]

PU:
        IF GO * LOAD THEN S1

S1:
        IF /LOAD THEN S2
        IF /GO THEN I0

S2:
        IF /LOAD THEN S2
        IF /GO THEN S1
        IF LS THEN S3
        S7

S3:        IF /HALT THEN PU
        S4

S4:        IF /HALT THEN PU
        S5

S5:     IF /HALT THEN PU
        S6

S6:     IF /HALT THEN PU
                S1

S7:     %start write%
        S9

%the next state should never be reached; the state machine programmer does not
recognise the exit transition, but will not compile without it...%

S8:      %dead state%
        S0

S9:     %keep writing; assert MS%
        S10

S10:        %stop writing%
        S1

% Instruction Execution %

I0:        %Get PC, continue write%
        IF GO THEN S1
        I1

I1:        %PC out%
        I2

I2:        %I-fetch & increment PC%
        IF /HALT THEN PU
        I3

I3:        %I strobe%
        I4

I4:        %source fetch%
        I5

I5:        %source strobe%
        IF /HALT THEN PU
        I6

I6:        %destination out%
        I7

I7:        %write to destination%
        I0

%now give the  signal outputs as a truth table%

T_TAB: STATE4 STATE3 STATE2 STATE1 STATE0:
        RWc MSc LOADMc LOADDc LOADIc LOADPCRc INCPCc OEOPc SOURCEc;
     %halted%
%PU%  0 0 0 0 0: 1 1 0 0 0 0 0 1 0;
     %waiting%
%S1%  0 0 0 0 1: 0 0 0 0 0 0 0 1 0;
     %loaded%
%S2%  0 0 0 1 0: 1 0 1 1 0 0 0 1 0;
     %read-1%
%S3%  0 0 0 1 1: 1 1 0 0 0 0 0 1 0;
     %read-2%
%S4%  0 0 1 0 0: 1 1 0 0 0 0 0 1 0;
     %read-3%
%S5%  0 0 1 0 1: 1 1 0 0 0 0 0 1 0;
     %read-end%
%S6%  0 0 1 1 0: 1 0 0 1 0 0 0 1 0;

     %write-1%
%S7%  0 0 1 1 1: 0 0 0 0 0 0 0 1 0;

% no S8 outputs given%

     %write-2%
%S9%  0 1 0 0 1: 0 1 0 0 0 0 0 1 0;
     %write-end%
%S10% 0 1 0 1 0: 0 0 0 0 0 0 0 1 0;

%Instruction execution signals%

     %get pc%
     %pc-addr%
%I0%  1 0 0 0 0: 0 0 0 0 0 1 0 1 0;
     %i-fetch (output PC)%
%I1%  1 0 0 0 1: 1 0 1 0 0 0 0 1 0;
     %i-strobe%
%I2%  1 0 0 1 0: 1 1 0 0 0 0 0 0 0;
     %s-addr (calculate source address)
%I3%  1 0 0 1 1: 1 1 0 0 1 0 1 0 0;
     %s-fetch%
%I4%  1 0 1 0 0: 1 1 1 0 0 0 0 0 1;
     %s-strobe%
%I5%  1 0 1 0 1: 1 1 0 0 0 0 0 0 1;
     %d-addr%
%I6%  1 1 1 0 0: 0 0 1 1 0 0 0 1 0;
     %d-write%
%I7%  1 1 1 0 1: 0 1 0 0 0 0 0 0 0;
END$
\end{verbatim}
\begin{figure}
\vspace{20cm}
\caption{Control Unit State Transition Diagram}
\label{fig:statemc}
\end{figure}
\clearpage
\section{Address Decoders}
The address decoder is implemented in two EPLDS.
At the slow speeds of my prototype, both could in fact be combined into the
single EP310 EPLD.
If the control EPLD was ever upgraded to an EP610, then the complex address decoder would also have to be upgraded to one which could operate at the same clock speed, which an EP310 or EP320 can not do.

\subsection{Complex Address Decoder}
This  EP600 program decodes the following signals:-
\begin{itemize}
\item the control of the source of the PC increment signal.
The increment signal should only be connected to the data bus for one clock cycle,
when the skip register is written to.
This increment must be done before the PC is loaded into the PCR or the skip is delayed.
\item the loading of the CC register after a write to the Carry.
\item loading the CC and the ACC registers after an ALU operation.
This must be done at least 100~nS after the start of the  write cycle.
\end{itemize}
To control the timing of signal issue, a Mealy Machine is used.

\begin{verbatim}
Steve Loughran
Edinburgh University
30/3/89
1
A
EP600
Complex Address Decoder
OPTION:TURBO=ON
PART:EP600
INPUTS:
        %clock%
        CLK@1
        %control signals%
        MS@2
        RW@23
        %address lines%
        A14@6
        A4@7
        A3@5
        A1@10
        A0@11

OUTPUTS:
%state outputs%
        C0@9,C1@8,C2@4
%load register signals%
        LOADA@15
        LOADCC@16
%select source of PC count instruction%
        SKIP@17

NETWORK:
        SKIP=CONF(SKIPc,)

MACHINE: complex
CLOCK: CLK
STATES: [C2     C1	C0	LOADA	LOADCC]
PU	[0	0	0	0	0]
S0	[1	1	1	0	0]
S2	[0	1	0	0	0]
S3	[0	1	1	0	0]
S5	[1	0	1	1	1]
S6	[1	1	0	0	1]

PU:
        S0
S0:
        %skip%
        IF MS*/A14*/A4*/A3*/A1*A0*/RW THEN S2
        %alu operation%
        IF MS*/A14*/RW*A4 THEN S3
        %load Carry%
        IF MS*/RW*/A14*/A4*A3 THEN S6

        %enable count from data bus0 for one cycle only%
        OUTPUTS:
                IF MS*/A14*/A4*/A3*/A1*A0*/RW THEN SKIPc
S1:
        S2
S2:         %wait till end of write cycle%
        IF /MS + RW THEN S0

        %perform an ALU operation%
S3:
        S5
S5:           %wait till end of cycle%
        IF /MS +RW THEN S0

                %load condition code register%
S6:           %wait till end of write cycle%
        IF /MS +RW THEN S0
END$
\end{verbatim}

\subsection{Simple Address Decoder}
The remaining EPLD addresses are all implemented in a purely combinatorial manner.
\begin{verbatim}
Steve Loughran
Edinburgh University
30/3/89
1
A
EP310
Simple Address Decoder
OPTION: TURBO=ON
PART: EP310
INPUTS:
        CLK@1
        % control signals%
        RW@3
        MS@2
        %address lines%
        A0@9
        A1@8
        A3@6
        A4@5
        A14@4
OUTPUTS:
        HALT@19
        LOADX@18
        LOADY@17
        LOADPC@16
        OEACC@15
        OECC@14
NETWORK:
        CLK=INP(CLK)
        RW=INP(RW)
        MS=INP(MS)
        A0=INP(A0)
        A1=INP(A1)
        A3=INP(A3)
        A4=INP(A4)
        A14=INP(A14)
        HALT=CONF(HALTc,)
        LOADX=CONF(LOADXc,)
        LOADY=CONF(LOADYc,)
        LOADPC=CONF(LOADPCc,)
        OEACC=CONF(OEACCc,)
        OECC=CONF(OECCc,)
EQUATIONS:
%the halt signal%
        HALTc=/(MS*/RW * /A14 * /A4 * /A3);
%output enables%
        OEACCc=/(MS * RW * /A14 * /A4 * /A3);
        OECCc=/(MS * /RW * /A14 * A4);
%register loading%
        LOADPCc=MS * /RW * /A14 * /A4 */A3 */A1 */A0;
        LOADXc=MS * /RW * /A14 * /A4 * /A3 */A1 */A0;
        LOADYc=MS */RW * /A14 * /A4 */A3 *A1 * A0;
END$
\end{verbatim}
\section{ALU shift and condition code programs}

The ALU shift unit is implemented with four PALS identically programmed to shift seven bits
a single bit to the right, and a special fifth device to shift the most significant bits.
Currently this most significant shift is performed in an EPLD, rather than a PAL.
The Condition Code evaluation is also done by an EPLD.
This was because some spare EPLDs were available for use.
By using these instead of PALS I avoided having to irreparably program two PALS.
This has increased the propagation delay of the ALU by 20 nS;
the PALs  need to be programmed to achieve full speed.

\subsection{Shift PALS}
The first four PALS were all programmed with the PAL software on the APMS.
This uses two files, a pin specification file and an equation specification file.

\subsubsection{Pinout}
\begin{verbatim}
{shift1.pin}
{the pinouts for the first four shift & zero detect PALS}

1 F0
2 F1
3 F2
4 F3
5 F4
6 F5
7 F6
8 F7
9 SHIFT
0
12 Z
19 H0
18 H1
17 H2
16 H3
15 H4
14 H5
13 H6
0
\end{verbatim}

\subsubsection{equations}
\begin{verbatim}
{Stephen Loughran}
{Edinburgh University CS4}
{15/5/89}
{PAL 10H8}
{ALU Shift Pal -1}
{Pal Implementation}
MODE EQUIN
IN F0,F1,F2,F3,F4,F5,F6,F7,SHIFT

	{each output is the input if shift is false}
	{or the input to the left if the shift signal is true}

        H0=F0.\SHIFT+F1.SHIFT
        H1=F1.\SHIFT+F2.SHIFT
        H2=F2.\SHIFT+F3.SHIFT
        H3=F3.\SHIFT+F4.SHIFT
        H4=F4.\SHIFT+F5.SHIFT
        H5=F5.\SHIFT+F6.SHIFT
        H6=F6.\SHIFT+F7.SHIFT

        {The zero flag normally tests inputs 0-6 for being zero}
        {returning true if so}
        {but on a shift tests bits 1-7 instead}
Z=\SHIFT.\F0.\F1.\F2.\F3.\F4.\F5.\F6+SHIFT.\F1.\F2.\F3.\F4.\F5.\F6.\F7
OUT Z,H6,H5,H4,H3,H2,H1,H0
\end{verbatim}

\subsection{The Shift EPLD}
This EPLD program shifts the most significant four bits of the result
and the carry flag.
It differs from the previous shift PALS in that the number of bits being tested
for zero is less ---the carry flag is not included in any test.
\begin{verbatim}
Stephen Loughran
Edinburgh University CS4
15/5/89
1
A
EP310
ALU Shift Pal -2   Most Significant Bits

OPTION: TURBO=ON
PART: EP310
INPUTS:
        F28@1
        F29@2
        F30@3
        F31@4
        Cin@5
        F0@6
        SHIFT@9
OUTPUTS:
        Z@12
        CARRY@15
        H31@16
        H30@17
        H29@18
        H28@19
NETWORK:
        F28=INP(F28)
        F29=INP(F29)
        F30=INP(F30)
        F31=INP(F31)
        Cin=INP(Cin)
        F0=INP(F0)
        SHIFT=INP(SHIFT)

        H28=CONF(H28c,)
        H29=CONF(H29c,)
        H30=CONF(H30c,)
        H31=CONF(H31c,)
        CARRY=CONF(CARRYc,)
        Z=CONF(Zc,)

EQUATIONS:
        H28c=F28*/SHIFT+F29*SHIFT;
        H29c=F29*/SHIFT+F30*SHIFT;
        H30c=F30*/SHIFT+F31*SHIFT;
        H31c=F31*/SHIFT+Cin*SHIFT;
        CARRYc=Cin*/SHIFT+F0*SHIFT;
        Zc=/SHIFT*/F28*/F29*/F30*/F31+
            SHIFT*/F29*/F30*/F31*/Cin;
END$
\end{verbatim}
\subsection{Condition Code EPLD}

This EPLD generates the zero and carry flags for the condition code register.
The Zero flag is true when all five zero flags from the Shift Unit are true.
The carry flag is selected from the result of the shift unit or bit zero of the data bus, depending upon the state of address bus line 4.
In this way the carry flag can be set by an explicit write operation.
\begin{verbatim}
Steve Loughran
Edinburgh University CS4
13/5/89
2
A
EP310
Condition Code PAL/EPLD
OPTION:TURBO=ON
PART:EP310
INPUTS:
        ADDR4@3
        Z0@4
        Z1@5
        DATA0@6
        Z2@7
        Z3@8
        Z4@9
        CIN@11
OUTPUTS:
        ZERO@19
        CARRY@17
NETWORK:
        ADDR4=INP(ADDR4)
        Z0=INP(Z0)
        Z1=INP(Z1)
        Z2=INP(Z2)
        Z3=INP(Z3)
        Z4=INP(Z4)
        DATA0=INP(DATA0)
        CIN=INP(CIN)
        ZERO=CONF(ZEROc,)
        CARRY=CONF(CARRYc,)
EQUATIONS:
        %Select carry from ALU or Databus%
        CARRYc=ADDR4*CIN+/ADDR4*DATA0;

        %calculate the Zero flag%
        ZEROc=Z0*Z1*Z2*Z3*Z4;
END$
\end{verbatim}


\documentclass[12]{scrartcl}
\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}
\makeatletter
\newcommand\Aboxed[1]{
   \@Aboxed#1\ENDDNE}
\def\@Aboxed#1&#2\ENDDNE{%
   &
   \settowidth\@tempdima{$\displaystyle#1{}$}
   \setlength\@tempdima{\@tempdima+\fboxsep+\fboxrule}
   \kern-\@tempdima
   \boxed{#1#2}
}
\makeatother

\begin{document}

\title{Homework 1, Section 5.2: 21, 22, 23}
\author{Alex Gordon}
\date{\today}
\maketitle
\section*{Homework}
\subsection*{21. A)}
False. If a matrix is not invertible then its determinant is zero. By the invertible Matrix Theorem, then
\subsection*{21. B)}
False. This contradicts the properties of a determinant (see theorem 3).
\subsection*{21. C)}
True. This contradicts the properties of a determinant (see theorem 3).
\subsection*{21. D)}
False. Example 4 proves this wrong.

\subsection*{22. A)}
False. When A is a 3 x 3 matrix, det A turns out to be the volume of the parallelepiped determined by the columns of $a_1, a_2, a_3$
\subsection*{22. B)}
False. This contradicts the properties of a determinant (see theorem 3).
\subsection*{22. C)}
True. In general, the algebraic multiplicity of an eigenvalue is its multiplicity as a root of the characteristic equation.
\subsection*{22. D)}
False. The slightly incorrect warning on page 277 shows this.

\subsection*{23.}
If $A = QR$, with Q invertible, and if $A_1 = RQ$ then $A_1 = Q^{-1}QRQ = Q^{-1} AQ$ which shows that $A_1$ is similar to A

\end{document}


\documentclass[12pt]{article}
\input{physics1}
\newcommand{\ap}{\mathrm{ap}}
\newcommand{\peri}{\mathrm{peri}}
\begin{document}

\section*{NYU Physics I---Problem Set 12}

Due Thursday 2018 November 29 at the beginning of lecture.

\paragraph{\problemname~\theproblem:}\refstepcounter{problem}%
What is the most expensive ingredient of a typical, traditional
Thanksgiving dinner \emph{by weight} (that is, in dollars per ounce or
per pound).  Start with the turkey and show your work (that is,
compare some ingredients). Don't forget the trace (that is, small
in quantity) ingredients!
What is the relevance of all this to world
history? Keep it traditional---traditional food with traditional
ingredients, like you could have cooked in 1850.
You might want to discuss with someone who cooked
a Thanksgiving dinner (or did the shopping for it).

\paragraph{\problemname~\theproblem:}\refstepcounter{problem}%
If all goes well in class on 2018-11-20, we will get a quadratic equation
for the radii $r_\ap$ and $r_\peri$ of aphelion and perihelion. The argument
goes like this: The total energy of an orbit can be written in terms of the
angular momentum and the radial velocity
\begin{eqnarray}
E & = & \frac{1}{2}\,m\,v^2 - \frac{G\,M\,m}{r}
\\
E & = & \frac{1}{2}\,m\,v_r^2 + \frac{1}{2}\,m\,v_\perp^2 - \frac{G\,M\,m}{r}
\\
E & = & \frac{1}{2}\,m\,v_r^2 + \frac{L^2}{2\,m\,r^2} - \frac{G\,M\,m}{r}
\label{foo}
\end{eqnarray}
where $E$ is the total energy of the orbit, $v_r$ is the radial component of the velocity,
and $L$ is the angular momentum of the orbit.
The radial velocity $v_r$ is exactly zero at aphelion and perihelion.
So set it to zero in equation~(\ref{foo}),
and solve the resulting quadratic equation! It will give two answers,
which are $r_\ap$ and $r_\peri$.
Use the definition of eccentricity
\begin{equation}
e \equiv \frac{r_\ap - r_\peri}{r_\ap + r_\peri}
\end{equation}
to figure out
the relationship between eccentricity $e$ of an elliptical orbit and
the total energy $E$ and the angular momentum $L$.

\paragraph{\problemname~\theproblem:}\refstepcounter{problem}%
\textsl{(a)}
Sketch orbits of fixed semi-major axis but increasing
eccentricity, from a circular orbit, to one that is close to radial
(eccentricity close to unity). Make sure you show the location of
the point around which the object is orbiting!

\textsl{(b)}
What is the transfer time for a radial plunge orbit
from the radius of the Moon's orbit down to the surface of the Earth?
Use the period of the Moon's orbit, the relevant  Kepler's law, and
the properties of the unit-eccentricity and circular orbits.

\textsl{(c)}
Look up the timeline of the Apollo~11 mission, especially
the return to Earth.  Do you see any issues there? What's your best
explanation of what happened?

\paragraph{\problemname~\theproblem:}\refstepcounter{problem}%
\textsl{(a)}
How fast do you have to move with respect to the Earth's surface to
escape Earth's gravity? That is, what is escape velocity from the Earth.
Calculate it yourself in terms of the radius $R$ of the Earth and the
value of $g$ at the surface. Then give it also in $\mps$.

\textsl{(b)} A spaceship of mass $m$ resting on the surface of the
Earth is bound to the Earth but also to the Sun. If we make
the naive (and close to correct) assumption that these energies just
add, what is the total binding energy of the spaceship in the Solar
System? This calculation can be confusing, because although you can assume
the spaceship is stationary with respect to the Earth (so there is
only gravitational potential energy with respect to the Earth), the
spaceship is moving fast relative to the Sun (so there is both
gravitational potential and kinetic energy with respect to the
Sun). The best way to do the calculation is to just pick the Newtonian reference
frame centered on the Sun, and compute the kinetic and potential
energies in that frame. Now what is the escape velocity from the Solar
System? Give your answer in $\mps$.

\textsl{(c)} Look up the derivation of how a rocket accelerates. You
should be able to find a rocket equation that relates the initial mass
of the rocket+fuel, the final mass of the rocket after the fuel is
spent, the speed at which the rocket ejects exhaust, and the final
speed of the rocket. (Hint: The equation is exponential in a mass
ratio.) If the rocket can eject exhaust at 10 times the speed of sound
in air at STP (and that's optimistic!), what is the ratio of initial
mass to final mass of a rocket that will leave the Solar System? What
is the maximum fraction of the spaceship initial mass that can be used
for payload---that is, for cabin, crew, and cargo?

\textsl{(d)} Now imagine the spaceship is going to another planet just
like the Earth. What fraction of the spaceship can be used for
non-fuel payload in this case? The point is that it takes just as much
velocity change to slow down at the end of the journey as it took to
take off at the beginning, and that the end-of-flight fuel is part of
the cargo that the ship has to take with it at launch. You should get
that the payload fraction is (something like) the square of what you got in
the previous part.

\paragraph{Extra Problem (will not be graded for credit):}%
What do you think the above problem means for interstellar travel?

\paragraph{Extra Problem (will not be graded for credit):}%
Make a spreadsheet integration that integrates a test-particle
(low-mass) orbit in the central force law, and show that you do indeed
get an elliptical orbit. You want to use a time step that is $<0.001$
of the period and go for $>1000$ timesteps if you want the integration
to look good! This integration is harder than other integrations you
have done in this class, because you have to project the force onto
the $x$ and $y$ directions correctly. That is, you have to keep track
of both $x$ and $y$ positions, velocities, and accelerations. Do the
problem in the two-dimensional plane of the orbit. If you want
feedback or get stuck, bring your intermediate work to Prof~Hogg for
discussion.

\end{document}


\documentclass[twocolumn,longbibliography]{quantumarticle-customized}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{graphicx}
\usepackage[pdfpagelabels,pdftex,bookmarks,breaklinks]{hyperref}
\usepackage[all]{hypcap}
\hypersetup{colorlinks,citecolor=blue,urlcolor=blue,linkcolor=blue}

\title{Factoring with $n+2$ clean qubits and $n-1$ dirty qubits}
\author{Craig Gidney}
\affiliation{Google, Santa Barbara, CA 93117, USA}
\email{craiggidney@google.com}

\def\sectionautorefname{Section}

\begin{document}
\maketitle

\begin{abstract}
We present reversible classical circuits for performing various arithmetic operations aided by dirty ancillae (i.e. extra bits/qubits in an unknown state that must be restored before the circuit ends).
We improve the number of clean qubits needed to factor an $n$-bit number with Shor's algorithm \cite{Shor1999} from $1.5n + O(1)$ \cite{zalka2006} to $n+2$, assisted by $n-1$ dirty qubits, without increasing the asymptotic size or depth of the circuit.
\end{abstract}

\section{Introduction} \label{sec:introduction}

When constructing quantum circuits, or classical reversible circuits, an important resource is the number of available ancillae.
An ancilla is an extra bit or qubit that is available for use by a circuit as temporary workspace.
Ancillae may be initialized to a known computational basis state (``clean bit"), or be given to the circuit in an unknown and potentially entangled state that must be restored before the circuit finishes (``dirty bit").
Clean bits are more valuable, allowing for simpler and more compact circuit constructions, but dirty bits are more plentiful, since any temporarily unused bit is a borrowable dirty bit.

One part of a circuit can borrow dirty bits from another part of the same circuit, so circuit constructions that require only dirty bits are easier to apply under tight space constraints, or on circuit topologies where other ancillae are too far away to be acquired quickly.
When attempting to reduce the number of bits or qubits required by a circuit, replacing constructions that use clean ancillae with ones that use dirty ancillae is a useful intermediate goal.

It is important to note that, pragmatically speaking, it is far more important to, for example, achieve low T gate counts under plausible architectural constraints than to reduce the number of clean qubits required by a circuit.
Our goal in this paper is not to come up with an implementation of Shor's algorithm optimized in the ways that matter for plausible future quantum computer architectures.
Our goal is to explore the consequences of picking a metric, trying to optimize it, and seeing what ideas fall out.
The circuit constructions we present will not be optimized to achieve good constant factors on circuit depth or gate count (though their asymptotics are fine).
And they will ignore machine architecture; they assume all-to-all connectivity between qubits.
And the {\em total} number of qubits we use ($2n+1$) is higher than previous work.
But interesting ideas don't always come from thinking directly about a problem; there is much to be found by placing artificial goals and seeing where they lead.
That exploration is our intent.
In this paper, we reduce the number of clean qubits required to factor an $n$-bit number with Shor's algorithm from $1.5n + O(1)$ clean qubits \cite{zalka2006} to $n+2$ clean qubits assisted by $n-1$ dirty qubits.
We do so without increasing the asymptotic circuit depth or size.

Our paper is structured as follows.
\autoref{sec:introduction} introduces and describes the conventions our circuit constructions and circuit diagrams will follow.
In \autoref{sec:construct} we describe all the circuit constructions we use to reduce the period finding step of Shor's algorithm into constant-sized gates, while tracking the number of required dirty ancillae.
Then, in \autoref{sec:costs}, we discuss the novelty and comparative costs of the presented circuit constructions.
Finally, \autoref{sec:conclusion} concludes with a discussion of possible future improvements.

All constructions in this paper use a two's-complement representation of integers.
When a result would exceed the size of a register, it wraps (i.e. all the non-modular arithmetic constructions we discuss actually perform arithmetic modulo $2^n$, where $n$ is the size of the target register).

All diagrams order qubits from least significant bit (LSB) at the top to most significant bit (MSB) at the bottom.

All our circuit diagrams annotate operations with the number of clean and/or dirty ancillae they need.
For example, a dashed line from an operation down to a triangle inscribed with ``3 dirty" means that the operation needs 3 dirty ancilla.
If there are 3 unused wires that the operation can borrow, then the triangle will be green and a note of ``(satisfied)" will be written underneath.
If there are not enough unused wires shown in the diagram, the triangle will be yellow.

The ancillae counts shown in diagrams and discussed in the text are not optimal; they are entirely based on what the constructions we discuss in this paper achieve.
Nearly all the circuit constructions we present are classical reversible circuits (i.e. they do not use any quantum operations), so tricks such as the ancilla bootstrap shown in \autoref{fig:bootstrap-ancilla} could cut the ancilla count in several places.
However, none of these improvements decrease the ancillae required at any crucial bottleneck, and so they do not reduce the number of qubits required by our overall construction of Shor's algorithm.

To avoid ambiguity, circuit diagrams will divide multi-register operations into separate parts.
For example, for an addition operation that adds a register $x$ into a register $y$ (i.e. performs $|x\rangle |y\rangle \rightarrow |x\rangle |y + x \pmod{2^n} \rangle$), we will place a light-gray box with the text ``Input A" over the wires corresponding to $x$ and a white box with the text ``+A" over the wires corresponding to $y$.
The ``A" symbol refers to the value of the input register, in the computational basis, at the time of the operation.
Diagrams will often use a sequence of operations each with their own ``Input A" box specific to that operation.
This reuse of ``A" does not indicate any relation between those input values.
The use of ``A" is merely a convention for indicating how the input-indicating box and the effect-indicating box are supposed to combine to form a single operation.

In the case of operations parametrized by compile-time constants, diagrams will use the letters ``K" and/or ``R".
For example, a box showing ``+K (mod R)" refers to the modular-offset operation $|x\rangle \rightarrow |x+K \pmod{R}\rangle$.
We use $R$ to refer to the modulus in modular-arithmetic operations, and to the value that is factored by Shor's algorithm.
In several constructions we assume that $R$ is odd.
Removing factors of 2 from a factoring problem is trivial, so this assumption does not decrease the generality of the overall construction.

Because adding a constant into a register is more expensive than adding one register into another, we avoid ambiguity between the two operations by always referring to the operation that adds a constant as an ``offset operation".
We will refer to the operation that adds one register into another as just ``addition" or, if needed for clarity, ``enregistered addition".

When an operation is controlled by a wire bundle, it is conditioned on all wires in the bundle.
When a single-qubit gate is applied to a wire bundle, the gate applies separately to every wire.
For example, when a NOT gate controlled by one wire bundle is applied to another wire bundle, every wire in the latter is toggled when and only when every wire in the former is on.

For completeness, even when the period finding reduction doesn't require a controlled version of an operation, we nevertheless provide a controllable construction that scales linearly with the number of controls.

For brevity, we take for granted that each circuit's inverse operation is decomposed into the same operations as the original operation but run in reverse order and with each sub-operation inverted.
A decrement is a reversed increment, a multiply-add is a reversed multiply-subtract, a modular division is a reversed modular multiplication, a modular halving is a reversed modular double, and so forth.

We do not attempt to define or implement reasonable behavior for modular arithmetic circuits applied to out of range values (ones equal to or larger than the modulus).
This {\em includes input values}.
For example, if our modular addition construction ($x \mathrel{{+}{=}} y \pmod{R}$) is applied to a $y \geq R$, then we don't guarantee that $y \mod R$ will be added into $x$, that the operation will commute with other additions, that optimizations won't change the behavior, or that anything sensible at all will happen.
If the precondition $y < R$ is violated, what occurs is undefined behavior \cite{c11}.

\section{Constructions} \label{sec:construct}

Our reduction, from the period finding step of Shor's algorithm down to constant-sized gates, uses many circuit constructions.
\autoref{fig:dependencies} shows an overview of the various operations we will use, and the path through them that we will take.

\begin{figure}
  \centering
  \includegraphics[height=17.3cm]{assets/dependencies.png}
  \caption{
    Graph of the transitive reduction of dependencies between constructions in our paper.
    Edge labels indicate which constructions use a dependency more than a constant number of times.
  }
  \label{fig:dependencies}
\end{figure}

\subsection{Period Finding for Modular Exponentiation}

\begin{figure}
  \centering
  \makebox[\linewidth]{
    \includegraphics[width=\linewidth]{assets/shor-period-finding.png}
  }
  \caption{
	High-level definition of the period finding circuit \cite{Shor1999} used by Shor's algorithm.
	$R$ is the modulus and the number to be factored, $B$ is a randomly chosen base, $n$ is the number of bits needed to store $R$, and $p \in \Theta(n)$ controls the precision of the phase estimation step.
    The triangles indicate how many ancillae are needed ``behind the scenes", by our constructions, to perform an operation.
	Recovering the period requires classical post-processing of the sampled output.
  }
  \label{fig:period-finding}
\end{figure}

A high-level view of the circuit for period finding applied to modular exponentiation, the core quantum subroutine of Shor's quantum factoring algorithm \cite{Shor1999}, is shown in \autoref{fig:period-finding}.

Before the quantum circuit is constructed, a base $B$ is chosen at random.
The randomly chosen $B$ must be co-prime to $R$.
When a $B$ that is not co-prime to $R$ is accidentally chosen, the lucky victim can instead factor $R$ by recursively factoring $R_1 = \gcd(B, R)$ and $R_2 = R / \gcd(B, R)$.

The circuit begins by preparing a uniform superposition $|\psi_0\rangle = \sqrt{2^{-n}} \sum_{k=0}^{2^n-1} |k\rangle$, then uses the $\times B^A {\pmod R}$ operation to separate that superposition into equivalence classes modulo the unknown period $l$ of this operation.
That is to say, w.l.o.g. the state ends up equal to $|\psi_{1,x}\rangle = \sqrt{l 2^{-n}} \sum_{k=0}^{\approx (2^n/l)-1} |l k + x \rangle$ for some $x$.
The circuit then applies an inverse Fourier transform to the state.
Fourier transforming a uniform signal with period $l$ produces a spectrum with peaks near $N \cdot 0/l$, $N \cdot 1/l$, $N \cdot 2/l$, ..., $N \cdot (p-1)/l$.
Shor's algorithm recovers the period $l$ by sampling values $s_i$ from this spectrum, then using a continued fractions algorithm to compute the denominator of the fraction (with denominator below $R$) that is closest to $s_i/N$.

Because period-finding measures all qubits immediately after performing a QFT, most of the transformed qubits can be measured earlier than shown.
In fact, each qubit can be measured so early that the next qubit needed for the QFT does not even need to be initialized yet!
Only one of the qubits in the phase-estimation register needs to be present at a time, and so the phase register can be reduced to a single repeatedly-used qubit \cite{zalka1998, mosca1999, parker2000, beauregard2003}.
\autoref{fig:period-finding-solo-phase-qubit} shows a period-finding circuit with this property.
It uses (a) controlled modular multiplication, (b) measurement, (c) X-axis rotations classically parametrized by previous measurements, and (d) qubit resets.
The only non-trivial operation is (a), the controlled modular multiplication of an $n$-qubit register.

We perform modular multiplication with modular scaled-addition operations and an ancilla register as in \cite{beauregard2003}.
However, to allow our ancilla register to be mostly dirty, we extend the operation so that it has a well defined effect on the second register: multiplying by the inverse factor.
We will refer to this combined operation as a ``bimultiply".

The bimultiplications we perform throughout the algorithm do change the value of the ancilla register, but after the usual end of the circuit we can undo the damage.
The key insight is that the work register is initialized to $|1\rangle$ and gets multiplied by constants inverse to the ones trashing the dirty ancilla register.
Instead of discarding the work register after performing phase estimation, as is normally done, we have a use for it.
We measure the work register to recover the fixup factor needed to restore the dirty register's original value.
\autoref{fig:period-finding-solo-phase-qubit-explicit-dirty-register} shows this construction.

Because our modular circuit constructions would have undefined behavior if any register had a value equal to or larger than $R$, we need the ancilla register to contain a value less than $R$.
We ensure this by requiring that the ancilla register's MSB be $|0\rangle$ (i.e. clean) and that the registers be as small as possible (i.e. have size $n = \lceil \lg_2(R) \rceil$).

\begin{figure*}
  \centering
  \makebox[\linewidth]{
    \includegraphics[width=\linewidth]{assets/shor-period-finding-solo-phase-qubit.png}
  }
  \caption{
	Period finding with a single phase-estimation qubit \cite{beauregard2003}.
	The small oplus' ({\tiny $\oplus$}) are ``X-axis controls".
	An X-axis control is equivalent to a normal control, but with a Hadamard gate applied before and after.
	It conditions on the state $\frac{1}{\sqrt 2}|0\rangle - \frac{1}{\sqrt 2}|1\rangle$ instead of on the state $|1\rangle$.
  }
  \label{fig:period-finding-solo-phase-qubit}
\end{figure*}

\begin{figure*}
  \centering
  \makebox[\linewidth]{
    \includegraphics[width=\linewidth]{assets/shor-period-finding-solo-phase-qubit-double-register.png}
  }
  \caption{
	Period finding with a single phase-estimation qubit and paired inverse multiplications (``bimultiplications").
	Uses $O(n^3 \lg n)$ gates, $O(n^3)$ depth, and no additional qubits beyond those shown.
  }
  \label{fig:period-finding-solo-phase-qubit-explicit-dirty-register}
\end{figure*}

\subsection{Modular Bimultiplication}

As in \cite{beauregard2003}, we perform controlled modular multiplication with a second register and modular scaled-addition operations.
However, to allow the second register to be dirty, we use an additional scale-add as well as a negation operation as in \cite{zalka2006}.
See \autoref{fig:controlled-modular-multiply} for the circuit diagram.

To show that the circuit works, suppose that the two registers start in the state $(x, y)$, working modulo $R$.
We scale-add the first register times $K$ into the second register to produce the state $(x, y+xK)$.
Then a scale-subtract times $K^{-1}$ out of the first register puts the system into the state $(x-yK^{-1}-xKK^{-1}, y+xK)$, which is just $(-yK^{-1}, y+xK)$.
Next, we cancel the $y$ term in the second register by scale-adding the first register times $K$ into it again, leaving $(-yK^{-1}, y+xK-yK^{-1} \cdot K)$ which is simply $(-yK^{-1}, xK)$.
Finally, we swap the terms and negate the second term to get $(xK, yK^{-1})$ as desired.

In the case where $K$ has no multiplicative inverse modulo $R$, this construction will not work (it would define an invalid irreversible operation).
However, that would mean $K$ is a factor of $R$; a case that can be checked for and handled classically before bothering to factor $R$ with a quantum computer.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-modular-multiply.png}
  \caption{
    Controlled modular bimultiplication, with a constant multiplier $K$, using three modular scaled-additions and a swap.
    $K$ must have a multiplicative inverse modulo $R$.
    Uses no ancillae, $O(c + n^2 \lg n)$ gates, and $O(c + n^2)$ depth where $c$ is the number of controls and $n$ is the register size.
    The negation operation requires 2 dirty ancillae, but notice there are free wires in the other register that can be borrowed, so the overall construction requires no additional dirty ancilla (for non-trivial $n$).
  }
  \label{fig:controlled-modular-multiply}
\end{figure}

\subsection{Modular Scaled-Addition}

To perform modular scale-add operations, we use a shift-and-add approach similar to \cite{beauregard2003}.
We right-shift (i.e. divide by $2 {\pmod R}$) the target register $n-1$ times, then begin iteratively left-shifting (i.e. multiplying by $2 {\pmod R}$) and adding $K$ into the target.
We condition the first modular addition on the most significant bit of the input, the second addition on the next most significant bit, and so forth.
(The more significant bits go first because their effects must be hit by more left-shifts.)
See \autoref{fig:controlled-modular-scale-accumulate}.

The conditional offset and modular doubling operations need a dirty bit, but for non-trivial $n$ there are more than enough unused bits available to borrow, so the circuit as a whole doesn't require any dirty bits.

Note that the modular doublings (and halvings) require $R$ to be odd, since otherwise the operation would be irreversible.
However, given that in the intended use case $R$ is a number to be factored, it is reasonable to require callers to have factored out multiples of two beforehand.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-modular-multiply-accumulate.png}
  \caption{
    Reducing a controlled modular scale-add, with a constant multiplier $K$, into the modular equivalent of shift-and-add.
    Requires the modulus $R$ to be odd.
    Uses no ancillae, $O(c + n^2 \lg n)$ gates, and $O(c + n^2)$ depth where $c$ is the number of controls and $n$ is the register size.
  }
  \label{fig:controlled-modular-scale-accumulate}
\end{figure}

\subsection{Modular Doubling}

To multiply a register by 2 modulo an odd $R$, we note that the permutation this operation performs is to take the values from $[(R+1)/2, R)$, the top-half of the valid range, and interleave them between the values from $[0, (R+1)/2)$, the bottom-half of the valid range.

We can perform this interleaving by moving the valid-top-half up until it starts at $2^{n-1}$, i.e. aligns with the MSB boundary.
A left-rotate of the register bits then moves the MSB to the LSB, converting the alignment into interleaving.

Because it's expensive to perform an offset that affects values above $R/2$ while leaving values below $R/2$ alone, the circuit shown in \autoref{fig:modular-double} uses a different alignment strategy.
It starts by offset-ing the whole range down by $\lceil R/2 \rceil$, which wraps the valid-bottom-half of the input around to the top of the register's range.
This offset also aligns what was originally the valid-top-half against the bottom of the register range.
Then the circuit uses a controlled offset to move just the top half of the register (including the invalid range above $R$) up by $\lceil R/2 \rceil$, re-wrapping what was originally the valid-bottom-half past the top and around to the middle, aligning it with the MSB boundary.
The circuit then toggles the MSB, fixing the fact that, although the valid-top-half is aligned with 0 and the valid-bottom-half is aligned with $2^{n-1}$, that's exactly the reverse of what we want.
With the desired alignment achieved, the circuit interleaves the two halves with a left-rotate.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-modular-double.png}
  \caption{
    Controlled modular doubling.
    $R$ must be odd.
    Uses 1 dirty ancilla, $O(c + n \lg n)$ gates, and $O(c + n)$ depth, where $c$ is the number of controls and $n$ is the register size.
  }
  \label{fig:modular-double}
\end{figure}

\subsection{Pivot-Flips} \label{sec:pivot-flips}

We will implement both modular negation and modular offset/addition in terms of a non-standard operation we call a ``pivot-flip".
A pivot-flip is an operation that reverses the order of states less than a given pivot value, without affecting other states.
For example, a pivot-flip with the pivot equal to 4 would swap $|0\rangle$ and $|3\rangle$, swap $|1\rangle$ and $|2\rangle$, and leave all other states untouched.

The exact permutation performed by a pivot-flip with pivot equal to $K$ is:

$$\text{PivotFlip}_K = \sum_{i=0}^{K-1} |K-i-1\rangle \langle i| + \sum_{i=K}^{N-1} |i\rangle \langle i|$$

To perform a pivot-flip efficiently, we use the fact that $x \rightarrow \lnot(x - K)$ nearly does what is required: it flips the range below $K$ but unfortunately also flips the range above-and-including $K$.
It's a ``bi-flip".

The bi-flip operation is its own inverse, so it can be ``toggle-controlled''.
If we apply two bi-flips controlled by the same control qubit, then toggling the control qubit determines whether or not a bi-flip is applied to the target register.
When the control qubit stays off, neither bi-flip fires and nothing happens to the target.
When the control qubit stays on, both bi-flips fire and they undo each other.
But if the control qubit is toggled after the first bi-flip but before the second, then exactly one of them will fire and the target register ends up bi-flipped.

Another useful property of a bi-flip is that it doesn't move any states across the pivot.
A bi-flip at $K$ preserves $x<K$ for all $x$.
This allows the toggling of the control qubit, that determines whether a toggle-controlled bi-flip will happen, to be based on a comparison of the pivot against the target register we are operating on.
Even at points where the target may or may not have been bi-flipped.

See \autoref{fig:controlled-pivot-flip} and \autoref{fig:controlled-const-pivot-flip} for the circuit diagrams.
For states that are less than the pivot, the comparison against the pivot keeps toggling the ancilla and exactly one of the controlled bi-flips will fire.
For states equal to or larger than the pivot, the ancilla does not get toggled and so the bi-flips undo each other.
Therefore only the range below the pivot is flipped.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-pivot-flip.png}
  \caption{
    Controlled pivot-flip circuit with an enregistered pivot.
    The target register can be larger than the input register, but not smaller.
    Uses $2$ dirty ancillae, $O(c + m \lg m)$ gates, and $O(c + m)$ depth where $c$ is the number of controls, $n$ is the size of the input register, $e$ is the extra size of the target register, and $m=n+e$ is the size of the target register.
  }
  \label{fig:controlled-pivot-flip}
\end{figure}

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-const-pivot-flip.png}
  \caption{
    Controlled pivot-flip circuit with a constant pivot.
    Uses $2$ dirty ancillae, $O(c + n \lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.
  }
  \label{fig:controlled-const-pivot-flip}
\end{figure}

\subsection{Modular Addition / Offset}

As shown in \autoref{fig:mod-add-from-pivot-flip-bars}, a modular addition can be implemented by three pivot-flips.
To add $K$ into a register modulo $R$, perform pivot-flips with the pivot at $R-K$, then $R$, then $K$.
See \autoref{fig:controlled-modular-add} for the circuit.
(An optimization we don't show is that, because the values above $R$ don't matter, the pivot-flip at $R$ can be replaced by a bi-flip.)

Interestingly, controlled modular addition can borrow its own controls as dirty bits.
For modular offset (i.e. adding a compile-time constant into a register), the two dirty bits are required whether or not the operation is controlled.
See \autoref{fig:controlled-modular-offset}.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/mod-add-from-pivot-flip-bars.png}
  \caption{
     Modular addition of $A \pmod{R}$ can be done with three pivot flips.
     One at $R-A$, then one at $R$, then one at $A$.
     Requires $A \leq R$.
   }
  \label{fig:mod-add-from-pivot-flip-bars}
\end{figure}

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-modular-addition.png}
  \caption{
    Controlled modular addition construction based on pivot-flips.
    The arithmetic being performed on the input register temporarily transitions it from storing $x$ to $R-x$ for the first pivot flip.
    Because $R$ is a compile-time constant, $R+1$ is also a compile-time constant and the $+R+1$ operation is a normal offset operation.
    All arithmetic is two's complement, i.e. modulo $2^n$.
    Uses $2-c$ dirty ancillae, $O(c + n \lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.
  }
  \label{fig:controlled-modular-add}
\end{figure}

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-modular-offset.png}
  \caption{
    Controlled modular offset construction based on pivot-flips.
    Uses $2$ dirty ancillae, $O(c + n \lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.
  }
  \label{fig:controlled-modular-offset}
\end{figure}

\subsection{Modular Negation}

To negate a number mod $R$, we need to reverse the order of the states $|1\rangle$ to $|R-1\rangle$.
We do so by temporarily moving $|0\rangle$ out the way with a decrement, pivot-flipping at $R-1$, then undoing the decrement.
See \autoref{fig:negate-mod}.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/negate-mod.png}
  \caption{
    Controlled modular negation.
    Uses $2$ dirty ancillae, $O(c + n \lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.
  }
  \label{fig:negate-mod}
\end{figure}

\subsection{Comparison}

Comparison operations toggle a target bit based on the relationship between two input registers.
We implement comparisons as in \cite{takahashi2005}, using an addition followed by a slightly smaller subtraction that clears all changes except the overflow signal into the target bit.
See \autoref{fig:compare}.

For comparisons against another register this approach uses $1$ dirty ancilla (if controlled, otherwise no ancillae), $O(c + n)$ gates, and $O(c + n)$ depth.
For comparisons against a constant, the number of gates increases to $O(c + n \lg n)$ and an extra dirty ancilla is required.

When $n$ dirty qubits are available, the overflow-predicting construction from \cite{haner2016} with better constant factors can be used instead.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/comparison-less-const.png}
  \caption{
    Controlled comparison.
    Uses $2$ dirty ancillae, $O(c + n \lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.
  }
  \label{fig:compare}
\end{figure}

\subsection{Addition / Offset}

\cite{takahashi2005} provides a reversible adder circuit that uses $O(n)$ gates, $O(n)$ depth, and no ancillae.
We show an equivalent circuit in \autoref{fig:inlineadder}.

Because the construction in \autoref{fig:inlineadder} uses the input register as workspace, it doesn't work when the input is a compile-time constant or when the target register is larger than the input register.
(When the target register is smaller, we simply ignore the high bits of the input due to overflow wraparound.)
This is a problem for us, because some of our constructions add constants into register (e.g. modular scale-add), and some others add inputs into larger target registers (e.g. comparison).

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/inline-adder.png}
  \caption{ Adder for input and target registers of the same size.
  Requires no ancillae, and uses $O(n)$ gates and depth.
  Based on \cite{van2004, takahashi2005}.}
  \label{fig:inlineadder}
\end{figure}

When the value to be added into a register is a compile-time constant (i.e. when applying an offset gate), we use the offset construction from \cite{haner2016}.
Their offset circuit, shown in \autoref{fig:offset}, uses $O(n \lg n)$ gates, $O(n)$ depth, and one dirty ancilla.

When the target register is larger than the input register, the addition circuit in \autoref{fig:inlineadder} can be modified without increasing the asymptotic cost.
We do this by removing the surrounding CNOTs and adding three increment/decrement operations to the circuit, as follows.
(Note that, to avoid cyclic dependencies, the increment and decrement constructions described in the next subsection will only use the same-register-size adder.)

First, because there are many target bits not reached by the time we have swept through the entire input register, carry signals aren't reaching the high bit of the target register.
We fix this by replacing the innermost CNOT, the carry-propagating CNOT, with a controlled increment.
Second and third, because we're using the MSB of the input register as the carry signal, it causes an increment at the LSB instead of at the correct position.
We undo the LSB increment with a controlled decrement, and use a controlled increment to apply the MSB's effect where it should have actually gone.
See the circuit diagram in \autoref{fig:inline-adder-into-large}.

To control addition gates, and offset gates, we use ``commutator controlling": finding operations $G$ and $H$ such that their group-theory commutator $[G, H] = G \cdot H \cdot G^\dagger \cdot H^\dagger$ equals a desired operation $U$ and either $G$ or $H$ can be efficiently controlled.
In particular, we focus on the case where $G^2 = U$ and $H$ satisfies $H \cdot G \cdot H^\dagger = G^\dagger$ (i.e. framing $G$ with $H$ inverts the effect of $G$).

In the case of addition, we have the property $\lnot (\lnot x + K) = \lnot (-x - 1 + K) = -(-x - 1 + K) - 1 = x-K$.
So a valid inverting operation $H$ for addition is a NOT gate applied to every target wire; $H=X^{\otimes n}$.
If we then consider $G=\text{S}_{\text{-} K}$, where $S$ is an offset-by-subscript operation, we find that $[G, H] = [\text{S}_{-K}, X^{\otimes n}] = \text{S}_{2K}$.
We can control this constructed $\text{S}_{2K}$ operation by adding controls only to the multi-not operation $H$, which is cheap to do.
To add $K$ instead of $2K$, we temporarily prepend a dirty LSB onto the target register.
We show this construction in \autoref{fig:controlled-addition}.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/offset.png}
  \caption{
      Offset circuit from \cite{haner2016}.
      $e$ is either 0 or 1.
      Uses $1$ dirty ancilla, $O(n \lg n)$ gates, and $O(n)$ depth (by overlapping the recursive cases).
  }
  \label{fig:offset}
\end{figure}

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/inline-adder-into-large.png}
  \caption{
      Adder with target larger than source, using no ancillae.
      Uses $O(n)$ gates and depth.
      The increment and decrement gates all have at least one free wire to borrow as a dirty ancilla.
  }
  \label{fig:inline-adder-into-large}
\end{figure}

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-addition.png}
  \caption{
    Reducing controlled addition to uncontrolled addition.
    Uses $O(c + m)$ gates, $O(c + m)$ depth, and a dirty ancilla.
    When applied to offset gates, uses $O(c + m \lg m)$ gates, $O(m + c)$ depth, and two dirty ancillae.
    $c$ is the number of controls, $n$ is the size of the input, and $m > n$ is the size of the target register.
  }
  \label{fig:controlled-addition}
\end{figure}

\subsection{Increment}

A register can be incremented by subtracting both $x$ and $\neg x = -x-1$ from it, for any $x$.
When $n$ dirty bits are available, $x$ can come from a register defined by those $n$ arbitrary bits, as shown in \autoref{fig:increment-many-dirty}.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/increment-many-dirty.png}
  \caption{ Subtracting $x$ and $-x-1$ from a register increments it. Requires $O(n)$ depth and size, and $n$ dirty ancillae.}
  \label{fig:increment-many-dirty}
\end{figure}

To improve from $n$ dirty bits to the single dirty bit used by the circuit in \autoref{fig:controlled-increment-odd}, we break the register into two halves.
A high-half that is incremented only if all of the low bits are on, and a low-half that is unconditionally incremented.

If the increment is uncontrolled, the low-half can be incremented with the double-subtraction trick by borrowing the high-half.
When there are controls, we instead increment the low-half using a commutator-control construction where one operation subtracts the ancilla register out of the target and the other applies a NOT gate to every input wire and target wire.
This works because $\lnot (\lnot T + \lnot K) - K = \lnot (-T - 1 - K - 1) - K = (T+2+K) - 1 - K = T + 1$.

The high-half is trickier to deal with.
We want to borrow the low-half for the double-subtraction trick, but the low-half is being used as a control and so can't be borrowed.
To work around not being able to operate on the borrowed low-half bits while using them as a control, we use more commutator control tricks and some knowledge of what state the low-half must be in if operations it is controlling are firing.

We add and subtract the low-half out of the high-half, but frame the addition with NOT gates controlled by all bits in the low half.
When any of the bits in the low-half are off, the NOT gates don't fire and the addition and subtraction will cancel each other.
When all of the bits in the low-half are on, i.e. when the low-half is storing the two's complement representation of -1, the NOT gates do fire.
This inverts the addition into a subtraction, and the low-half (which is storing -1) is subtracted out of the high-half twice.
Therefore the high-half was incremented by 2.
To halve the +2 into a +1, we prepend a dirty LSB onto the target register.

Recall that, earlier in the paper, we used increments and decrements to implement addition where the target was larger than the input.
To avoid an expensive cyclic dependency in our increment construction, the additions we use must not be larger-target additions.
(Also, when the two registers are not the same size, they define arithmetic modulo different powers of 2.
This breaks properties such as $T + \lnot K = T - K - 1$.)

Because we can only perform additions and subtractions with input and target registers of the same size, the construction described so far in this section only works for odd-sized registers.
To handle even-sized registers, we decompose the increment into a controlled-increment and a NOT gate.
We use the LSB as a control determining whether the (odd-sized) rest of the register is incremented, and then toggle the LSB.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-increment-odd.png}
  \caption{
    Odd-sized controlled increment.
    For the even-sized case, separate the LSB from the rest of the register, increment the rest of the register using the LSB as an extra control, then toggle the LSB.
    Uses $O(c+n)$ gates, $O(c+n)$ depth, and 1 dirty ancilla.
  }
  \label{fig:controlled-increment-odd}
\end{figure}

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/ancilla-bootstrap.png}
  \caption{ Bootstrapping a dirty ancilla out of an increment gate using quantum operations.
  The $i^{\text{frac}}$ gate is a ``phase gradient" operation that phases each computational basis state $|v\rangle$ by an amount proportional to $v/2^d$, where $d$ is the size of the register.
  In this case each state is phased by $e^{i \frac{\pi}{2} v/2^d}$.
  The phase gradient is implemented by a column of $Z^{2^{-k}}$ gates.}
  \label{fig:bootstrap-ancilla}
\end{figure}

\subsection{Bit Swaps, Rotations, and Reversals}

Bit permuting operations can usually be emulated by re-labelling qubits, so they are easy to overlook in circuits.
But some of our circuit diagrams have used controlled bit rotations which require actual gates.
We provide the relevant constructions in \autoref{fig:bit-rotate} and \autoref{fig:bit-reverse}.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-bit-rotate.png}
  \caption{
    A controlled bit rotation / bit swap is three controlled bit-reverses.
    Uses no ancillae, $O(c + n)$ gates, and $O(c + n)$ depth.
  }
  \label{fig:bit-rotate}
\end{figure}

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/controlled-reverse.png}
  \caption{
    Inline controlled bit order reversal on an odd-sized register of size $n=2k+1$, and on an even-sized register of size $n=2k+2$.
    Each XOR operation is a series of independent CNOTs (note that the inputs have opposite endian-ness to the outputs).
    Uses no ancillae, $O(c + n)$ gates, and $O(c + n)$ depth.
  }
  \label{fig:bit-reverse}
\end{figure}

\subsection{Multi-Nots}

Several of our constructions have used CNOTs applied to wire bundles, with many controls and many targets.
A naive approach to implementing these operations would be to apply a separate NOT, each controlled by every control, to every target.
But this would use $O(n \cdot c)$ gates, which is not linear in the number of controls.

To avoid paying the overhead of $c$ controls for every target, we toggle {\em one} target conditioned on all of the controls.
We then use toggle-controlling to spread the toggling effect to all of the other targets.

To efficiently reduce the single remaining CNOT with $c$ controls into constant-sized Toffoli gates, we take advantage of the many available dirty ancilla.
See \autoref{fig:multi-not} and \autoref{fig:cnot-reduction}.

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/multi-cnot-to-single-cnots.png}
  \caption{
    Reducing a many-control many-target CNOT into one many-control single-target CNOT and many single-target single-control CNOTs.
    Uses no ancillae, $O(c + n)$ gates, and $O(c + n)$ depth where $n$ is the number of targets and $c$ is the number of controls.
    The depth can be reduced to $O(c + \lg n)$ by spreading the toggling effect more intelligently.
  }
  \label{fig:multi-not}
\end{figure}

\begin{figure}
  \centering
  \includegraphics[width=\linewidth]{assets/cnot-reduction.png}
  \caption{
    When $c-2$ dirty ancillae are available, a controlled-not with $c$ controls can be reduced into $4c - 8$ Toffoli gates \cite{barenco1995}.
    It is possible to reduce the number of ancilla needed to just one, by using twice as many Toffoli gates, but that construction isn't needed in the context of period finding because there are always enough unused qubits to borrow.
  }
  \label{fig:cnot-reduction}
\end{figure}

\section{Overview and Improvements} \label{sec:costs}

\begin{figure*}
  \centering
  \makebox[\linewidth]{
    \begin{tabular}{ l | c c c c c l }
       & Year & Depth & Gates & Clean Qubits & Total Qubits \\
      \hline
      Shor \cite{Shor1999} & 1994 & $\Theta(n M(n))$ & $\Theta(n M(n))$ & $\Theta(n)$ & $\Theta(n)$ \\
      Beckman et al. \cite{beckman1996} & 1996 & $\Theta(n^3)$ & $\Theta(n^3)$ & $5n + 1$ & $5n + 1$ \\
      Veldral et al. \cite{vedral1996} & 1996 & $\Theta(n^3)$ & $\Theta(n^3)$ & $4n + 3$ & $4n + 3$ \\
      Beauregard \cite{beauregard2003} & 2003 & $\Theta(n^3 \lg \frac{1}{\varepsilon})$ & $\Theta(n^3 \lg \frac{n}{\varepsilon} \lg \frac{1}{\varepsilon})$ & $2n+3$ & $2n+3$ \\
      Takahashi et al. \cite{takahashi2006} & 2006 & $\Theta(n^3 \lg \frac{1}{\varepsilon})$ & $\Theta(n^3 \lg \frac{n}{\varepsilon} \lg \frac{1}{\varepsilon})$ & $2n+2$ & $2n+2$ \\
      Zalka \cite{zalka2006} & 2006 & $\Theta(n^3 \lg \frac{1}{\varepsilon})$ & $\Theta(n^3 \lg \frac{n}{\varepsilon} \lg \frac{1}{\varepsilon})$ & $1.5n+O(1)$ & $1.5n+O(1)$ \\
      H\"{a}ner et al. \cite{haner2016} & 2016 & $\Theta(n^3)$ & $\Theta(n^3 \lg n)$ & $2n+2$ & $2n+2$ \\
      (ours) & 2017 & $\Theta(n^3)$ & $\Theta(n^3 \lg n)$ & $n+2$ & $2n+1$ \\
    \end{tabular}
  }
  \caption{
    Space-efficient constructions of Shor's algorithm over time.
    The table only includes papers that presented explicit circuit constructions and improved the minimum number of qubits required to perform the algorithm (or else the time complexity at a slightly larger qubit count).
    $M(n)$ is the classical time-complexity of multiplication, which is known to be asymptotically at most $n \cdot (\lg n) \cdot 2^{O(\lg^* n)}$ \cite{furer2007}.
    $\varepsilon$ is the maximum error when synthesizing the circuit out of a fixed set of universal gates, which is asymptotically relevant for algorithms that use Draper addition \cite{draper2000} (i.e. applying phase gradients in frequency space) instead of Toffoli-based addition/offset constructions.
  }
  \label{fig:table-over-time}
\end{figure*}

Recall that \autoref{fig:dependencies} shows a dependency graph of the constructions discussed in this paper.
Our asymptotic costs are dominated by performing $O(n)$ modular multiplications, each of which uses $O(n)$ modular additions and offsets, each of which uses $O(n \lg n)$ constant-sized classical gates \cite{haner2016} and $O(n)$ depth.
The total cost of the period-finding step in Shor's algorithm, using our construction, is $O(n^3 \lg n)$ gates and $O(n^3)$ depth.

In \autoref{fig:table-over-time} we show how the number of qubits needed for Shor's algorithm has improved over time.
Our main improvements over previous arithmetic constructions are 1) the use of pivot-flips for modular addition, 2) the use of dirty bimultiplication for modular multiplication, and 3) the $O(n)$ incrementer requiring only a single dirty ancilla.

Previous modular addition constructions worked by temporarily storing an is-wraparound-needed comparison in a clean ancilla \cite{takahashi2006, haner2016}.
Pivot flips also require ancillae, but the ancillae can be dirty and, in the context of Shor's algorithm, there are always qubits available to borrow whenever a pivot-flip is needed.
This improvement ends up saving a qubit, reducing the total number of qubits we would have needed from $2n+2$ as in \cite{haner2016} to $2n+1$.

Previous modular multiplication constructions did not work with a dirty ancilla register.
They either required a clean ancilla register because they leaked the ancilla register into the work register \cite{haner2016}, or else a trashable ancilla register because there was no way to undo the damage being done by the multiplications \cite{zalka2006}.
The leakage problem is fixed by adding an extra scale-add operation and a negation operation \cite{zalka2006}.
We fixed the trashing problem by measuring the work register at the end of the circuit, and using its value to drive a clean-up multiplication that restores the ancilla register.
This improvement allows $n-1$ of the qubits in the ancilla register to be dirty.
The MSB has to stay clean to ensure the register's value is less than the modulus being factored.

Previous published incrementers (not counting an unpublished version of our construction being cited by \cite{haner2016}) required either $O(n^2)$ gates or $\omega(1)$ ancillae \cite{draper2000, barenco1995}.
Our classical incrementer construction uses $O(n)$ gates and a single dirty ancilla.

Note that, for classical reversible computation, 1 dirty ancilla is the minimum possible for an incrementer.
An increment operation on $n$ bits is equivalent to performing a state-permutation that uses $2^n-1$ swaps to sweep the state $|2^n-1\rangle$ from the top of the state-space to the bottom of the state-space one step at a time.
Note that $2^n-1$ is odd for non-trivial $n$, and therefore the parity of the state permutation performed by an increment operation is odd.
However, the parity of the permutation performed by any classical gate that doesn't cover the entire circuit is even.
Since odd-parity permutations can't be implemented by composing even-parity permutations, it is impossible to compose smaller operations into an increment operation that covers every bit.
An uncovered bit (i.e. a dirty ancilla) must be present.

When quantum operations are available, the parity barrier can be bypassed and incrementing can be performed without any ancilla.
The asymptotic cost is slightly worse due to the cost of synthesizing tiny rotations, and the constant factors hidden by the asymptotic notation are also worse.
See \autoref{fig:bootstrap-ancilla} for the construction.

We used \href{https://github.com/Strilanc/Quirk}{Quirk} \cite{quirk2016} to explore \cite{victor2013}, check, and refine individual constructions.
The full construction down to Toffoli gates was tested in \href{https://github.com/ProjectQ-Framework/ProjectQ}{ProjectQ} \cite{projq2016}.
The python source code for our test implementation, and an issue tracker for submitting errata, can be found online at \href{https://github.com/Strilanc/PaperImpl-2017-DirtyPeriodFinding}{https://github.com/Strilanc/PaperImpl-2017-DirtyPeriodFinding}.

Although the asymptotic costs of our constructions match previous work, the constant factors are significantly worse.
For example, our equivalent of a controlled 32-qubit multiplication uses roughly 1.3 million Toffoli gates (the specific number depends on the factor to multiply by, the modulus, whether or not a number of optimizations are used, and whether or not those optimizations apply to a given case).
This cost is over an order of magnitude worse than previous work \cite{haner2016}.
The reason for the increased cost is that using dirty ancillae results in more uncomputation work, in repeating some operations twice conditionally to do them once unconditionally, and in less efficient constructions in general.
These inefficiencies stack multiplicatively when one construction uses another as a subroutine.

\section{Future Work and Conclusion} \label{sec:conclusion}

In this paper we described how to perform various arithmetic operations using only dirty ancilla.
We also described various techniques we used to find the constructions: pivot flipping, toggle controlling, commutator controlling, and exploration by directly manipulating circuit diagrams.
We showed how these constructions reduce the number of clean qubits required to perform Shor's algorithm from $1.5n+O(1)$ to $n+2$.

Of the $2n+1$ qubits our period-finding construction requires, $1$ is used for the phase estimation qubit, $n$ are used to store the work register, and $n$ are ancillae used to implement modular multiplication in terms of scaled modular addition.
Except for multiplication, all our arithmetic constructions use two or fewer dirty ancillae.
Since we reduce modular scale-addition into operations that have a $\Theta(n)$ surplus of unused qubits, in context there are always more than enough dirty ancillae available to implement the simpler arithmetic inline.
Because there is slack in the simpler arithmetic constructions, improving the overall number of qubits used by Shor's algorithm requires only that we improve the first step of reducing modular multiplication into some other operation.

One way we could reduce modular multiplication into better operations is by knowing the factorization $p \cdot q$ of the modulus $R$, with $p$ and $q$ each having size $\approx n/2$.
The Chinese remainder theorem guarantees that $x \mod R$ could be uniquely represented as the pair of half-sized values $(x \mod p, x \mod q)$.
Multiplications of the half-sized values could use and reuse the same half-sized ancilla register, for a total of three half-sized registers (one for $x \mod p$, one for $x \mod q$, and one hopefully-dirty ancilla register).
Despite the large reduction in the number of ancillae available to the underlying arithmetic operations, each operation would still have more than enough ancillae and contribute no additional ancillae to the overall circuit.
(Note: because the initial value $x_0 = 1$ is trivial, and the final value is measured or discarded, it's not necessary to implement circuits that translate between the Chinese-remainder representation and the usual 2s-complement representation.)
Of course, since we use Shor's algorithm to compute the factorization of $R$, using the factorization of $R$ to optimize Shor's algorithm would be paradoxical.
The $1.5n$ achieved in \cite{zalka2006} was done via this kind of method, except that instead of factoring $R$ Zalka factored the value to multiply by and the factoring was done modulo $R$ (by stopping a generalized gcd at a midway point) instead of in $\mathbb{Z}$.

A second way to reduce modular multiplication into (slightly) smaller operations could be with commutator control.
Note that the modular Fourier transform inverts the effect of modular multiplication: $QFT_{R} \cdot (\times K \,\text{mod}\, R) \cdot QFT_R^{-1} = (\times K^{-1} \,\text{mod}\, R)$.
This has two useful high-level effects.
First, by applying the bimultiplication gate used in this paper twice, but inverting the effect on the ancilla register for the second application, we can build a proper modular multiplication gate that only affects a single register.
Second, we can use commutator control to move controls from the modular multiplication gate onto modular Fourier transform gates.
Assuming controlled modular QFTs can be performed with fewer ancillae than controlled modular multiplication, we could save a qubit when performing the modular multiplication by borrowing the control qubit.

Possible future improvements aside, in this paper we showed that the number of clean qubits sufficient to perform Shor's algorithm is no more than $n + O(1)$.
We consider this to be a step towards a construction for Shor's algorithm that uses only $n + O(1)$ qubits total.
We do note, however, that these improvements are of more theoretical than practical interest.
In practice, on error corrected quantum computers, the important cost to optimize is the number of T gates.
In that sense, the main {\em practical} contribution of this paper is the improved increment circuit and the demonstration of constructing circuits under tight space constraints.

\section{Acknowledgements}

We thank Matthew Neeley, Dave Bacon, and Austin Fowler for comments on earlier versions of this paper, from which it greatly benefited.

\bibliographystyle{plain}
\bibliography{citations}

\end{document}