<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>tommath.tex</title>
<style type="text/css">
.enscript-comment { font-style: italic; color: rgb(178,34,34); }
.enscript-function-name { font-weight: bold; color: rgb(0,0,255); }
.enscript-variable-name { font-weight: bold; color: rgb(184,134,11); }
.enscript-keyword { font-weight: bold; color: rgb(160,32,240); }
.enscript-reference { font-weight: bold; color: rgb(95,158,160); }
.enscript-string { font-weight: bold; color: rgb(188,143,143); }
.enscript-builtin { font-weight: bold; color: rgb(218,112,214); }
.enscript-type { font-weight: bold; color: rgb(34,139,34); }
.enscript-highlight { text-decoration: underline; color: 0; }
</style>
</head>
<body id="top">
<h1 style="margin:8px;" id="f1">tommath.tex&nbsp;&nbsp;&nbsp;<span style="font-weight: normal; font-size: 0.5em;">[<a href="tommath.tex">plain text</a>]</span></h1>
<hr/>
<div></div>
<pre>
<span class="enscript-keyword">\documentclass</span>[b5paper]{book}
<span class="enscript-keyword">\usepackage</span>{hyperref}
<span class="enscript-keyword">\usepackage</span>{makeidx}
<span class="enscript-keyword">\usepackage</span>{amssymb}
<span class="enscript-keyword">\usepackage</span>{color}
<span class="enscript-keyword">\usepackage</span>{alltt}
<span class="enscript-keyword">\usepackage</span>{graphicx}
<span class="enscript-keyword">\usepackage</span>{layout}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\union</span>{<span class="enscript-keyword">\cup</span>}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\intersect</span>{<span class="enscript-keyword">\cap</span>}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\getsrandom</span>{<span class="enscript-keyword">\stackrel</span>{<span class="enscript-keyword">\rm</span> R}{<span class="enscript-keyword">\gets</span>}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\cross</span>{<span class="enscript-keyword">\times</span>}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\cat</span>{<span class="enscript-keyword">\hspace</span>{0.5em} <span class="enscript-keyword">\|</span> <span class="enscript-keyword">\hspace</span>{0.5em}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\catn</span>{<span class="enscript-variable-name">$\|$</span>}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\divides</span>{<span class="enscript-keyword">\hspace</span>{0.3em} | <span class="enscript-keyword">\hspace</span>{0.3em}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\nequiv</span>{<span class="enscript-keyword">\not</span><span class="enscript-keyword">\equiv</span>}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\approx</span>{<span class="enscript-keyword">\raisebox</span>{0.2ex}{<span class="enscript-keyword">\mbox</span>{<span class="enscript-keyword">\small</span> <span class="enscript-variable-name">$\sim$</span>}}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\lcm</span>{{<span class="enscript-keyword">\rm</span> lcm}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\gcd</span>{{<span class="enscript-keyword">\rm</span> gcd}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\log</span>{{<span class="enscript-keyword">\rm</span> log}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\ord</span>{{<span class="enscript-keyword">\rm</span> ord}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\abs</span>{{<span class="enscript-keyword">\mathit</span> abs}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\rep</span>{{<span class="enscript-keyword">\mathit</span> rep}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\mod</span>{{<span class="enscript-keyword">\mathit</span><span class="enscript-keyword">\ </span>mod<span class="enscript-keyword">\ </span>}}
<span class="enscript-keyword">\renewcommand</span>{<span class="enscript-keyword">\pmod</span>}[1]{<span class="enscript-keyword">\ </span>({<span class="enscript-keyword">\rm</span> mod<span class="enscript-keyword">\ </span>}{#1})}
<span class="enscript-keyword">\newcommand</span>{<span class="enscript-keyword">\floor</span>}[1]{<span class="enscript-keyword">\left</span><span class="enscript-keyword">\lfloor</span>{#1}<span class="enscript-keyword">\right</span><span class="enscript-keyword">\rfloor</span>}
<span class="enscript-keyword">\newcommand</span>{<span class="enscript-keyword">\ceil</span>}[1]{<span class="enscript-keyword">\left</span><span class="enscript-keyword">\lceil</span>{#1}<span class="enscript-keyword">\right</span><span class="enscript-keyword">\rceil</span>}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\Or</span>{{<span class="enscript-keyword">\rm</span><span class="enscript-keyword">\ </span>or<span class="enscript-keyword">\ </span>}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\And</span>{{<span class="enscript-keyword">\rm</span><span class="enscript-keyword">\ </span>and<span class="enscript-keyword">\ </span>}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\iff</span>{<span class="enscript-keyword">\hspace</span>{1em}<span class="enscript-keyword">\Longleftrightarrow</span><span class="enscript-keyword">\hspace</span>{1em}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\implies</span>{<span class="enscript-keyword">\Rightarrow</span>}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\undefined</span>{{<span class="enscript-keyword">\rm</span> ``undefined&quot;}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\Proof</span>{<span class="enscript-keyword">\vspace</span>{1ex}<span class="enscript-keyword">\noindent</span> {<span class="enscript-keyword">\bf</span> Proof:}<span class="enscript-keyword">\hspace</span>{1em}}
<span class="enscript-keyword">\let</span><span class="enscript-keyword">\oldphi</span><span class="enscript-keyword">\phi</span>
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\phi</span>{<span class="enscript-keyword">\varphi</span>}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\Pr</span>{{<span class="enscript-keyword">\rm</span> Pr}}
<span class="enscript-keyword">\newcommand</span>{<span class="enscript-keyword">\str</span>}[1]{{<span class="enscript-keyword">\mathbf</span>{#1}}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\F</span>{{<span class="enscript-keyword">\mathbb</span> F}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\N</span>{{<span class="enscript-keyword">\mathbb</span> N}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\Z</span>{{<span class="enscript-keyword">\mathbb</span> Z}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\R</span>{{<span class="enscript-keyword">\mathbb</span> R}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\C</span>{{<span class="enscript-keyword">\mathbb</span> C}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\Q</span>{{<span class="enscript-keyword">\mathbb</span> Q}}
<span class="enscript-keyword">\definecolor</span>{DGray}{gray}{0.5}
<span class="enscript-keyword">\newcommand</span>{<span class="enscript-keyword">\emailaddr</span>}[1]{<span class="enscript-keyword">\mbox</span>{<span class="enscript-variable-name">$&lt;$</span>{#1}<span class="enscript-variable-name">$&gt;$</span>}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\twiddle</span>{<span class="enscript-keyword">\raisebox</span>{0.3ex}{<span class="enscript-keyword">\mbox</span>{<span class="enscript-keyword">\tiny</span> <span class="enscript-variable-name">$\sim$</span>}}}
<span class="enscript-keyword">\def</span><span class="enscript-keyword">\gap</span>{<span class="enscript-keyword">\vspace</span>{0.5ex}}
<span class="enscript-keyword">\makeindex</span>
<span class="enscript-keyword">\begin</span>{document}
<span class="enscript-keyword">\frontmatter</span>
<span class="enscript-keyword">\pagestyle</span>{empty}
<span class="enscript-keyword">\title</span>{Multi--Precision Math}
<span class="enscript-keyword">\author</span>{<span class="enscript-keyword">\mbox</span>{
<span class="enscript-comment">%\begin{small}
</span><span class="enscript-keyword">\begin</span>{tabular}{c}
Tom St Denis <span class="enscript-keyword">\\</span>
Algonquin College <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Mads Rasmussen <span class="enscript-keyword">\\</span>
Open Communications Security <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Greg Rose <span class="enscript-keyword">\\</span>
QUALCOMM Australia <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-comment">%\end{small}
</span>}
}
<span class="enscript-keyword">\maketitle</span>
This text has been placed in the public domain.  This text corresponds to the v0.39 release of the 
LibTomMath project.

<span class="enscript-keyword">\begin</span>{alltt}
Tom St Denis
111 Banning Rd
Ottawa, Ontario
K2L 1C3
Canada

Phone: 1-613-836-3160
Email: <a href="mailto:tomstdenis@gmail.com">tomstdenis@gmail.com</a>
<span class="enscript-keyword">\end</span>{alltt}

This text is formatted to the international B5 paper size of 176mm wide by 250mm tall using the <span class="enscript-keyword">\LaTeX</span>{} 
{<span class="enscript-keyword">\em</span> book} macro package and the Perl {<span class="enscript-keyword">\em</span> booker} package.

<span class="enscript-keyword">\tableofcontents</span>
<span class="enscript-keyword">\listoffigures</span>
<span class="enscript-keyword">\chapter</span>*{Prefaces}
When I tell people about my LibTom projects and that I release them as public domain they are often puzzled.  
They ask why I did it and especially why I continue to work on them for free.  The best I can explain it is ``Because I can.''  
Which seems odd and perhaps too terse for adult conversation. I often qualify it with ``I am able, I am willing.'' which 
perhaps explains it better.  I am the first to admit there is not anything that special with what I have done.  Perhaps
others can see that too and then we would have a society to be proud of.  My LibTom projects are what I am doing to give 
back to society in the form of tools and knowledge that can help others in their endeavours.

I started writing this book because it was the most logical task to further my goal of open academia.  The LibTomMath source
code itself was written to be easy to follow and learn from.  There are times, however, where pure C source code does not
explain the algorithms properly.  Hence this book.  The book literally starts with the foundation of the library and works
itself outwards to the more complicated algorithms.  The use of both pseudo--code and verbatim source code provides a duality
of ``theory'' and ``practice'' that the computer science students of the world shall appreciate.  I never deviate too far
from relatively straightforward algebra and I hope that this book can be a valuable learning asset.

This book and indeed much of the LibTom projects would not exist in their current form if it was not for a plethora
of kind people donating their time, resources and kind words to help support my work.  Writing a text of significant
length (along with the source code) is a tiresome and lengthy process.  Currently the LibTom project is four years old,
comprises of literally thousands of users and over 100,000 lines of source code, TeX and other material.  People like Mads and Greg 
were there at the beginning to encourage me to work well.  It is amazing how timely validation from others can boost morale to 
continue the project. Definitely my parents were there for me by providing room and board during the many months of work in 2003.  

To my many friends whom I have met through the years I thank you for the good times and the words of encouragement.  I hope I
honour your kind gestures with this project.

Open Source.  Open Academia.  Open Minds.

<span class="enscript-keyword">\begin</span>{flushright} Tom St Denis <span class="enscript-keyword">\end</span>{flushright}

<span class="enscript-keyword">\newpage</span>
I found the opportunity to work with Tom appealing for several reasons, not only could I broaden my own horizons, but also 
contribute to educate others facing the problem of having to handle big number mathematical calculations.

This book is Tom's child and he has been caring and fostering the project ever since the beginning with a clear mind of 
how he wanted the project to turn out. I have helped by proofreading the text and we have had several discussions about 
the layout and language used.

I hold a masters degree in cryptography from the University of Southern Denmark and have always been interested in the 
practical aspects of cryptography. 

Having worked in the security consultancy business for several years in S<span class="enscript-keyword">\~</span>{a}o Paulo, Brazil, I have been in touch with a 
great deal of work in which multiple precision mathematics was needed. Understanding the possibilities for speeding up 
multiple precision calculations is often very important since we deal with outdated machine architecture where modular 
reductions, for example, become painfully slow.

This text is for people who stop and wonder when first examining algorithms such as RSA for the first time and asks 
themselves, ``You tell me this is only secure for large numbers, fine; but how do you implement these numbers?''

<span class="enscript-keyword">\begin</span>{flushright}
Mads Rasmussen

S<span class="enscript-keyword">\~</span>{a}o Paulo - SP

Brazil
<span class="enscript-keyword">\end</span>{flushright}

<span class="enscript-keyword">\newpage</span>
It's all because I broke my leg. That just happened to be at about the same time that Tom asked for someone to review the section of the book about 
Karatsuba multiplication. I was laid up, alone and immobile, and thought ``Why not?'' I vaguely knew what Karatsuba multiplication was, but not 
really, so I thought I could help, learn, and stop myself from watching daytime cable TV, all at once.

At the time of writing this, I've still not met Tom or Mads in meatspace. I've been following Tom's progress since his first splash on the 
sci.crypt Usenet news group. I watched him go from a clueless newbie, to the cryptographic equivalent of a reformed smoker, to a real
contributor to the field, over a period of about two years. I've been impressed with his obvious intelligence, and astounded by his productivity. 
Of course, he's young enough to be my own child, so he doesn't have my problems with staying awake.

When I reviewed that single section of the book, in its very earliest form, I was very pleasantly surprised. So I decided to collaborate more fully, 
and at least review all of it, and perhaps write some bits too. There's still a long way to go with it, and I have watched a number of close 
friends go through the mill of publication, so I think that the way to go is longer than Tom thinks it is. Nevertheless, it's a good effort, 
and I'm pleased to be involved with it.

<span class="enscript-keyword">\begin</span>{flushright}
Greg Rose, Sydney, Australia, June 2003. 
<span class="enscript-keyword">\end</span>{flushright}

<span class="enscript-keyword">\mainmatter</span>
<span class="enscript-keyword">\pagestyle</span>{headings}
<span class="enscript-keyword">\chapter</span>{Introduction}
<span class="enscript-keyword">\section</span>{Multiple Precision Arithmetic}

<span class="enscript-keyword">\subsection</span>{What is Multiple Precision Arithmetic?}
When we think of long-hand arithmetic such as addition or multiplication we rarely consider the fact that we instinctively
raise or lower the precision of the numbers we are dealing with.  For example, in decimal we almost immediate can 
reason that <span class="enscript-variable-name">$7$</span> times <span class="enscript-variable-name">$6$</span> is <span class="enscript-variable-name">$42$</span>.  However, <span class="enscript-variable-name">$42$</span> has two digits of precision as opposed to one digit we started with.  
Further multiplications of say <span class="enscript-variable-name">$3$</span> result in a larger precision result <span class="enscript-variable-name">$126$</span>.  In these few examples we have multiple 
precisions for the numbers we are working with.  Despite the various levels of precision a single subset<span class="enscript-keyword">\footnote</span>{With the occasional optimization.}
 of algorithms can be designed to accomodate them.  

By way of comparison a fixed or single precision operation would lose precision on various operations.  For example, in
the decimal system with fixed precision <span class="enscript-variable-name">$6 \cdot 7 = 2$</span>.

Essentially at the heart of computer based multiple precision arithmetic are the same long-hand algorithms taught in
schools to manually add, subtract, multiply and divide.  

<span class="enscript-keyword">\subsection</span>{The Need for Multiple Precision Arithmetic}
The most prevalent need for multiple precision arithmetic, often referred to as ``bignum'' math, is within the implementation
of public-key cryptography algorithms.   Algorithms such as RSA <span class="enscript-keyword">\cite</span>{RSAREF} and Diffie-Hellman <span class="enscript-keyword">\cite</span>{DHREF} require 
integers of significant magnitude to resist known cryptanalytic attacks.  For example, at the time of this writing a 
typical RSA modulus would be at least greater than <span class="enscript-variable-name">$10^{309}$</span>.  However, modern programming languages such as ISO C <span class="enscript-keyword">\cite</span>{ISOC} and 
Java <span class="enscript-keyword">\cite</span>{JAVA} only provide instrinsic support for integers which are relatively small and single precision.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|r|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Data Type} &amp; <span class="enscript-keyword">\textbf</span>{Range} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> char  &amp; <span class="enscript-variable-name">$-128 \ldots 127$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> short &amp; <span class="enscript-variable-name">$-32768 \ldots 32767$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> long  &amp; <span class="enscript-variable-name">$-2147483648 \ldots 2147483647$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> long long &amp; <span class="enscript-variable-name">$-9223372036854775808 \ldots 9223372036854775807$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Typical Data Types for the C Programming Language}
<span class="enscript-keyword">\label</span>{fig:ISOC}
<span class="enscript-keyword">\end</span>{figure}

The largest data type guaranteed to be provided by the ISO C programming 
language<span class="enscript-keyword">\footnote</span>{As per the ISO C standard.  However, each compiler vendor is allowed to augment the precision as they 
see fit.}  can only represent values up to <span class="enscript-variable-name">$10^{19}$</span> as shown in figure <span class="enscript-keyword">\ref</span>{fig:ISOC}. On its own the C language is 
insufficient to accomodate the magnitude required for the problem at hand.  An RSA modulus of magnitude <span class="enscript-variable-name">$10^{19}$</span> could be 
trivially factored<span class="enscript-keyword">\footnote</span>{A Pollard-Rho factoring would take only <span class="enscript-variable-name">$2^{16}$</span> time.} on the average desktop computer, 
rendering any protocol based on the algorithm insecure.  Multiple precision algorithms solve this very problem by 
extending the range of representable integers while using single precision data types.

Most advancements in fast multiple precision arithmetic stem from the need for faster and more efficient cryptographic 
primitives.  Faster modular reduction and exponentiation algorithms such as Barrett's algorithm, which have appeared in 
various cryptographic journals, can render algorithms such as RSA and Diffie-Hellman more efficient.  In fact, several 
major companies such as RSA Security, Certicom and Entrust have built entire product lines on the implementation and 
deployment of efficient algorithms.

However, cryptography is not the only field of study that can benefit from fast multiple precision integer routines.  
Another auxiliary use of multiple precision integers is high precision floating point data types.  
The basic IEEE <span class="enscript-keyword">\cite</span>{IEEE} standard floating point type is made up of an integer mantissa <span class="enscript-variable-name">$q$</span>, an exponent <span class="enscript-variable-name">$e$</span> and a sign bit <span class="enscript-variable-name">$s$</span>.  
Numbers are given in the form <span class="enscript-variable-name">$n = q \cdot b^e \cdot -1^s$</span> where <span class="enscript-variable-name">$b = 2$</span> is the most common base for IEEE.  Since IEEE 
floating point is meant to be implemented in hardware the precision of the mantissa is often fairly small 
(<span class="enscript-keyword">\textit</span>{23, 48 and 64 bits}).  The mantissa is merely an integer and a multiple precision integer could be used to create
a mantissa of much larger precision than hardware alone can efficiently support.  This approach could be useful where 
scientific applications must minimize the total output error over long calculations.

Yet another use for large integers is within arithmetic on polynomials of large characteristic (i.e. <span class="enscript-variable-name">$GF(p)[x]$</span> for large <span class="enscript-variable-name">$p$</span>).
In fact the library discussed within this text has already been used to form a polynomial basis library<span class="enscript-keyword">\footnote</span>{See <span class="enscript-keyword">\url</span>{<a href="http://poly.libtomcrypt.org">http://poly.libtomcrypt.org</a>} for more details.}.

<span class="enscript-keyword">\subsection</span>{Benefits of Multiple Precision Arithmetic}
<span class="enscript-keyword">\index</span>{precision}
The benefit of multiple precision representations over single or fixed precision representations is that 
no precision is lost while representing the result of an operation which requires excess precision.  For example, 
the product of two <span class="enscript-variable-name">$n$</span>-bit integers requires at least <span class="enscript-variable-name">$2n$</span> bits of precision to be represented faithfully.  A multiple 
precision algorithm would augment the precision of the destination to accomodate the result while a single precision system 
would truncate excess bits to maintain a fixed level of precision.

It is possible to implement algorithms which require large integers with fixed precision algorithms.  For example, elliptic
curve cryptography (<span class="enscript-keyword">\textit</span>{ECC}) is often implemented on smartcards by fixing the precision of the integers to the maximum 
size the system will ever need.  Such an approach can lead to vastly simpler algorithms which can accomodate the 
integers required even if the host platform cannot natively accomodate them<span class="enscript-keyword">\footnote</span>{For example, the average smartcard 
processor has an 8 bit accumulator.}.  However, as efficient as such an approach may be, the resulting source code is not
normally very flexible.  It cannot, at runtime, accomodate inputs of higher magnitude than the designer anticipated.

Multiple precision algorithms have the most overhead of any style of arithmetic.  For the the most part the 
overhead can be kept to a minimum with careful planning, but overall, it is not well suited for most memory starved
platforms.  However, multiple precision algorithms do offer the most flexibility in terms of the magnitude of the 
inputs.  That is, the same algorithms based on multiple precision integers can accomodate any reasonable size input 
without the designer's explicit forethought.  This leads to lower cost of ownership for the code as it only has to 
be written and tested once.

<span class="enscript-keyword">\section</span>{Purpose of This Text}
The purpose of this text is to instruct the reader regarding how to implement efficient multiple precision algorithms.  
That is to not only explain a limited subset of the core theory behind the algorithms but also the various ``house keeping'' 
elements that are neglected by authors of other texts on the subject.  Several well reknowned texts <span class="enscript-keyword">\cite</span>{TAOCPV2,HAC} 
give considerably detailed explanations of the theoretical aspects of algorithms and often very little information 
regarding the practical implementation aspects.  

In most cases how an algorithm is explained and how it is actually implemented are two very different concepts.  For 
example, the Handbook of Applied Cryptography (<span class="enscript-keyword">\textit</span>{HAC}), algorithm 14.7 on page 594, gives a relatively simple 
algorithm for performing multiple precision integer addition.  However, the description lacks any discussion concerning 
the fact that the two integer inputs may be of differing magnitudes.  As a result the implementation is not as simple
as the text would lead people to believe.  Similarly the division routine (<span class="enscript-keyword">\textit</span>{algorithm 14.20, pp. 598}) does not 
discuss how to handle sign or handle the dividend's decreasing magnitude in the main loop (<span class="enscript-keyword">\textit</span>{step <span class="enscript-keyword">\#</span>3}).

Both texts also do not discuss several key optimal algorithms required such as ``Comba'' and Karatsuba multipliers 
and fast modular inversion, which we consider practical oversights.  These optimal algorithms are vital to achieve 
any form of useful performance in non-trivial applications.  

To solve this problem the focus of this text is on the practical aspects of implementing a multiple precision integer
package.  As a case study the ``LibTomMath''<span class="enscript-keyword">\footnote</span>{Available at <span class="enscript-keyword">\url</span>{<a href="http://math.libtomcrypt.com">http://math.libtomcrypt.com</a>}} package is used 
to demonstrate algorithms with real implementations<span class="enscript-keyword">\footnote</span>{In the ISO C programming language.} that have been field 
tested and work very well.  The LibTomMath library is freely available on the Internet for all uses and this text 
discusses a very large portion of the inner workings of the library.

The algorithms that are presented will always include at least one ``pseudo-code'' description followed 
by the actual C source code that implements the algorithm.  The pseudo-code can be used to implement the same 
algorithm in other programming languages as the reader sees fit.  

This text shall also serve as a walkthrough of the creation of multiple precision algorithms from scratch.  Showing
the reader how the algorithms fit together as well as where to start on various taskings.  

<span class="enscript-keyword">\section</span>{Discussion and Notation}
<span class="enscript-keyword">\subsection</span>{Notation}
A multiple precision integer of <span class="enscript-variable-name">$n$</span>-digits shall be denoted as <span class="enscript-variable-name">$x = (x_{n-1}, \ldots, x_1, x_0)_{ \beta }$</span> and represent
the integer <span class="enscript-variable-name">$x \equiv \sum_{i=0}^{n-1} x_i\beta^i$</span>.  The elements of the array <span class="enscript-variable-name">$x$</span> are said to be the radix <span class="enscript-variable-name">$\beta$</span> digits 
of the integer.  For example, <span class="enscript-variable-name">$x = (1,2,3)_{10}$</span> would represent the integer 
<span class="enscript-variable-name">$1\cdot 10^2 + 2\cdot10^1 + 3\cdot10^0 = 123$</span>.  

<span class="enscript-keyword">\index</span>{mp<span class="enscript-keyword">\_</span>int}
The term ``mp<span class="enscript-keyword">\_</span>int'' shall refer to a composite structure which contains the digits of the integer it represents, as well 
as auxilary data required to manipulate the data.  These additional members are discussed further in section 
<span class="enscript-keyword">\ref</span>{sec:MPINT}.  For the purposes of this text a ``multiple precision integer'' and an ``mp<span class="enscript-keyword">\_</span>int'' are assumed to be 
synonymous.  When an algorithm is specified to accept an mp<span class="enscript-keyword">\_</span>int variable it is assumed the various auxliary data members 
are present as well.  An expression of the type <span class="enscript-keyword">\textit</span>{variablename.item} implies that it should evaluate to the 
member named ``item'' of the variable.  For example, a string of characters may have a member ``length'' which would 
evaluate to the number of characters in the string.  If the string <span class="enscript-variable-name">$a$</span> equals ``hello'' then it follows that 
<span class="enscript-variable-name">$a.length = 5$</span>.  

For certain discussions more generic algorithms are presented to help the reader understand the final algorithm used
to solve a given problem.  When an algorithm is described as accepting an integer input it is assumed the input is 
a plain integer with no additional multiple-precision members.  That is, algorithms that use integers as opposed to 
mp<span class="enscript-keyword">\_</span>ints as inputs do not concern themselves with the housekeeping operations required such as memory management.  These 
algorithms will be used to establish the relevant theory which will subsequently be used to describe a multiple
precision algorithm to solve the same problem.  

<span class="enscript-keyword">\subsection</span>{Precision Notation}
The variable <span class="enscript-variable-name">$\beta$</span> represents the radix of a single digit of a multiple precision integer and 
must be of the form <span class="enscript-variable-name">$q^p$</span> for <span class="enscript-variable-name">$q, p \in \Z^+$</span>.  A single precision variable must be able to represent integers in 
the range <span class="enscript-variable-name">$0 \le x &lt; q \beta$</span> while a double precision variable must be able to represent integers in the range 
<span class="enscript-variable-name">$0 \le x &lt; q \beta^2$</span>.  The extra radix-<span class="enscript-variable-name">$q$</span> factor allows additions and subtractions to proceed without truncation of the 
carry.  Since all modern computers are binary, it is assumed that <span class="enscript-variable-name">$q$</span> is two.

<span class="enscript-keyword">\index</span>{mp<span class="enscript-keyword">\_</span>digit} <span class="enscript-keyword">\index</span>{mp<span class="enscript-keyword">\_</span>word}
Within the source code that will be presented for each algorithm, the data type <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>digit} will represent 
a single precision integer type, while, the data type <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>word} will represent a double precision integer type.  In 
several algorithms (notably the Comba routines) temporary results will be stored in arrays of double precision mp<span class="enscript-keyword">\_</span>words.  
For the purposes of this text <span class="enscript-variable-name">$x_j$</span> will refer to the <span class="enscript-variable-name">$j$</span>'th digit of a single precision array and <span class="enscript-variable-name">$\hat x_j$</span> will refer to 
the <span class="enscript-variable-name">$j$</span>'th digit of a double precision array.  Whenever an expression is to be assigned to a double precision
variable it is assumed that all single precision variables are promoted to double precision during the evaluation.  
Expressions that are assigned to a single precision variable are truncated to fit within the precision of a single
precision data type.

For example, if <span class="enscript-variable-name">$\beta = 10^2$</span> a single precision data type may represent a value in the 
range <span class="enscript-variable-name">$0 \le x &lt; 10^3$</span>, while a double precision data type may represent a value in the range <span class="enscript-variable-name">$0 \le x &lt; 10^5$</span>.  Let
<span class="enscript-variable-name">$a = 23$</span> and <span class="enscript-variable-name">$b = 49$</span> represent two single precision variables.  The single precision product shall be written
as <span class="enscript-variable-name">$c \leftarrow a \cdot b$</span> while the double precision product shall be written as <span class="enscript-variable-name">$\hat c \leftarrow a \cdot b$</span>.
In this particular case, <span class="enscript-variable-name">$\hat c = 1127$</span> and <span class="enscript-variable-name">$c = 127$</span>.  The most significant digit of the product would not fit 
in a single precision data type and as a result <span class="enscript-variable-name">$c \ne \hat c$</span>.  

<span class="enscript-keyword">\subsection</span>{Algorithm Inputs and Outputs}
Within the algorithm descriptions all variables are assumed to be scalars of either single or double precision
as indicated.  The only exception to this rule is when variables have been indicated to be of type mp<span class="enscript-keyword">\_</span>int.  This 
distinction is important as scalars are often used as array indicies and various other counters.  

<span class="enscript-keyword">\subsection</span>{Mathematical Expressions}
The <span class="enscript-variable-name">$\lfloor \mbox{ } \rfloor$</span> brackets imply an expression truncated to an integer not greater than the expression 
itself.  For example, <span class="enscript-variable-name">$\lfloor 5.7 \rfloor = 5$</span>.  Similarly the <span class="enscript-variable-name">$\lceil \mbox{ } \rceil$</span> brackets imply an expression
rounded to an integer not less than the expression itself.  For example, <span class="enscript-variable-name">$\lceil 5.1 \rceil = 6$</span>.  Typically when 
the <span class="enscript-variable-name">$/$</span> division symbol is used the intention is to perform an integer division with truncation.  For example, 
<span class="enscript-variable-name">$5/2 = 2$</span> which will often be written as <span class="enscript-variable-name">$\lfloor 5/2 \rfloor = 2$</span> for clarity.  When an expression is written as a 
fraction a real value division is implied, for example <span class="enscript-variable-name">${5 \over 2} = 2.5$</span>.  

The norm of a multiple precision integer, for example <span class="enscript-variable-name">$\vert \vert x \vert \vert$</span>, will be used to represent the number of digits in the representation
of the integer.  For example, <span class="enscript-variable-name">$\vert \vert 123 \vert \vert = 3$</span> and <span class="enscript-variable-name">$\vert \vert 79452 \vert \vert = 5$</span>.  

<span class="enscript-keyword">\subsection</span>{Work Effort}
<span class="enscript-keyword">\index</span>{big-Oh}
To measure the efficiency of the specified algorithms, a modified big-Oh notation is used.  In this system all 
single precision operations are considered to have the same cost<span class="enscript-keyword">\footnote</span>{Except where explicitly noted.}.  
That is a single precision addition, multiplication and division are assumed to take the same time to 
complete.  While this is generally not true in practice, it will simplify the discussions considerably.

Some algorithms have slight advantages over others which is why some constants will not be removed in 
the notation.  For example, a normal baseline multiplication (section <span class="enscript-keyword">\ref</span>{sec:basemult}) requires <span class="enscript-variable-name">$O(n^2)$</span> work while a 
baseline squaring (section <span class="enscript-keyword">\ref</span>{sec:basesquare}) requires <span class="enscript-variable-name">$O({{n^2 + n}\over 2})$</span> work.  In standard big-Oh notation these 
would both be said to be equivalent to <span class="enscript-variable-name">$O(n^2)$</span>.  However, 
in the context of the this text this is not the case as the magnitude of the inputs will typically be rather small.  As a 
result small constant factors in the work effort will make an observable difference in algorithm efficiency.

All of the algorithms presented in this text have a polynomial time work level.  That is, of the form 
<span class="enscript-variable-name">$O(n^k)$</span> for <span class="enscript-variable-name">$n, k \in \Z^{+}$</span>.  This will help make useful comparisons in terms of the speed of the algorithms and how 
various optimizations will help pay off in the long run.

<span class="enscript-keyword">\section</span>{Exercises}
Within the more advanced chapters a section will be set aside to give the reader some challenging exercises related to
the discussion at hand.  These exercises are not designed to be prize winning problems, but instead to be thought 
provoking.  Wherever possible the problems are forward minded, stating problems that will be answered in subsequent 
chapters.  The reader is encouraged to finish the exercises as they appear to get a better understanding of the 
subject material.  

That being said, the problems are designed to affirm knowledge of a particular subject matter.  Students in particular
are encouraged to verify they can answer the problems correctly before moving on.

Similar to the exercises of <span class="enscript-keyword">\cite</span>[pp. ix]{TAOCPV2} these exercises are given a scoring system based on the difficulty of
the problem.  However, unlike <span class="enscript-keyword">\cite</span>{TAOCPV2} the problems do not get nearly as hard.  The scoring of these 
exercises ranges from one (the easiest) to five (the hardest).  The following table sumarizes the 
scoring system used.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{tabular}{|c|l|}
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$\left [ 1 \right ]$</span> &amp; An easy problem that should only take the reader a manner of <span class="enscript-keyword">\\</span>
                            &amp; minutes to solve.  Usually does not involve much computer time <span class="enscript-keyword">\\</span>
                            &amp; to solve. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$\left [ 2 \right ]$</span> &amp; An easy problem that involves a marginal amount of computer <span class="enscript-keyword">\\</span>
                     &amp; time usage.  Usually requires a program to be written to <span class="enscript-keyword">\\</span>
                     &amp; solve the problem. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$\left [ 3 \right ]$</span> &amp; A moderately hard problem that requires a non-trivial amount <span class="enscript-keyword">\\</span>
                     &amp; of work.  Usually involves trivial research and development of <span class="enscript-keyword">\\</span>
                     &amp; new theory from the perspective of a student. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$\left [ 4 \right ]$</span> &amp; A moderately hard problem that involves a non-trivial amount <span class="enscript-keyword">\\</span>
                     &amp; of work and research, the solution to which will demonstrate <span class="enscript-keyword">\\</span>
                     &amp; a higher mastery of the subject matter. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$\left [ 5 \right ]$</span> &amp; A hard problem that involves concepts that are difficult for a <span class="enscript-keyword">\\</span>
                     &amp; novice to solve.  Solutions to these problems will demonstrate a <span class="enscript-keyword">\\</span>
                     &amp; complete mastery of the given subject. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Exercise Scoring System}
<span class="enscript-keyword">\end</span>{figure}

Problems at the first level are meant to be simple questions that the reader can answer quickly without programming a solution or
devising new theory.  These problems are quick tests to see if the material is understood.  Problems at the second level 
are also designed to be easy but will require a program or algorithm to be implemented to arrive at the answer.  These
two levels are essentially entry level questions.  

Problems at the third level are meant to be a bit more difficult than the first two levels.  The answer is often 
fairly obvious but arriving at an exacting solution requires some thought and skill.  These problems will almost always 
involve devising a new algorithm or implementing a variation of another algorithm previously presented.  Readers who can
answer these questions will feel comfortable with the concepts behind the topic at hand.

Problems at the fourth level are meant to be similar to those of the level three questions except they will require 
additional research to be completed.  The reader will most likely not know the answer right away, nor will the text provide 
the exact details of the answer until a subsequent chapter.  

Problems at the fifth level are meant to be the hardest 
problems relative to all the other problems in the chapter.  People who can correctly answer fifth level problems have a 
mastery of the subject matter at hand.

Often problems will be tied together.  The purpose of this is to start a chain of thought that will be discussed in future chapters.  The reader
is encouraged to answer the follow-up problems and try to draw the relevance of problems.

<span class="enscript-keyword">\section</span>{Introduction to LibTomMath}

<span class="enscript-keyword">\subsection</span>{What is LibTomMath?}
LibTomMath is a free and open source multiple precision integer library written entirely in portable ISO C.  By portable it 
is meant that the library does not contain any code that is computer platform dependent or otherwise problematic to use on 
any given platform.  

The library has been successfully tested under numerous operating systems including Unix<span class="enscript-keyword">\footnote</span>{All of these
trademarks belong to their respective rightful owners.}, MacOS, Windows, Linux, PalmOS and on standalone hardware such 
as the Gameboy Advance.  The library is designed to contain enough functionality to be able to develop applications such 
as public key cryptosystems and still maintain a relatively small footprint.

<span class="enscript-keyword">\subsection</span>{Goals of LibTomMath}

Libraries which obtain the most efficiency are rarely written in a high level programming language such as C.  However, 
even though this library is written entirely in ISO C, considerable care has been taken to optimize the algorithm implementations within the 
library.  Specifically the code has been written to work well with the GNU C Compiler (<span class="enscript-keyword">\textit</span>{GCC}) on both x86 and ARM 
processors.  Wherever possible, highly efficient algorithms, such as Karatsuba multiplication, sliding window 
exponentiation and Montgomery reduction have been provided to make the library more efficient.  

Even with the nearly optimal and specialized algorithms that have been included the Application Programing Interface 
(<span class="enscript-keyword">\textit</span>{API}) has been kept as simple as possible.  Often generic place holder routines will make use of specialized 
algorithms automatically without the developer's specific attention.  One such example is the generic multiplication 
algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>mul()} which will automatically use Toom--Cook, Karatsuba, Comba or baseline multiplication 
based on the magnitude of the inputs and the configuration of the library.  

Making LibTomMath as efficient as possible is not the only goal of the LibTomMath project.  Ideally the library should 
be source compatible with another popular library which makes it more attractive for developers to use.  In this case the
MPI library was used as a API template for all the basic functions.  MPI was chosen because it is another library that fits 
in the same niche as LibTomMath.  Even though LibTomMath uses MPI as the template for the function names and argument 
passing conventions, it has been written from scratch by Tom St Denis.

The project is also meant to act as a learning tool for students, the logic being that no easy-to-follow ``bignum'' 
library exists which can be used to teach computer science students how to perform fast and reliable multiple precision 
integer arithmetic.  To this end the source code has been given quite a few comments and algorithm discussion points.  

<span class="enscript-keyword">\section</span>{Choice of LibTomMath}
LibTomMath was chosen as the case study of this text not only because the author of both projects is one and the same but
for more worthy reasons.  Other libraries such as GMP <span class="enscript-keyword">\cite</span>{GMP}, MPI <span class="enscript-keyword">\cite</span>{MPI}, LIP <span class="enscript-keyword">\cite</span>{LIP} and OpenSSL 
<span class="enscript-keyword">\cite</span>{OPENSSL} have multiple precision integer arithmetic routines but would not be ideal for this text for 
reasons that will be explained in the following sub-sections.

<span class="enscript-keyword">\subsection</span>{Code Base}
The LibTomMath code base is all portable ISO C source code.  This means that there are no platform dependent conditional
segments of code littered throughout the source.  This clean and uncluttered approach to the library means that a
developer can more readily discern the true intent of a given section of source code without trying to keep track of
what conditional code will be used.

The code base of LibTomMath is well organized.  Each function is in its own separate source code file 
which allows the reader to find a given function very quickly.  On average there are <span class="enscript-variable-name">$76$</span> lines of code per source
file which makes the source very easily to follow.  By comparison MPI and LIP are single file projects making code tracing
very hard.  GMP has many conditional code segments which also hinder tracing.  

When compiled with GCC for the x86 processor and optimized for speed the entire library is approximately <span class="enscript-variable-name">$100$</span>KiB<span class="enscript-keyword">\footnote</span>{The notation ``KiB'' means <span class="enscript-variable-name">$2^{10}$</span> octets, similarly ``MiB'' means <span class="enscript-variable-name">$2^{20}$</span> octets.}
 which is fairly small compared to GMP (over <span class="enscript-variable-name">$250$</span>KiB).  LibTomMath is slightly larger than MPI (which compiles to about 
<span class="enscript-variable-name">$50$</span>KiB) but LibTomMath is also much faster and more complete than MPI.

<span class="enscript-keyword">\subsection</span>{API Simplicity}
LibTomMath is designed after the MPI library and shares the API design.  Quite often programs that use MPI will build 
with LibTomMath without change. The function names correlate directly to the action they perform.  Almost all of the 
functions share the same parameter passing convention.  The learning curve is fairly shallow with the API provided 
which is an extremely valuable benefit for the student and developer alike.  

The LIP library is an example of a library with an API that is awkward to work with.  LIP uses function names that are often ``compressed'' to 
illegible short hand.  LibTomMath does not share this characteristic.  

The GMP library also does not return error codes.  Instead it uses a POSIX.1 <span class="enscript-keyword">\cite</span>{POSIX1} signal system where errors
are signaled to the host application.  This happens to be the fastest approach but definitely not the most versatile.  In
effect a math error (i.e. invalid input, heap error, etc) can cause a program to stop functioning which is definitely 
undersireable in many situations.

<span class="enscript-keyword">\subsection</span>{Optimizations}
While LibTomMath is certainly not the fastest library (GMP often beats LibTomMath by a factor of two) it does
feature a set of optimal algorithms for tasks such as modular reduction, exponentiation, multiplication and squaring.  GMP 
and LIP also feature such optimizations while MPI only uses baseline algorithms with no optimizations.  GMP lacks a few
of the additional modular reduction optimizations that LibTomMath features<span class="enscript-keyword">\footnote</span>{At the time of this writing GMP
only had Barrett and Montgomery modular reduction algorithms.}.  

LibTomMath is almost always an order of magnitude faster than the MPI library at computationally expensive tasks such as modular
exponentiation.  In the grand scheme of ``bignum'' libraries LibTomMath is faster than the average library and usually  
slower than the best libraries such as GMP and OpenSSL by only a small factor.

<span class="enscript-keyword">\subsection</span>{Portability and Stability}
LibTomMath will build ``out of the box'' on any platform equipped with a modern version of the GNU C Compiler 
(<span class="enscript-keyword">\textit</span>{GCC}).  This means that without changes the library will build without configuration or setting up any 
variables.  LIP and MPI will build ``out of the box'' as well but have numerous known bugs.  Most notably the author of 
MPI has recently stopped working on his library and LIP has long since been discontinued.  

GMP requires a configuration script to run and will not build out of the box.   GMP and LibTomMath are still in active
development and are very stable across a variety of platforms.

<span class="enscript-keyword">\subsection</span>{Choice}
LibTomMath is a relatively compact, well documented, highly optimized and portable library which seems only natural for
the case study of this text.  Various source files from the LibTomMath project will be included within the text.  However, 
the reader is encouraged to download their own copy of the library to actually be able to work with the library.  

<span class="enscript-keyword">\chapter</span>{Getting Started}
<span class="enscript-keyword">\section</span>{Library Basics}
The trick to writing any useful library of source code is to build a solid foundation and work outwards from it.  First, 
a problem along with allowable solution parameters should be identified and analyzed.  In this particular case the 
inability to accomodate multiple precision integers is the problem.  Futhermore, the solution must be written
as portable source code that is reasonably efficient across several different computer platforms.

After a foundation is formed the remainder of the library can be designed and implemented in a hierarchical fashion.  
That is, to implement the lowest level dependencies first and work towards the most abstract functions last.  For example, 
before implementing a modular exponentiation algorithm one would implement a modular reduction algorithm.
By building outwards from a base foundation instead of using a parallel design methodology the resulting project is 
highly modular.  Being highly modular is a desirable property of any project as it often means the resulting product
has a small footprint and updates are easy to perform.  

Usually when I start a project I will begin with the header files.  I define the data types I think I will need and 
prototype the initial functions that are not dependent on other functions (within the library).  After I 
implement these base functions I prototype more dependent functions and implement them.   The process repeats until
I implement all of the functions I require.  For example, in the case of LibTomMath I implemented functions such as 
mp<span class="enscript-keyword">\_</span>init() well before I implemented mp<span class="enscript-keyword">\_</span>mul() and even further before I implemented mp<span class="enscript-keyword">\_</span>exptmod().  As an example as to 
why this design works note that the Karatsuba and Toom-Cook multipliers were written <span class="enscript-keyword">\textit</span>{after} the 
dependent function mp<span class="enscript-keyword">\_</span>exptmod() was written.  Adding the new multiplication algorithms did not require changes to the 
mp<span class="enscript-keyword">\_</span>exptmod() function itself and lowered the total cost of ownership (<span class="enscript-keyword">\textit</span>{so to speak}) and of development 
for new algorithms.  This methodology allows new algorithms to be tested in a complete framework with relative ease.

<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\includegraphics</span>{pics/design_process.ps}
<span class="enscript-keyword">\caption</span>{Design Flow of the First Few Original LibTomMath Functions.}
<span class="enscript-keyword">\label</span>{pic:design_process}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\end</span>{center}

Only after the majority of the functions were in place did I pursue a less hierarchical approach to auditing and optimizing
the source code.  For example, one day I may audit the multipliers and the next day the polynomial basis functions.  

It only makes sense to begin the text with the preliminary data types and support algorithms required as well.  
This chapter discusses the core algorithms of the library which are the dependents for every other algorithm.

<span class="enscript-keyword">\section</span>{What is a Multiple Precision Integer?}
Recall that most programming languages, in particular ISO C <span class="enscript-keyword">\cite</span>{ISOC}, only have fixed precision data types that on their own cannot 
be used to represent values larger than their precision will allow. The purpose of multiple precision algorithms is 
to use fixed precision data types to create and manipulate multiple precision integers which may represent values 
that are very large.  

As a well known analogy, school children are taught how to form numbers larger than nine by prepending more radix ten digits.  In the decimal system
the largest single digit value is <span class="enscript-variable-name">$9$</span>.  However, by concatenating digits together larger numbers may be represented.  Newly prepended digits 
(<span class="enscript-keyword">\textit</span>{to the left}) are said to be in a different power of ten column.  That is, the number <span class="enscript-variable-name">$123$</span> can be described as having a <span class="enscript-variable-name">$1$</span> in the hundreds 
column, <span class="enscript-variable-name">$2$</span> in the tens column and <span class="enscript-variable-name">$3$</span> in the ones column.  Or more formally <span class="enscript-variable-name">$123 = 1 \cdot 10^2 + 2 \cdot 10^1 + 3 \cdot 10^0$</span>.  Computer based 
multiple precision arithmetic is essentially the same concept.  Larger integers are represented by adjoining fixed 
precision computer words with the exception that a different radix is used.

What most people probably do not think about explicitly are the various other attributes that describe a multiple precision 
integer.  For example, the integer <span class="enscript-variable-name">$154_{10}$</span> has two immediately obvious properties.  First, the integer is positive, 
that is the sign of this particular integer is positive as opposed to negative.  Second, the integer has three digits in 
its representation.  There is an additional property that the integer posesses that does not concern pencil-and-paper 
arithmetic.  The third property is how many digits placeholders are available to hold the integer.  

The human analogy of this third property is ensuring there is enough space on the paper to write the integer.  For example,
if one starts writing a large number too far to the right on a piece of paper they will have to erase it and move left.  
Similarly, computer algorithms must maintain strict control over memory usage to ensure that the digits of an integer
will not exceed the allowed boundaries.  These three properties make up what is known as a multiple precision 
integer or mp<span class="enscript-keyword">\_</span>int for short.  

<span class="enscript-keyword">\subsection</span>{The mp<span class="enscript-keyword">\_</span>int Structure}
<span class="enscript-keyword">\label</span>{sec:MPINT}
The mp<span class="enscript-keyword">\_</span>int structure is the ISO C based manifestation of what represents a multiple precision integer.  The ISO C standard does not provide for 
any such data type but it does provide for making composite data types known as structures.  The following is the structure definition 
used within LibTomMath.

<span class="enscript-keyword">\index</span>{mp<span class="enscript-keyword">\_</span>int}
<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-comment">%\begin{verbatim}
</span><span class="enscript-keyword">\begin</span>{tabular}{|l|}
<span class="enscript-keyword">\hline</span>
typedef struct <span class="enscript-keyword">\{</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}int used, alloc, sign;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}mp<span class="enscript-keyword">\_</span>digit *dp;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\}</span> <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>int}; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-comment">%\end{verbatim}
</span><span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{The mp<span class="enscript-keyword">\_</span>int Structure}
<span class="enscript-keyword">\label</span>{fig:mpint}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{figure}

The mp<span class="enscript-keyword">\_</span>int structure (fig. <span class="enscript-keyword">\ref</span>{fig:mpint}) can be broken down as follows.

<span class="enscript-keyword">\begin</span>{enumerate}
<span class="enscript-keyword">\item</span> The <span class="enscript-keyword">\textbf</span>{used} parameter denotes how many digits of the array <span class="enscript-keyword">\textbf</span>{dp} contain the digits used to represent
a given integer.  The <span class="enscript-keyword">\textbf</span>{used} count must be positive (or zero) and may not exceed the <span class="enscript-keyword">\textbf</span>{alloc} count.  

<span class="enscript-keyword">\item</span> The <span class="enscript-keyword">\textbf</span>{alloc} parameter denotes how 
many digits are available in the array to use by functions before it has to increase in size.  When the <span class="enscript-keyword">\textbf</span>{used} count 
of a result would exceed the <span class="enscript-keyword">\textbf</span>{alloc} count all of the algorithms will automatically increase the size of the 
array to accommodate the precision of the result.  

<span class="enscript-keyword">\item</span> The pointer <span class="enscript-keyword">\textbf</span>{dp} points to a dynamically allocated array of digits that represent the given multiple 
precision integer.  It is padded with <span class="enscript-variable-name">$(\textbf{alloc} - \textbf{used})$</span> zero digits.  The array is maintained in a least 
significant digit order.  As a pencil and paper analogy the array is organized such that the right most digits are stored
first starting at the location indexed by zero<span class="enscript-keyword">\footnote</span>{In C all arrays begin at zero.} in the array.  For example, 
if <span class="enscript-keyword">\textbf</span>{dp} contains <span class="enscript-variable-name">$\lbrace a, b, c, \ldots \rbrace$</span> where <span class="enscript-keyword">\textbf</span>{dp}<span class="enscript-variable-name">$_0 = a$</span>, <span class="enscript-keyword">\textbf</span>{dp}<span class="enscript-variable-name">$_1 = b$</span>, <span class="enscript-keyword">\textbf</span>{dp}<span class="enscript-variable-name">$_2 = c$</span>, <span class="enscript-variable-name">$\ldots$</span> then 
it would represent the integer <span class="enscript-variable-name">$a + b\beta + c\beta^2 + \ldots$</span>  

<span class="enscript-keyword">\index</span>{MP<span class="enscript-keyword">\_</span>ZPOS} <span class="enscript-keyword">\index</span>{MP<span class="enscript-keyword">\_</span>NEG}
<span class="enscript-keyword">\item</span> The <span class="enscript-keyword">\textbf</span>{sign} parameter denotes the sign as either zero/positive (<span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS}) or negative (<span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>NEG}).  
<span class="enscript-keyword">\end</span>{enumerate}

<span class="enscript-keyword">\subsubsection</span>{Valid mp<span class="enscript-keyword">\_</span>int Structures}
Several rules are placed on the state of an mp<span class="enscript-keyword">\_</span>int structure and are assumed to be followed for reasons of efficiency.  
The only exceptions are when the structure is passed to initialization functions such as mp<span class="enscript-keyword">\_</span>init() and mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy().

<span class="enscript-keyword">\begin</span>{enumerate}
<span class="enscript-keyword">\item</span> The value of <span class="enscript-keyword">\textbf</span>{alloc} may not be less than one.  That is <span class="enscript-keyword">\textbf</span>{dp} always points to a previously allocated
array of digits.
<span class="enscript-keyword">\item</span> The value of <span class="enscript-keyword">\textbf</span>{used} may not exceed <span class="enscript-keyword">\textbf</span>{alloc} and must be greater than or equal to zero.
<span class="enscript-keyword">\item</span> The value of <span class="enscript-keyword">\textbf</span>{used} implies the digit at index <span class="enscript-variable-name">$(used - 1)$</span> of the <span class="enscript-keyword">\textbf</span>{dp} array is non-zero.  That is, 
leading zero digits in the most significant positions must be trimmed.
   <span class="enscript-keyword">\begin</span>{enumerate}
   <span class="enscript-keyword">\item</span> Digits in the <span class="enscript-keyword">\textbf</span>{dp} array at and above the <span class="enscript-keyword">\textbf</span>{used} location must be zero.
   <span class="enscript-keyword">\end</span>{enumerate}
<span class="enscript-keyword">\item</span> The value of <span class="enscript-keyword">\textbf</span>{sign} must be <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS} if <span class="enscript-keyword">\textbf</span>{used} is zero; 
this represents the mp<span class="enscript-keyword">\_</span>int value of zero.
<span class="enscript-keyword">\end</span>{enumerate}

<span class="enscript-keyword">\section</span>{Argument Passing}
A convention of argument passing must be adopted early on in the development of any library.  Making the function 
prototypes consistent will help eliminate many headaches in the future as the library grows to significant complexity.  
In LibTomMath the multiple precision integer functions accept parameters from left to right as pointers to mp<span class="enscript-keyword">\_</span>int 
structures.  That means that the source (input) operands are placed on the left and the destination (output) on the right.   
Consider the following examples.

<span class="enscript-keyword">\begin</span>{verbatim}
   mp_mul(&amp;a, &amp;b, &amp;c);   /* c = a * b */
   mp_add(&amp;a, &amp;b, &amp;a);   /* a = a + b */
   mp_sqr(&amp;a, &amp;b);       /* b = a * a */
<span class="enscript-keyword">\end</span>{verbatim}

The left to right order is a fairly natural way to implement the functions since it lets the developer read aloud the
functions and make sense of them.  For example, the first function would read ``multiply a and b and store in c''.

Certain libraries (<span class="enscript-keyword">\textit</span>{LIP by Lenstra for instance}) accept parameters the other way around, to mimic the order
of assignment expressions.  That is, the destination (output) is on the left and arguments (inputs) are on the right.  In 
truth, it is entirely a matter of preference.  In the case of LibTomMath the convention from the MPI library has been 
adopted.  

Another very useful design consideration, provided for in LibTomMath, is whether to allow argument sources to also be a 
destination.  For example, the second example (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>add}) adds <span class="enscript-variable-name">$a$</span> to <span class="enscript-variable-name">$b$</span> and stores in <span class="enscript-variable-name">$a$</span>.  This is an important 
feature to implement since it allows the calling functions to cut down on the number of variables it must maintain.  
However, to implement this feature specific care has to be given to ensure the destination is not modified before the 
source is fully read.

<span class="enscript-keyword">\section</span>{Return Values}
A well implemented application, no matter what its purpose, should trap as many runtime errors as possible and return them 
to the caller.  By catching runtime errors a library can be guaranteed to prevent undefined behaviour.  However, the end 
developer can still manage to cause a library to crash.  For example, by passing an invalid pointer an application may
fault by dereferencing memory not owned by the application.

In the case of LibTomMath the only errors that are checked for are related to inappropriate inputs (division by zero for 
instance) and memory allocation errors.  It will not check that the mp<span class="enscript-keyword">\_</span>int passed to any function is valid nor 
will it check pointers for validity.  Any function that can cause a runtime error will return an error code as an 
<span class="enscript-keyword">\textbf</span>{int} data type with one of the following values (fig <span class="enscript-keyword">\ref</span>{fig:errcodes}).

<span class="enscript-keyword">\index</span>{MP<span class="enscript-keyword">\_</span>OKAY} <span class="enscript-keyword">\index</span>{MP<span class="enscript-keyword">\_</span>VAL} <span class="enscript-keyword">\index</span>{MP<span class="enscript-keyword">\_</span>MEM}
<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|l|l|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Value} &amp; <span class="enscript-keyword">\textbf</span>{Meaning} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>OKAY} &amp; The function was successful <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>VAL}  &amp; One of the input value(s) was invalid <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>MEM}  &amp; The function ran out of heap memory <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{LibTomMath Error Codes}
<span class="enscript-keyword">\label</span>{fig:errcodes}
<span class="enscript-keyword">\end</span>{figure}

When an error is detected within a function it should free any memory it allocated, often during the initialization of
temporary mp<span class="enscript-keyword">\_</span>ints, and return as soon as possible.  The goal is to leave the system in the same state it was when the 
function was called.  Error checking with this style of API is fairly simple.

<span class="enscript-keyword">\begin</span>{verbatim}
   int err;
   if ((err = mp_add(&amp;a, &amp;b, &amp;c)) != MP_OKAY) {
      printf(&quot;Error: <span class="enscript-comment">%s\n&quot;, mp_error_to_string(err));
</span>      exit(EXIT_FAILURE);
   }
<span class="enscript-keyword">\end</span>{verbatim}

The GMP <span class="enscript-keyword">\cite</span>{GMP} library uses C style <span class="enscript-keyword">\textit</span>{signals} to flag errors which is of questionable use.  Not all errors are fatal 
and it was not deemed ideal by the author of LibTomMath to force developers to have signal handlers for such cases.

<span class="enscript-keyword">\section</span>{Initialization and Clearing}
The logical starting point when actually writing multiple precision integer functions is the initialization and 
clearing of the mp<span class="enscript-keyword">\_</span>int structures.  These two algorithms will be used by the majority of the higher level algorithms.

Given the basic mp<span class="enscript-keyword">\_</span>int structure an initialization routine must first allocate memory to hold the digits of
the integer.  Often it is optimal to allocate a sufficiently large pre-set number of digits even though
the initial integer will represent zero.  If only a single digit were allocated quite a few subsequent re-allocations
would occur when operations are performed on the integers.  There is a tradeoff between how many default digits to allocate
and how many re-allocations are tolerable.  Obviously allocating an excessive amount of digits initially will waste 
memory and become unmanageable.  

If the memory for the digits has been successfully allocated then the rest of the members of the structure must
be initialized.  Since the initial state of an mp<span class="enscript-keyword">\_</span>int is to represent the zero integer, the allocated digits must be set
to zero.  The <span class="enscript-keyword">\textbf</span>{used} count set to zero and <span class="enscript-keyword">\textbf</span>{sign} set to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS}.

<span class="enscript-keyword">\subsection</span>{Initializing an mp<span class="enscript-keyword">\_</span>int}
An mp<span class="enscript-keyword">\_</span>int is said to be initialized if it is set to a valid, preferably default, state such that all of the members of the
structure are set to valid values.  The mp<span class="enscript-keyword">\_</span>init algorithm will perform such an action.

<span class="enscript-keyword">\index</span>{mp<span class="enscript-keyword">\_</span>init}
<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>init}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Allocate memory and initialize <span class="enscript-variable-name">$a$</span> to a known valid mp<span class="enscript-keyword">\_</span>int state.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Allocate memory for <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} digits. <span class="enscript-keyword">\\</span>
2.  If the allocation failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}) <span class="enscript-keyword">\\</span>
3.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$MP\_PREC - 1$</span> do  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$a_n \leftarrow 0$</span><span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$a.sign \leftarrow MP\_ZPOS$</span><span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$a.used \leftarrow 0$</span><span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$a.alloc \leftarrow MP\_PREC$</span><span class="enscript-keyword">\\</span>
7.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY})<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>init}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>init.}
The purpose of this function is to initialize an mp<span class="enscript-keyword">\_</span>int structure so that the rest of the library can properly
manipulte it.  It is assumed that the input may not have had any of its members previously initialized which is certainly
a valid assumption if the input resides on the stack.  

Before any of the members such as <span class="enscript-keyword">\textbf</span>{sign}, <span class="enscript-keyword">\textbf</span>{used} or <span class="enscript-keyword">\textbf</span>{alloc} are initialized the memory for
the digits is allocated.  If this fails the function returns before setting any of the other members.  The <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} 
name represents a constant<span class="enscript-keyword">\footnote</span>{Defined in the ``tommath.h'' header file within LibTomMath.} 
used to dictate the minimum precision of newly initialized mp<span class="enscript-keyword">\_</span>int integers.  Ideally, it is at least equal to the smallest
precision number you'll be working with.

Allocating a block of digits at first instead of a single digit has the benefit of lowering the number of usually slow
heap operations later functions will have to perform in the future.  If <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} is set correctly the slack 
memory and the number of heap operations will be trivial.

Once the allocation has been made the digits have to be set to zero as well as the <span class="enscript-keyword">\textbf</span>{used}, <span class="enscript-keyword">\textbf</span>{sign} and
<span class="enscript-keyword">\textbf</span>{alloc} members initialized.  This ensures that the mp<span class="enscript-keyword">\_</span>int will always represent the default state of zero regardless
of the original condition of the input.

<span class="enscript-keyword">\textbf</span>{Remark.}
This function introduces the idiosyncrasy that all iterative loops, commonly initiated with the ``for'' keyword, iterate incrementally
when the ``to'' keyword is placed between two expressions.  For example, ``for <span class="enscript-variable-name">$a$</span> from <span class="enscript-variable-name">$b$</span> to <span class="enscript-variable-name">$c$</span> do'' means that
a subsequent expression (or body of expressions) are to be evaluated upto <span class="enscript-variable-name">$c - b$</span> times so long as <span class="enscript-variable-name">$b \le c$</span>.  In each
iteration the variable <span class="enscript-variable-name">$a$</span> is substituted for a new integer that lies inclusively between <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$c$</span>.  If <span class="enscript-variable-name">$b &gt; c$</span> occured
the loop would not iterate.  By contrast if the ``downto'' keyword were used in place of ``to'' the loop would iterate 
decrementally.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>init.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

One immediate observation of this initializtion function is that it does not return a pointer to a mp<span class="enscript-keyword">\_</span>int structure.  It 
is assumed that the caller has already allocated memory for the mp<span class="enscript-keyword">\_</span>int structure, typically on the application stack.  The 
call to mp<span class="enscript-keyword">\_</span>init() is used only to initialize the members of the structure to a known default state.  

Here we see (line 24) the memory allocation is performed first.  This allows us to exit cleanly and quickly
if there is an error.  If the allocation fails the routine will return <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>MEM} to the caller to indicate there
was a memory error.  The function XMALLOC is what actually allocates the memory.  Technically XMALLOC is not a function
but a macro defined in ``tommath.h``.  By default, XMALLOC will evaluate to malloc() which is the C library's built--in
memory allocation routine.

In order to assure the mp<span class="enscript-keyword">\_</span>int is in a known state the digits must be set to zero.  On most platforms this could have been
accomplished by using calloc() instead of malloc().  However,  to correctly initialize a integer type to a given value in a 
portable fashion you have to actually assign the value.  The for loop (line 30) performs this required
operation.

After the memory has been successfully initialized the remainder of the members are initialized 
(lines 34 through 35) to their respective default states.  At this point the algorithm has succeeded and
a success code is returned to the calling function.  If this function returns <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>OKAY} it is safe to assume the 
mp<span class="enscript-keyword">\_</span>int structure has been properly initialized and is safe to use with other functions within the library.  

<span class="enscript-keyword">\subsection</span>{Clearing an mp<span class="enscript-keyword">\_</span>int}
When an mp<span class="enscript-keyword">\_</span>int is no longer required by the application, the memory that has been allocated for its digits must be 
returned to the application's memory pool with the mp<span class="enscript-keyword">\_</span>clear algorithm.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>clear}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The memory for <span class="enscript-variable-name">$a$</span> shall be deallocated.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$a$</span> has been previously freed then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
2.  for <span class="enscript-variable-name">$n$</span> from 0 to <span class="enscript-variable-name">$a.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$a_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
3.  Free the memory allocated for the digits of <span class="enscript-variable-name">$a$</span>. <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$a.used \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$a.alloc \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$a.sign \leftarrow MP\_ZPOS$</span> <span class="enscript-keyword">\\</span>
7.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>clear}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>clear.}
This algorithm accomplishes two goals.  First, it clears the digits and the other mp<span class="enscript-keyword">\_</span>int members.  This ensures that 
if a developer accidentally re-uses a cleared structure it is less likely to cause problems.  The second goal
is to free the allocated memory.

The logic behind the algorithm is extended by marking cleared mp<span class="enscript-keyword">\_</span>int structures so that subsequent calls to this
algorithm will not try to free the memory multiple times.  Cleared mp<span class="enscript-keyword">\_</span>ints are detectable by having a pre-defined invalid 
digit pointer <span class="enscript-keyword">\textbf</span>{dp} setting.

Once an mp<span class="enscript-keyword">\_</span>int has been cleared the mp<span class="enscript-keyword">\_</span>int structure is no longer in a valid state for any other algorithm
with the exception of algorithms mp<span class="enscript-keyword">\_</span>init, mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy, mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>size and mp<span class="enscript-keyword">\_</span>clear.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>clear.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The algorithm only operates on the mp<span class="enscript-keyword">\_</span>int if it hasn't been previously cleared.  The if statement (line 25)
checks to see if the <span class="enscript-keyword">\textbf</span>{dp} member is not <span class="enscript-keyword">\textbf</span>{NULL}.  If the mp<span class="enscript-keyword">\_</span>int is a valid mp<span class="enscript-keyword">\_</span>int then <span class="enscript-keyword">\textbf</span>{dp} cannot be
<span class="enscript-keyword">\textbf</span>{NULL} in which case the if statement will evaluate to true.

The digits of the mp<span class="enscript-keyword">\_</span>int are cleared by the for loop (line 27) which assigns a zero to every digit.  Similar to mp<span class="enscript-keyword">\_</span>init()
the digits are assigned zero instead of using block memory operations (such as memset()) since this is more portable.  

The digits are deallocated off the heap via the XFREE macro.  Similar to XMALLOC the XFREE macro actually evaluates to
a standard C library function.  In this case the free() function.  Since free() only deallocates the memory the pointer
still has to be reset to <span class="enscript-keyword">\textbf</span>{NULL} manually (line 35).  

Now that the digits have been cleared and deallocated the other members are set to their final values (lines 36 and 37).

<span class="enscript-keyword">\section</span>{Maintenance Algorithms}

The previous sections describes how to initialize and clear an mp<span class="enscript-keyword">\_</span>int structure.  To further support operations
that are to be performed on mp<span class="enscript-keyword">\_</span>int structures (such as addition and multiplication) the dependent algorithms must be
able to augment the precision of an mp<span class="enscript-keyword">\_</span>int and 
initialize mp<span class="enscript-keyword">\_</span>ints with differing initial conditions.  

These algorithms complete the set of low level algorithms required to work with mp<span class="enscript-keyword">\_</span>int structures in the higher level
algorithms such as addition, multiplication and modular exponentiation.

<span class="enscript-keyword">\subsection</span>{Augmenting an mp<span class="enscript-keyword">\_</span>int's Precision}
When storing a value in an mp<span class="enscript-keyword">\_</span>int structure, a sufficient number of digits must be available to accomodate the entire 
result of an operation without loss of precision.  Quite often the size of the array given by the <span class="enscript-keyword">\textbf</span>{alloc} member 
is large enough to simply increase the <span class="enscript-keyword">\textbf</span>{used} digit count.  However, when the size of the array is too small it 
must be re-sized appropriately to accomodate the result.  The mp<span class="enscript-keyword">\_</span>grow algorithm will provide this functionality.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>grow}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and an integer <span class="enscript-variable-name">$b$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$a$</span> is expanded to accomodate <span class="enscript-variable-name">$b$</span> digits. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  if <span class="enscript-variable-name">$a.alloc \ge b$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$u \leftarrow b\mbox{ (mod }MP\_PREC\mbox{)}$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$v \leftarrow b + 2 \cdot MP\_PREC - u$</span> <span class="enscript-keyword">\\</span>
4.  Re-allocate the array of digits <span class="enscript-variable-name">$a$</span> to size <span class="enscript-variable-name">$v$</span> <span class="enscript-keyword">\\</span>
5.  If the allocation failed then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
6.  for n from a.alloc to <span class="enscript-variable-name">$v - 1$</span> do  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}6.1  <span class="enscript-variable-name">$a_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$a.alloc \leftarrow v$</span> <span class="enscript-keyword">\\</span>
8.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>grow}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>grow.}
It is ideal to prevent re-allocations from being performed if they are not required (step one).  This is useful to 
prevent mp<span class="enscript-keyword">\_</span>ints from growing excessively in code that erroneously calls mp<span class="enscript-keyword">\_</span>grow.  

The requested digit count is padded up to next multiple of <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} plus an additional <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} (steps two and three).  
This helps prevent many trivial reallocations that would grow an mp<span class="enscript-keyword">\_</span>int by trivially small values.  

It is assumed that the reallocation (step four) leaves the lower <span class="enscript-variable-name">$a.alloc$</span> digits of the mp<span class="enscript-keyword">\_</span>int intact.  This is much 
akin to how the <span class="enscript-keyword">\textit</span>{realloc} function from the standard C library works.  Since the newly allocated digits are 
assumed to contain undefined values they are initially set to zero.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>grow.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

A quick optimization is to first determine if a memory re-allocation is required at all.  The if statement (line 24) checks
if the <span class="enscript-keyword">\textbf</span>{alloc} member of the mp<span class="enscript-keyword">\_</span>int is smaller than the requested digit count.  If the count is not larger than <span class="enscript-keyword">\textbf</span>{alloc}
the function skips the re-allocation part thus saving time.

When a re-allocation is performed it is turned into an optimal request to save time in the future.  The requested digit count is
padded upwards to 2nd multiple of <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} larger than <span class="enscript-keyword">\textbf</span>{alloc} (line 25).  The XREALLOC function is used
to re-allocate the memory.  As per the other functions XREALLOC is actually a macro which evaluates to realloc by default.  The realloc
function leaves the base of the allocation intact which means the first <span class="enscript-keyword">\textbf</span>{alloc} digits of the mp<span class="enscript-keyword">\_</span>int are the same as before
the re-allocation.  All	that is left is to clear the newly allocated digits and return.

Note that the re-allocation result is actually stored in a temporary pointer <span class="enscript-variable-name">$tmp$</span>.  This is to allow this function to return
an error with a valid pointer.  Earlier releases of the library stored the result of XREALLOC into the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>.  That would
result in a memory leak if XREALLOC ever failed.  

<span class="enscript-keyword">\subsection</span>{Initializing Variable Precision mp<span class="enscript-keyword">\_</span>ints}
Occasionally the number of digits required will be known in advance of an initialization, based on, for example, the size 
of input mp<span class="enscript-keyword">\_</span>ints to a given algorithm.  The purpose of algorithm mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>size is similar to mp<span class="enscript-keyword">\_</span>init except that it 
will allocate <span class="enscript-keyword">\textit</span>{at least} a specified number of digits.  

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>size}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and the requested number of digits <span class="enscript-variable-name">$b$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$a$</span> is initialized to hold at least <span class="enscript-variable-name">$b$</span> digits. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$u \leftarrow b \mbox{ (mod }MP\_PREC\mbox{)}$</span> <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$v \leftarrow b + 2 \cdot MP\_PREC - u$</span> <span class="enscript-keyword">\\</span>
3.  Allocate <span class="enscript-variable-name">$v$</span> digits. <span class="enscript-keyword">\\</span>
4.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$v - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$a_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$a.sign \leftarrow MP\_ZPOS$</span><span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$a.used \leftarrow 0$</span><span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$a.alloc \leftarrow v$</span><span class="enscript-keyword">\\</span>
8.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY})<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>size}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>size.}
This algorithm will initialize an mp<span class="enscript-keyword">\_</span>int structure <span class="enscript-variable-name">$a$</span> like algorithm mp<span class="enscript-keyword">\_</span>init with the exception that the number of 
digits allocated can be controlled by the second input argument <span class="enscript-variable-name">$b$</span>.  The input size is padded upwards so it is a 
multiple of <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} plus an additional <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} digits.  This padding is used to prevent trivial 
allocations from becoming a bottleneck in the rest of the algorithms.

Like algorithm mp<span class="enscript-keyword">\_</span>init, the mp<span class="enscript-keyword">\_</span>int structure is initialized to a default state representing the integer zero.  This 
particular algorithm is useful if it is known ahead of time the approximate size of the input.  If the approximation is
correct no further memory re-allocations are required to work with the mp<span class="enscript-keyword">\_</span>int.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>size.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The number of digits <span class="enscript-variable-name">$b$</span> requested is padded (line 24) by first augmenting it to the next multiple of 
<span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} and then adding <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} to the result.  If the memory can be successfully allocated the 
mp<span class="enscript-keyword">\_</span>int is placed in a default state representing the integer zero.  Otherwise, the error code <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>MEM} will be 
returned (line 29).  

The digits are allocated and set to zero at the same time with the calloc() function (line @25,XCALLOC@).  The 
<span class="enscript-keyword">\textbf</span>{used} count is set to zero, the <span class="enscript-keyword">\textbf</span>{alloc} count set to the padded digit count and the <span class="enscript-keyword">\textbf</span>{sign} flag set 
to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS} to achieve a default valid mp<span class="enscript-keyword">\_</span>int state (lines 33, 34 and 35).  If the function 
returns succesfully then it is correct to assume that the mp<span class="enscript-keyword">\_</span>int structure is in a valid state for the remainder of the 
functions to work with.

<span class="enscript-keyword">\subsection</span>{Multiple Integer Initializations and Clearings}
Occasionally a function will require a series of mp<span class="enscript-keyword">\_</span>int data types to be made available simultaneously.  
The purpose of algorithm mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>multi is to initialize a variable length array of mp<span class="enscript-keyword">\_</span>int structures in a single
statement.  It is essentially a shortcut to multiple initializations.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>multi}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Variable length array <span class="enscript-variable-name">$V_k$</span> of mp<span class="enscript-keyword">\_</span>int variables of length <span class="enscript-variable-name">$k$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The array is initialized such that each mp<span class="enscript-keyword">\_</span>int of <span class="enscript-variable-name">$V_k$</span> is ready to use. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  for <span class="enscript-variable-name">$n$</span> from 0 to <span class="enscript-variable-name">$k - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}1.1.  Initialize the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$V_n$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>init}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}1.2.  If initialization failed then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+6mm}1.2.1.  for <span class="enscript-variable-name">$j$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$n$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+9mm}1.2.1.1.  Free the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$V_j$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clear}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+6mm}1.2.2.   Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}) <span class="enscript-keyword">\\</span>
2.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>multi}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>multi.}
The algorithm will initialize the array of mp<span class="enscript-keyword">\_</span>int variables one at a time.  If a runtime error has been detected 
(<span class="enscript-keyword">\textit</span>{step 1.2}) all of the previously initialized variables are cleared.  The goal is an ``all or nothing'' 
initialization which allows for quick recovery from runtime errors.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>multi.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This function intializes a variable length list of mp<span class="enscript-keyword">\_</span>int structure pointers.  However, instead of having the mp<span class="enscript-keyword">\_</span>int
structures in an actual C array they are simply passed as arguments to the function.  This function makes use of the 
``...'' argument syntax of the C programming language.  The list is terminated with a final <span class="enscript-keyword">\textbf</span>{NULL} argument 
appended on the right.  

The function uses the ``stdarg.h'' <span class="enscript-keyword">\textit</span>{va} functions to step portably through the arguments to the function.  A count
<span class="enscript-variable-name">$n$</span> of succesfully initialized mp<span class="enscript-keyword">\_</span>int structures is maintained (line 48) such that if a failure does occur,
the algorithm can backtrack and free the previously initialized structures (lines 28 to 47).  


<span class="enscript-keyword">\subsection</span>{Clamping Excess Digits}
When a function anticipates a result will be <span class="enscript-variable-name">$n$</span> digits it is simpler to assume this is true within the body of 
the function instead of checking during the computation.  For example, a multiplication of a <span class="enscript-variable-name">$i$</span> digit number by a 
<span class="enscript-variable-name">$j$</span> digit produces a result of at most <span class="enscript-variable-name">$i + j$</span> digits.  It is entirely possible that the result is <span class="enscript-variable-name">$i + j - 1$</span> 
though, with no final carry into the last position.  However, suppose the destination had to be first expanded 
(<span class="enscript-keyword">\textit</span>{via mp<span class="enscript-keyword">\_</span>grow}) to accomodate <span class="enscript-variable-name">$i + j - 1$</span> digits than further expanded to accomodate the final carry.  
That would be a considerable waste of time since heap operations are relatively slow.

The ideal solution is to always assume the result is <span class="enscript-variable-name">$i + j$</span> and fix up the <span class="enscript-keyword">\textbf</span>{used} count after the function
terminates.  This way a single heap operation (<span class="enscript-keyword">\textit</span>{at most}) is required.  However, if the result was not checked
there would be an excess high order zero digit.  

For example, suppose the product of two integers was <span class="enscript-variable-name">$x_n = (0x_{n-1}x_{n-2}...x_0)_{\beta}$</span>.  The leading zero digit 
will not contribute to the precision of the result.  In fact, through subsequent operations more leading zero digits would
accumulate to the point the size of the integer would be prohibitive.  As a result even though the precision is very 
low the representation is excessively large.  

The mp<span class="enscript-keyword">\_</span>clamp algorithm is designed to solve this very problem.  It will trim high-order zeros by decrementing the 
<span class="enscript-keyword">\textbf</span>{used} count until a non-zero most significant digit is found.  Also in this system, zero is considered to be a 
positive number which means that if the <span class="enscript-keyword">\textbf</span>{used} count is decremented to zero, the sign must be set to 
<span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS}.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>clamp}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Any excess leading zero digits of <span class="enscript-variable-name">$a$</span> are removed <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  while <span class="enscript-variable-name">$a.used &gt; 0$</span> and <span class="enscript-variable-name">$a_{a.used - 1} = 0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}1.1  <span class="enscript-variable-name">$a.used \leftarrow a.used - 1$</span> <span class="enscript-keyword">\\</span>
2.  if <span class="enscript-variable-name">$a.used = 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}2.1  <span class="enscript-variable-name">$a.sign \leftarrow MP\_ZPOS$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>clamp}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>clamp.}
As can be expected this algorithm is very simple.  The loop on step one is expected to iterate only once or twice at
the most.  For example, this will happen in cases where there is not a carry to fill the last position.  Step two fixes the sign for 
when all of the digits are zero to ensure that the mp<span class="enscript-keyword">\_</span>int is valid at all times.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>clamp.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Note on line 28 how to test for the <span class="enscript-keyword">\textbf</span>{used} count is made on the left of the <span class="enscript-keyword">\&amp;</span><span class="enscript-keyword">\&amp;</span> operator.  In the C programming
language the terms to <span class="enscript-keyword">\&amp;</span><span class="enscript-keyword">\&amp;</span> are evaluated left to right with a boolean short-circuit if any condition fails.  This is 
important since if the <span class="enscript-keyword">\textbf</span>{used} is zero the test on the right would fetch below the array.  That is obviously 
undesirable.  The parenthesis on line 31 is used to make sure the <span class="enscript-keyword">\textbf</span>{used} count is decremented and not
the pointer ``a''.  

<span class="enscript-keyword">\section</span>*{Exercises}
<span class="enscript-keyword">\begin</span>{tabular}{cl}
<span class="enscript-variable-name">$\left [ 1 \right ]$</span> &amp; Discuss the relevance of the <span class="enscript-keyword">\textbf</span>{used} member of the mp<span class="enscript-keyword">\_</span>int structure. <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 1 \right ]$</span> &amp; Discuss the consequences of not using padding when performing allocations.  <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 2 \right ]$</span> &amp; Estimate an ideal value for <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>PREC} when performing 1024-bit RSA <span class="enscript-keyword">\\</span>
                     &amp; encryption when <span class="enscript-variable-name">$\beta = 2^{28}$</span>.  <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 1 \right ]$</span> &amp; Discuss the relevance of the algorithm mp<span class="enscript-keyword">\_</span>clamp.  What does it prevent? <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 1 \right ]$</span> &amp; Give an example of when the algorithm  mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy might be useful. <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}


<span class="enscript-comment">%%%
</span><span class="enscript-comment">% CHAPTER FOUR
</span><span class="enscript-comment">%%%
</span>
<span class="enscript-keyword">\chapter</span>{Basic Operations}

<span class="enscript-keyword">\section</span>{Introduction}
In the previous chapter a series of low level algorithms were established that dealt with initializing and maintaining
mp<span class="enscript-keyword">\_</span>int structures.  This chapter will discuss another set of seemingly non-algebraic algorithms which will form the low 
level basis of the entire library.  While these algorithm are relatively trivial it is important to understand how they
work before proceeding since these algorithms will be used almost intrinsically in the following chapters.

The algorithms in this chapter deal primarily with more ``programmer'' related tasks such as creating copies of
mp<span class="enscript-keyword">\_</span>int structures, assigning small values to mp<span class="enscript-keyword">\_</span>int structures and comparisons of the values mp<span class="enscript-keyword">\_</span>int structures
represent.   

<span class="enscript-keyword">\section</span>{Assigning Values to mp<span class="enscript-keyword">\_</span>int Structures}
<span class="enscript-keyword">\subsection</span>{Copying an mp<span class="enscript-keyword">\_</span>int}
Assigning the value that a given mp<span class="enscript-keyword">\_</span>int structure represents to another mp<span class="enscript-keyword">\_</span>int structure shall be known as making
a copy for the purposes of this text.  The copy of the mp<span class="enscript-keyword">\_</span>int will be a separate entity that represents the same
value as the mp<span class="enscript-keyword">\_</span>int it was copied from.  The mp<span class="enscript-keyword">\_</span>copy algorithm provides this functionality. 

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>copy}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.  An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Store a copy of <span class="enscript-variable-name">$a$</span> in <span class="enscript-variable-name">$b$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b.alloc &lt; a.used$</span> then grow <span class="enscript-variable-name">$b$</span> to <span class="enscript-variable-name">$a.used$</span> digits.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>grow}) <span class="enscript-keyword">\\</span>
2.  for <span class="enscript-variable-name">$n$</span> from 0 to <span class="enscript-variable-name">$a.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$b_{n} \leftarrow a_{n}$</span> <span class="enscript-keyword">\\</span>
3.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$a.used$</span> to <span class="enscript-variable-name">$b.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$b_{n} \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$b.used \leftarrow a.used$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$b.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
6.  return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>copy}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>copy.}
This algorithm copies the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> such that upon succesful termination of the algorithm the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> will
represent the same integer as the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>.  The mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> shall be a complete and distinct copy of the 
mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> meaing that the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> can be modified and it shall not affect the value of the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span>.

If <span class="enscript-variable-name">$b$</span> does not have enough room for the digits of <span class="enscript-variable-name">$a$</span> it must first have its precision augmented via the mp<span class="enscript-keyword">\_</span>grow 
algorithm.  The digits of <span class="enscript-variable-name">$a$</span> are copied over the digits of <span class="enscript-variable-name">$b$</span> and any excess digits of <span class="enscript-variable-name">$b$</span> are set to zero (step two
and three).  The <span class="enscript-keyword">\textbf</span>{used} and <span class="enscript-keyword">\textbf</span>{sign} members of <span class="enscript-variable-name">$a$</span> are finally copied over the respective members of
<span class="enscript-variable-name">$b$</span>.

<span class="enscript-keyword">\textbf</span>{Remark.}  This algorithm also introduces a new idiosyncrasy that will be used throughout the rest of the
text.  The error return codes of other algorithms are not explicitly checked in the pseudo-code presented.  For example, in 
step one of the mp<span class="enscript-keyword">\_</span>copy algorithm the return of mp<span class="enscript-keyword">\_</span>grow is not explicitly checked to ensure it succeeded.  Text space is 
limited so it is assumed that if a algorithm fails it will clear all temporarily allocated mp<span class="enscript-keyword">\_</span>ints and return
the error code itself.  However, the C code presented will demonstrate all of the error handling logic required to 
implement the pseudo-code.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>copy.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Occasionally a dependent algorithm may copy an mp<span class="enscript-keyword">\_</span>int effectively into itself such as when the input and output
mp<span class="enscript-keyword">\_</span>int structures passed to a function are one and the same.  For this case it is optimal to return immediately without 
copying digits (line 25).  

The mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> must have enough digits to accomodate the used digits of the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>.  If <span class="enscript-variable-name">$b.alloc$</span> is less than
<span class="enscript-variable-name">$a.used$</span> the algorithm mp<span class="enscript-keyword">\_</span>grow is used to augment the precision of <span class="enscript-variable-name">$b$</span> (lines 30 to 33).  In order to
simplify the inner loop that copies the digits from <span class="enscript-variable-name">$a$</span> to <span class="enscript-variable-name">$b$</span>, two aliases <span class="enscript-variable-name">$tmpa$</span> and <span class="enscript-variable-name">$tmpb$</span> point directly at the digits
of the mp<span class="enscript-keyword">\_</span>ints <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> respectively.  These aliases (lines 43 and 46) allow the compiler to access the digits without first dereferencing the
mp<span class="enscript-keyword">\_</span>int pointers and then subsequently the pointer to the digits.  

After the aliases are established the digits from <span class="enscript-variable-name">$a$</span> are copied into <span class="enscript-variable-name">$b$</span> (lines 49 to 51) and then the excess 
digits of <span class="enscript-variable-name">$b$</span> are set to zero (lines 54 to 56).  Both ``for'' loops make use of the pointer aliases and in 
fact the alias for <span class="enscript-variable-name">$b$</span> is carried through into the second ``for'' loop to clear the excess digits.  This optimization 
allows the alias to stay in a machine register fairly easy between the two loops.

<span class="enscript-keyword">\textbf</span>{Remarks.}  The use of pointer aliases is an implementation methodology first introduced in this function that will
be used considerably in other functions.  Technically, a pointer alias is simply a short hand alias used to lower the 
number of pointer dereferencing operations required to access data.  For example, a for loop may resemble

<span class="enscript-keyword">\begin</span>{alltt}
for (x = 0; x &lt; 100; x++) <span class="enscript-keyword">\{</span>
    a-&gt;num[4]-&gt;dp[x] = 0;
<span class="enscript-keyword">\}</span>
<span class="enscript-keyword">\end</span>{alltt}

This could be re-written using aliases as 

<span class="enscript-keyword">\begin</span>{alltt}
mp_digit *tmpa;
a = a-&gt;num[4]-&gt;dp;
for (x = 0; x &lt; 100; x++) <span class="enscript-keyword">\{</span>
    *a++ = 0;
<span class="enscript-keyword">\}</span>
<span class="enscript-keyword">\end</span>{alltt}

In this case an alias is used to access the 
array of digits within an mp<span class="enscript-keyword">\_</span>int structure directly.  It may seem that a pointer alias is strictly not required 
as a compiler may optimize out the redundant pointer operations.  However, there are two dominant reasons to use aliases.

The first reason is that most compilers will not effectively optimize pointer arithmetic.  For example, some optimizations 
may work for the Microsoft Visual C++ compiler (MSVC) and not for the GNU C Compiler (GCC).  Also some optimizations may 
work for GCC and not MSVC.  As such it is ideal to find a common ground for as many compilers as possible.  Pointer 
aliases optimize the code considerably before the compiler even reads the source code which means the end compiled code 
stands a better chance of being faster.

The second reason is that pointer aliases often can make an algorithm simpler to read.  Consider the first ``for'' 
loop of the function mp<span class="enscript-keyword">\_</span>copy() re-written to not use pointer aliases.

<span class="enscript-keyword">\begin</span>{alltt}
    /* copy all the digits */
    for (n = 0; n &lt; a-&gt;used; n++) <span class="enscript-keyword">\{</span>
      b-&gt;dp[n] = a-&gt;dp[n];
    <span class="enscript-keyword">\}</span>
<span class="enscript-keyword">\end</span>{alltt}

Whether this code is harder to read depends strongly on the individual.  However, it is quantifiably slightly more 
complicated as there are four variables within the statement instead of just two.

<span class="enscript-keyword">\subsubsection</span>{Nested Statements}
Another commonly used technique in the source routines is that certain sections of code are nested.  This is used in
particular with the pointer aliases to highlight code phases.  For example, a Comba multiplier (discussed in chapter six)
will typically have three different phases.  First the temporaries are initialized, then the columns calculated and 
finally the carries are propagated.  In this example the middle column production phase will typically be nested as it
uses temporary variables and aliases the most.

The nesting also simplies the source code as variables that are nested are only valid for their scope.  As a result
the various temporary variables required do not propagate into other sections of code.


<span class="enscript-keyword">\subsection</span>{Creating a Clone}
Another common operation is to make a local temporary copy of an mp<span class="enscript-keyword">\_</span>int argument.  To initialize an mp<span class="enscript-keyword">\_</span>int 
and then copy another existing mp<span class="enscript-keyword">\_</span>int into the newly intialized mp<span class="enscript-keyword">\_</span>int will be known as creating a clone.  This is 
useful within functions that need to modify an argument but do not wish to actually modify the original copy.  The 
mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy algorithm has been designed to help perform this task.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span><span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$a$</span> is initialized to be a copy of <span class="enscript-variable-name">$b$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Init <span class="enscript-variable-name">$a$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>init}) <span class="enscript-keyword">\\</span>
2.  Copy <span class="enscript-variable-name">$b$</span> to <span class="enscript-variable-name">$a$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>copy}) <span class="enscript-keyword">\\</span>
3.  Return the status of the copy operation. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy.}
This algorithm will initialize an mp<span class="enscript-keyword">\_</span>int variable and copy another previously initialized mp<span class="enscript-keyword">\_</span>int variable into it.  As 
such this algorithm will perform two operations in one step.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This will initialize <span class="enscript-keyword">\textbf</span>{a} and make it a verbatim copy of the contents of <span class="enscript-keyword">\textbf</span>{b}.  Note that 
<span class="enscript-keyword">\textbf</span>{a} will have its own memory allocated which means that <span class="enscript-keyword">\textbf</span>{b} may be cleared after the call
and <span class="enscript-keyword">\textbf</span>{a} will be left intact.  

<span class="enscript-keyword">\section</span>{Zeroing an Integer}
Reseting an mp<span class="enscript-keyword">\_</span>int to the default state is a common step in many algorithms.  The mp<span class="enscript-keyword">\_</span>zero algorithm will be the algorithm used to
perform this task.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>zero}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Zero the contents of <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$a.used \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$a.sign \leftarrow$</span> MP<span class="enscript-keyword">\_</span>ZPOS <span class="enscript-keyword">\\</span>
3.  for <span class="enscript-variable-name">$n$</span> from 0 to <span class="enscript-variable-name">$a.alloc - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$a_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>zero}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>zero.}
This algorithm simply resets a mp<span class="enscript-keyword">\_</span>int to the default state.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>zero.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

After the function is completed, all of the digits are zeroed, the <span class="enscript-keyword">\textbf</span>{used} count is zeroed and the 
<span class="enscript-keyword">\textbf</span>{sign} variable is set to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS}.

<span class="enscript-keyword">\section</span>{Sign Manipulation}
<span class="enscript-keyword">\subsection</span>{Absolute Value}
With the mp<span class="enscript-keyword">\_</span>int representation of an integer, calculating the absolute value is trivial.  The mp<span class="enscript-keyword">\_</span>abs algorithm will compute
the absolute value of an mp<span class="enscript-keyword">\_</span>int.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>abs}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Computes <span class="enscript-variable-name">$b = \vert a \vert$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Copy <span class="enscript-variable-name">$a$</span> to <span class="enscript-variable-name">$b$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>copy}) <span class="enscript-keyword">\\</span>
2.  If the copy failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$b.sign \leftarrow MP\_ZPOS$</span> <span class="enscript-keyword">\\</span>
4.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>abs}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>abs.}
This algorithm computes the absolute of an mp<span class="enscript-keyword">\_</span>int input.  First it copies <span class="enscript-variable-name">$a$</span> over <span class="enscript-variable-name">$b$</span>.  This is an example of an
algorithm where the check in mp<span class="enscript-keyword">\_</span>copy that determines if the source and destination are equal proves useful.  This allows,
for instance, the developer to pass the same mp<span class="enscript-keyword">\_</span>int as the source and destination to this function without addition 
logic to handle it.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>abs.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This fairly trivial algorithm first eliminates non--required duplications (line 28) and then sets the
<span class="enscript-keyword">\textbf</span>{sign} flag to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS}.

<span class="enscript-keyword">\subsection</span>{Integer Negation}
With the mp<span class="enscript-keyword">\_</span>int representation of an integer, calculating the negation is also trivial.  The mp<span class="enscript-keyword">\_</span>neg algorithm will compute
the negative of an mp<span class="enscript-keyword">\_</span>int input.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>neg}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Computes <span class="enscript-variable-name">$b = -a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Copy <span class="enscript-variable-name">$a$</span> to <span class="enscript-variable-name">$b$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>copy}) <span class="enscript-keyword">\\</span>
2.  If the copy failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
3.  If <span class="enscript-variable-name">$a.used = 0$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
4.  If <span class="enscript-variable-name">$a.sign = MP\_ZPOS$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$b.sign = MP\_NEG$</span>. <span class="enscript-keyword">\\</span>
5.  else do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$b.sign = MP\_ZPOS$</span>. <span class="enscript-keyword">\\</span>
6.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>neg}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>neg.}
This algorithm computes the negation of an input.  First it copies <span class="enscript-variable-name">$a$</span> over <span class="enscript-variable-name">$b$</span>.  If <span class="enscript-variable-name">$a$</span> has no used digits then
the algorithm returns immediately.  Otherwise it flips the sign flag and stores the result in <span class="enscript-variable-name">$b$</span>.  Note that if 
<span class="enscript-variable-name">$a$</span> had no digits then it must be positive by definition.  Had step three been omitted then the algorithm would return
zero as negative.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>neg.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Like mp<span class="enscript-keyword">\_</span>abs() this function avoids non--required duplications (line 22) and then sets the sign.  We
have to make sure that only non--zero values get a <span class="enscript-keyword">\textbf</span>{sign} of <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>NEG}.  If the mp<span class="enscript-keyword">\_</span>int is zero
than the <span class="enscript-keyword">\textbf</span>{sign} is hard--coded to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS}.

<span class="enscript-keyword">\section</span>{Small Constants}
<span class="enscript-keyword">\subsection</span>{Setting Small Constants}
Often a mp<span class="enscript-keyword">\_</span>int must be set to a relatively small value such as <span class="enscript-variable-name">$1$</span> or <span class="enscript-variable-name">$2$</span>.  For these cases the mp<span class="enscript-keyword">\_</span>set algorithm is useful.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>set}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and a digit <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Make <span class="enscript-variable-name">$a$</span> equivalent to <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Zero <span class="enscript-variable-name">$a$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>zero}). <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$a_0 \leftarrow b \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
3.  $a.used <span class="enscript-keyword">\leftarrow</span>  <span class="enscript-keyword">\left</span> <span class="enscript-keyword">\lbrace</span> <span class="enscript-keyword">\begin</span>{array}{ll}
                              1 &amp;  <span class="enscript-keyword">\mbox</span>{if }a_0 &gt; 0 <span class="enscript-keyword">\\</span>
                              0 &amp;  <span class="enscript-keyword">\mbox</span>{if }a_0 = 0 
                              <span class="enscript-keyword">\end</span>{array} <span class="enscript-keyword">\right</span> .$ <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>                              
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>set}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>set.}
This algorithm sets a mp<span class="enscript-keyword">\_</span>int to a small single digit value.  Step number 1 ensures that the integer is reset to the default state.  The
single digit is set (<span class="enscript-keyword">\textit</span>{modulo <span class="enscript-variable-name">$\beta$</span>}) and the <span class="enscript-keyword">\textbf</span>{used} count is adjusted accordingly.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>set.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

First we zero (line 21) the mp<span class="enscript-keyword">\_</span>int to make sure that the other members are initialized for a 
small positive constant.  mp<span class="enscript-keyword">\_</span>zero() ensures that the <span class="enscript-keyword">\textbf</span>{sign} is positive and the <span class="enscript-keyword">\textbf</span>{used} count
is zero.  Next we set the digit and reduce it modulo <span class="enscript-variable-name">$\beta$</span> (line 22).  After this step we have to 
check if the resulting digit is zero or not.  If it is not then we set the <span class="enscript-keyword">\textbf</span>{used} count to one, otherwise
to zero.

We can quickly reduce modulo <span class="enscript-variable-name">$\beta$</span> since it is of the form <span class="enscript-variable-name">$2^k$</span> and a quick binary AND operation with 
<span class="enscript-variable-name">$2^k - 1$</span> will perform the same operation.

One important limitation of this function is that it will only set one digit.  The size of a digit is not fixed, meaning source that uses 
this function should take that into account.  Only trivially small constants can be set using this function.

<span class="enscript-keyword">\subsection</span>{Setting Large Constants}
To overcome the limitations of the mp<span class="enscript-keyword">\_</span>set algorithm the mp<span class="enscript-keyword">\_</span>set<span class="enscript-keyword">\_</span>int algorithm is ideal.  It accepts a ``long''
data type as input and will always treat it as a 32-bit integer.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>set<span class="enscript-keyword">\_</span>int}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and a ``long'' integer <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Make <span class="enscript-variable-name">$a$</span> equivalent to <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Zero <span class="enscript-variable-name">$a$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>zero}) <span class="enscript-keyword">\\</span>
2.  for <span class="enscript-variable-name">$n$</span> from 0 to 7 do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$a \leftarrow a \cdot 16$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mul2d}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  <span class="enscript-variable-name">$u \leftarrow \lfloor b / 2^{4(7 - n)} \rfloor \mbox{ (mod }16\mbox{)}$</span><span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.3  <span class="enscript-variable-name">$a_0 \leftarrow a_0 + u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.4  <span class="enscript-variable-name">$a.used \leftarrow a.used + 1$</span> <span class="enscript-keyword">\\</span>
3.  Clamp excess used digits (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clamp}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>set<span class="enscript-keyword">\_</span>int}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>set<span class="enscript-keyword">\_</span>int.}
The algorithm performs eight iterations of a simple loop where in each iteration four bits from the source are added to the 
mp<span class="enscript-keyword">\_</span>int.  Step 2.1 will multiply the current result by sixteen making room for four more bits in the less significant positions.  In step 2.2 the
next four bits from the source are extracted and are added to the mp<span class="enscript-keyword">\_</span>int. The <span class="enscript-keyword">\textbf</span>{used} digit count is 
incremented to reflect the addition.  The <span class="enscript-keyword">\textbf</span>{used} digit counter is incremented since if any of the leading digits were zero the mp<span class="enscript-keyword">\_</span>int would have
zero digits used and the newly added four bits would be ignored.

Excess zero digits are trimmed in steps 2.1 and 3 by using higher level algorithms mp<span class="enscript-keyword">\_</span>mul2d and mp<span class="enscript-keyword">\_</span>clamp.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>set<span class="enscript-keyword">\_</span>int.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This function sets four bits of the number at a time to handle all practical <span class="enscript-keyword">\textbf</span>{DIGIT<span class="enscript-keyword">\_</span>BIT} sizes.  The weird
addition on line 39 ensures that the newly added in bits are added to the number of digits.  While it may not 
seem obvious as to why the digit counter does not grow exceedingly large it is because of the shift on line 28 
as well as the  call to mp<span class="enscript-keyword">\_</span>clamp() on line 41.  Both functions will clamp excess leading digits which keeps 
the number of used digits low.

<span class="enscript-keyword">\section</span>{Comparisons}
<span class="enscript-keyword">\subsection</span>{Unsigned Comparisions}
Comparing a multiple precision integer is performed with the exact same algorithm used to compare two decimal numbers.  For example,
to compare <span class="enscript-variable-name">$1,234$</span> to <span class="enscript-variable-name">$1,264$</span> the digits are extracted by their positions.  That is we compare <span class="enscript-variable-name">$1 \cdot 10^3 + 2 \cdot 10^2 + 3 \cdot 10^1 + 4 \cdot 10^0$</span>
to <span class="enscript-variable-name">$1 \cdot 10^3 + 2 \cdot 10^2 + 6 \cdot 10^1 + 4 \cdot 10^0$</span> by comparing single digits at a time starting with the highest magnitude 
positions.  If any leading digit of one integer is greater than a digit in the same position of another integer then obviously it must be greater.  

The first comparision routine that will be developed is the unsigned magnitude compare which will perform a comparison based on the digits of two
mp<span class="enscript-keyword">\_</span>int variables alone.  It will ignore the sign of the two inputs.  Such a function is useful when an absolute comparison is required or if the 
signs are known to agree in advance.

To facilitate working with the results of the comparison functions three constants are required.  

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|r|l|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Constant} &amp; <span class="enscript-keyword">\textbf</span>{Meaning} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>GT} &amp; Greater Than <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>EQ} &amp; Equal To <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>LT} &amp; Less Than <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Comparison Return Codes}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two mp<span class="enscript-keyword">\_</span>ints <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Unsigned comparison results (<span class="enscript-variable-name">$a$</span> to the left of <span class="enscript-variable-name">$b$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$a.used &gt; b.used$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>GT}) <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$a.used &lt; b.used$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>LT}) <span class="enscript-keyword">\\</span>
3.  for n from <span class="enscript-variable-name">$a.used - 1$</span> to 0 do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}3.1  if <span class="enscript-variable-name">$a_n &gt; b_n$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>GT}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}3.2  if <span class="enscript-variable-name">$a_n &lt; b_n$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>LT}) <span class="enscript-keyword">\\</span>
4.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>EQ}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag.}
By saying ``<span class="enscript-variable-name">$a$</span> to the left of <span class="enscript-variable-name">$b$</span>'' it is meant that the comparison is with respect to <span class="enscript-variable-name">$a$</span>, that is if <span class="enscript-variable-name">$a$</span> is greater than <span class="enscript-variable-name">$b$</span> it will return
<span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>GT} and similar with respect to when <span class="enscript-variable-name">$a = b$</span> and <span class="enscript-variable-name">$a &lt; b$</span>.  The first two steps compare the number of digits used in both <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>.  
Obviously if the digit counts differ there would be an imaginary zero digit in the smaller number where the leading digit of the larger number is.  
If both have the same number of digits than the actual digits themselves must be compared starting at the leading digit.  

By step three both inputs must have the same number of digits so its safe to start from either <span class="enscript-variable-name">$a.used - 1$</span> or <span class="enscript-variable-name">$b.used - 1$</span> and count down to
the zero'th digit.  If after all of the digits have been compared, no difference is found, the algorithm returns <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>EQ}.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The two if statements (lines 25 and 29) compare the number of digits in the two inputs.  These two are 
performed before all of the digits are compared since it is a very cheap test to perform and can potentially save 
considerable time.  The implementation given is also not valid without those two statements.  <span class="enscript-variable-name">$b.alloc$</span> may be 
smaller than <span class="enscript-variable-name">$a.used$</span>, meaning that undefined values will be read from <span class="enscript-variable-name">$b$</span> past the end of the array of digits.



<span class="enscript-keyword">\subsection</span>{Signed Comparisons}
Comparing with sign considerations is also fairly critical in several routines (<span class="enscript-keyword">\textit</span>{division for example}).  Based on an unsigned magnitude 
comparison a trivial signed comparison algorithm can be written.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>cmp}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two mp<span class="enscript-keyword">\_</span>ints <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Signed Comparison Results (<span class="enscript-variable-name">$a$</span> to the left of <span class="enscript-variable-name">$b$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  if <span class="enscript-variable-name">$a.sign = MP\_NEG$</span> and <span class="enscript-variable-name">$b.sign = MP\_ZPOS$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>LT}) <span class="enscript-keyword">\\</span>
2.  if <span class="enscript-variable-name">$a.sign = MP\_ZPOS$</span> and <span class="enscript-variable-name">$b.sign = MP\_NEG$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>GT}) <span class="enscript-keyword">\\</span>
3.  if <span class="enscript-variable-name">$a.sign = MP\_NEG$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}3.1  Return the unsigned comparison of <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$a$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag}) <span class="enscript-keyword">\\</span>
4   Otherwise <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}4.1  Return the unsigned comparison of <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>cmp}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>cmp.}
The first two steps compare the signs of the two inputs.  If the signs do not agree then it can return right away with the appropriate 
comparison code.  When the signs are equal the digits of the inputs must be compared to determine the correct result.  In step 
three the unsigned comparision flips the order of the arguments since they are both negative.  For instance, if <span class="enscript-variable-name">$-a &gt; -b$</span> then 
<span class="enscript-variable-name">$\vert a \vert &lt; \vert b \vert$</span>.  Step number four will compare the two when they are both positive.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>cmp.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The two if statements (lines 23 and 24) perform the initial sign comparison.  If the signs are not the equal then which ever
has the positive sign is larger.   The inputs are compared (line 32) based on magnitudes.  If the signs were both 
negative then the unsigned comparison is performed in the opposite direction (line 34).  Otherwise, the signs are assumed to 
be both positive and a forward direction unsigned comparison is performed.

<span class="enscript-keyword">\section</span>*{Exercises}
<span class="enscript-keyword">\begin</span>{tabular}{cl}
<span class="enscript-variable-name">$\left [ 2 \right ]$</span> &amp; Modify algorithm mp<span class="enscript-keyword">\_</span>set<span class="enscript-keyword">\_</span>int to accept as input a variable length array of bits. <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 3 \right ]$</span> &amp; Give the probability that algorithm mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag will have to compare <span class="enscript-variable-name">$k$</span> digits  <span class="enscript-keyword">\\</span>
                     &amp; of two random digits (of equal magnitude) before a difference is found. <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 1 \right ]$</span> &amp; Suggest a simple method to speed up the implementation of mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag based  <span class="enscript-keyword">\\</span>
                     &amp; on the observations made in the previous problem. <span class="enscript-keyword">\\</span>
                     &amp;
<span class="enscript-keyword">\end</span>{tabular}

<span class="enscript-keyword">\chapter</span>{Basic Arithmetic}
<span class="enscript-keyword">\section</span>{Introduction}
At this point algorithms for initialization, clearing, zeroing, copying, comparing and setting small constants have been 
established.  The next logical set of algorithms to develop are addition, subtraction and digit shifting algorithms.  These 
algorithms make use of the lower level algorithms and are the cruicial building block for the multiplication algorithms.  It is very important 
that these algorithms are highly optimized.  On their own they are simple <span class="enscript-variable-name">$O(n)$</span> algorithms but they can be called from higher level algorithms 
which easily places them at <span class="enscript-variable-name">$O(n^2)$</span> or even <span class="enscript-variable-name">$O(n^3)$</span> work levels.  

All of the algorithms within this chapter make use of the logical bit shift operations denoted by <span class="enscript-variable-name">$&lt;&lt;$</span> and <span class="enscript-variable-name">$&gt;&gt;$</span> for left and right 
logical shifts respectively.  A logical shift is analogous to sliding the decimal point of radix-10 representations.  For example, the real 
number <span class="enscript-variable-name">$0.9345$</span> is equivalent to <span class="enscript-variable-name">$93.45\%$</span> which is found by sliding the the decimal two places to the right (<span class="enscript-keyword">\textit</span>{multiplying by <span class="enscript-variable-name">$\beta^2 = 10^2$</span>}).  
Algebraically a binary logical shift is equivalent to a division or multiplication by a power of two.  
For example, <span class="enscript-variable-name">$a &lt;&lt; k = a \cdot 2^k$</span> while <span class="enscript-variable-name">$a &gt;&gt; k = \lfloor a/2^k \rfloor$</span>.

One significant difference between a logical shift and the way decimals are shifted is that digits below the zero'th position are removed
from the number.  For example, consider <span class="enscript-variable-name">$1101_2 &gt;&gt; 1$</span> using decimal notation this would produce <span class="enscript-variable-name">$110.1_2$</span>.  However, with a logical shift the 
result is <span class="enscript-variable-name">$110_2$</span>.  

<span class="enscript-keyword">\section</span>{Addition and Subtraction}
In common twos complement fixed precision arithmetic negative numbers are easily represented by subtraction from the modulus.  For example, with 32-bit integers
<span class="enscript-variable-name">$a - b\mbox{ (mod }2^{32}\mbox{)}$</span> is the same as <span class="enscript-variable-name">$a + (2^{32} - b) \mbox{ (mod }2^{32}\mbox{)}$</span>  since <span class="enscript-variable-name">$2^{32} \equiv 0 \mbox{ (mod }2^{32}\mbox{)}$</span>.  
As a result subtraction can be performed with a trivial series of logical operations and an addition.

However, in multiple precision arithmetic negative numbers are not represented in the same way.  Instead a sign flag is used to keep track of the
sign of the integer.  As a result signed addition and subtraction are actually implemented as conditional usage of lower level addition or 
subtraction algorithms with the sign fixed up appropriately.

The lower level algorithms will add or subtract integers without regard to the sign flag.  That is they will add or subtract the magnitude of
the integers respectively.

<span class="enscript-keyword">\subsection</span>{Low Level Addition}
An unsigned addition of multiple precision integers is performed with the same long-hand algorithm used to add decimal numbers.  That is to add the 
trailing digits first and propagate the resulting carry upwards.  Since this is a lower level algorithm the name will have a ``s<span class="enscript-keyword">\_</span>'' prefix.  
Historically that convention stems from the MPI library where ``s<span class="enscript-keyword">\_</span>'' stood for static functions that were hidden from the developer entirely.

<span class="enscript-keyword">\newpage</span>
<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two mp<span class="enscript-keyword">\_</span>ints <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The unsigned addition <span class="enscript-variable-name">$c = \vert a \vert + \vert b \vert$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  if <span class="enscript-variable-name">$a.used &gt; b.used$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}1.1  <span class="enscript-variable-name">$min \leftarrow b.used$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}1.2  <span class="enscript-variable-name">$max \leftarrow a.used$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}1.3  <span class="enscript-variable-name">$x   \leftarrow a$</span> <span class="enscript-keyword">\\</span>
2.  else  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}2.1  <span class="enscript-variable-name">$min \leftarrow a.used$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}2.2  <span class="enscript-variable-name">$max \leftarrow b.used$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}2.3  <span class="enscript-variable-name">$x   \leftarrow b$</span> <span class="enscript-keyword">\\</span>
3.  If <span class="enscript-variable-name">$c.alloc &lt; max + 1$</span> then grow <span class="enscript-variable-name">$c$</span> to hold at least <span class="enscript-variable-name">$max + 1$</span> digits (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>grow}) <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$oldused \leftarrow c.used$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$c.used \leftarrow max + 1$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$u \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
7.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$min - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}7.1  <span class="enscript-variable-name">$c_n \leftarrow a_n + b_n + u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}7.2  <span class="enscript-variable-name">$u \leftarrow c_n &gt;&gt; lg(\beta)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}7.3  <span class="enscript-variable-name">$c_n \leftarrow c_n \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
8.  if <span class="enscript-variable-name">$min \ne max$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}8.1  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$min$</span> to <span class="enscript-variable-name">$max - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+6mm}8.1.1  <span class="enscript-variable-name">$c_n \leftarrow x_n + u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+6mm}8.1.2  <span class="enscript-variable-name">$u \leftarrow c_n &gt;&gt; lg(\beta)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+6mm}8.1.3  <span class="enscript-variable-name">$c_n \leftarrow c_n \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
9.  <span class="enscript-variable-name">$c_{max} \leftarrow u$</span> <span class="enscript-keyword">\\</span>
10.  if <span class="enscript-variable-name">$olduse &gt; max$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+3mm}10.1  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$max + 1$</span> to <span class="enscript-variable-name">$oldused - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{+6mm}10.1.1  <span class="enscript-variable-name">$c_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
11.  Clamp excess digits in <span class="enscript-variable-name">$c$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clamp}) <span class="enscript-keyword">\\</span>
12.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add.}
This algorithm is loosely based on algorithm 14.7 of HAC <span class="enscript-keyword">\cite</span>[pp. 594]{HAC} but has been extended to allow the inputs to have different magnitudes.  
Coincidentally the description of algorithm A in Knuth <span class="enscript-keyword">\cite</span>[pp. 266]{TAOCPV2} shares the same deficiency as the algorithm from <span class="enscript-keyword">\cite</span>{HAC}.  Even the 
MIX pseudo  machine code presented by Knuth <span class="enscript-keyword">\cite</span>[pp. 266-267]{TAOCPV2} is incapable of handling inputs which are of different magnitudes.

The first thing that has to be accomplished is to sort out which of the two inputs is the largest.  The addition logic
will simply add all of the smallest input to the largest input and store that first part of the result in the
destination.  Then it will apply a simpler addition loop to excess digits of the larger input.

The first two steps will handle sorting the inputs such that <span class="enscript-variable-name">$min$</span> and <span class="enscript-variable-name">$max$</span> hold the digit counts of the two 
inputs.  The variable <span class="enscript-variable-name">$x$</span> will be an mp<span class="enscript-keyword">\_</span>int alias for the largest input or the second input <span class="enscript-variable-name">$b$</span> if they have the
same number of digits.  After the inputs are sorted the destination <span class="enscript-variable-name">$c$</span> is grown as required to accomodate the sum 
of the two inputs.  The original <span class="enscript-keyword">\textbf</span>{used} count of <span class="enscript-variable-name">$c$</span> is copied and set to the new used count.  

At this point the first addition loop will go through as many digit positions that both inputs have.  The carry
variable <span class="enscript-variable-name">$\mu$</span> is set to zero outside the loop.  Inside the loop an ``addition'' step requires three statements to produce
one digit of the summand.  First
two digits from <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> are added together along with the carry <span class="enscript-variable-name">$\mu$</span>.  The carry of this step is extracted and stored
in <span class="enscript-variable-name">$\mu$</span> and finally the digit of the result <span class="enscript-variable-name">$c_n$</span> is truncated within the range <span class="enscript-variable-name">$0 \le c_n &lt; \beta$</span>.

Now all of the digit positions that both inputs have in common have been exhausted.  If <span class="enscript-variable-name">$min \ne max$</span> then <span class="enscript-variable-name">$x$</span> is an alias
for one of the inputs that has more digits.  A simplified addition loop is then used to essentially copy the remaining digits
and the carry to the destination.

The final carry is stored in <span class="enscript-variable-name">$c_{max}$</span> and digits above <span class="enscript-variable-name">$max$</span> upto <span class="enscript-variable-name">$oldused$</span> are zeroed which completes the addition.


<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

We first sort (lines 28 to 36) the inputs based on magnitude and determine the <span class="enscript-variable-name">$min$</span> and <span class="enscript-variable-name">$max$</span> variables.
Note that <span class="enscript-variable-name">$x$</span> is a pointer to an mp<span class="enscript-keyword">\_</span>int assigned to the largest input, in effect it is a local alias.  Next we
grow the destination (38 to 42) ensure that it can accomodate the result of the addition. 

Similar to the implementation of mp<span class="enscript-keyword">\_</span>copy this function uses the braced code and local aliases coding style.  The three aliases that are on 
lines 56, 59 and 62 represent the two inputs and destination variables respectively.  These aliases are used to ensure the
compiler does not have to dereference <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span> or <span class="enscript-variable-name">$c$</span> (respectively) to access the digits of the respective mp<span class="enscript-keyword">\_</span>int.

The initial carry <span class="enscript-variable-name">$u$</span> will be cleared (line 65), note that <span class="enscript-variable-name">$u$</span> is of type mp<span class="enscript-keyword">\_</span>digit which ensures type 
compatibility within the implementation.  The initial addition (line 66 to 75) adds digits from
both inputs until the smallest input runs out of digits.  Similarly the conditional addition loop
(line 81 to 90) adds the remaining digits from the larger of the two inputs.  The addition is finished 
with the final carry being stored in <span class="enscript-variable-name">$tmpc$</span> (line 94).  Note the ``++'' operator within the same expression.
After line 94, <span class="enscript-variable-name">$tmpc$</span> will point to the <span class="enscript-variable-name">$c.used$</span>'th digit of the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$c$</span>.  This is useful
for the next loop (line 97 to 99) which set any old upper digits to zero.

<span class="enscript-keyword">\subsection</span>{Low Level Subtraction}
The low level unsigned subtraction algorithm is very similar to the low level unsigned addition algorithm.  The principle difference is that the
unsigned subtraction algorithm requires the result to be positive.  That is when computing <span class="enscript-variable-name">$a - b$</span> the condition <span class="enscript-variable-name">$\vert a \vert \ge \vert b\vert$</span> must 
be met for this algorithm to function properly.  Keep in mind this low level algorithm is not meant to be used in higher level algorithms directly.  
This algorithm as will be shown can be used to create functional signed addition and subtraction algorithms.


For this algorithm a new variable is required to make the description simpler.  Recall from section 1.3.1 that a mp<span class="enscript-keyword">\_</span>digit must be able to represent
the range <span class="enscript-variable-name">$0 \le x &lt; 2\beta$</span> for the algorithms to work correctly.  However, it is allowable that a mp<span class="enscript-keyword">\_</span>digit represent a larger range of values.  For 
this algorithm we will assume that the variable <span class="enscript-variable-name">$\gamma$</span> represents the number of bits available in a 
mp<span class="enscript-keyword">\_</span>digit (<span class="enscript-keyword">\textit</span>{this implies <span class="enscript-variable-name">$2^{\gamma} &gt; \beta$</span>}).  

For example, the default for LibTomMath is to use a ``unsigned long'' for the mp<span class="enscript-keyword">\_</span>digit ``type'' while <span class="enscript-variable-name">$\beta = 2^{28}$</span>.  In ISO C an ``unsigned long''
data type must be able to represent <span class="enscript-variable-name">$0 \le x &lt; 2^{32}$</span> meaning that in this case <span class="enscript-variable-name">$\gamma \ge 32$</span>.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two mp<span class="enscript-keyword">\_</span>ints <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> (<span class="enscript-variable-name">$\vert a \vert \ge \vert b \vert$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The unsigned subtraction <span class="enscript-variable-name">$c = \vert a \vert - \vert b \vert$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$min \leftarrow b.used$</span> <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$max \leftarrow a.used$</span> <span class="enscript-keyword">\\</span>
3.  If <span class="enscript-variable-name">$c.alloc &lt; max$</span> then grow <span class="enscript-variable-name">$c$</span> to hold at least <span class="enscript-variable-name">$max$</span> digits.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>grow}) <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$oldused \leftarrow c.used$</span> <span class="enscript-keyword">\\</span> 
5.  <span class="enscript-variable-name">$c.used \leftarrow max$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$u \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
7.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$min - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  <span class="enscript-variable-name">$c_n \leftarrow a_n - b_n - u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.2  <span class="enscript-variable-name">$u   \leftarrow c_n &gt;&gt; (\gamma - 1)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.3  <span class="enscript-variable-name">$c_n \leftarrow c_n \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
8.  if <span class="enscript-variable-name">$min &lt; max$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$min$</span> to <span class="enscript-variable-name">$max - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}8.1.1  <span class="enscript-variable-name">$c_n \leftarrow a_n - u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}8.1.2  <span class="enscript-variable-name">$u   \leftarrow c_n &gt;&gt; (\gamma - 1)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}8.1.3  <span class="enscript-variable-name">$c_n \leftarrow c_n \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
9. if <span class="enscript-variable-name">$oldused &gt; max$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.1  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$max$</span> to <span class="enscript-variable-name">$oldused - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}9.1.1  <span class="enscript-variable-name">$c_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
10. Clamp excess digits of <span class="enscript-variable-name">$c$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clamp}). <span class="enscript-keyword">\\</span>
11. Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub.}
This algorithm performs the unsigned subtraction of two mp<span class="enscript-keyword">\_</span>int variables under the restriction that the result must be positive.  That is when
passing variables <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> the condition that <span class="enscript-variable-name">$\vert a \vert \ge \vert b \vert$</span> must be met for the algorithm to function correctly.  This
algorithm is loosely based on algorithm 14.9 <span class="enscript-keyword">\cite</span>[pp. 595]{HAC} and is similar to algorithm S in <span class="enscript-keyword">\cite</span>[pp. 267]{TAOCPV2} as well.  As was the case
of the algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add both other references lack discussion concerning various practical details such as when the inputs differ in magnitude.

The initial sorting of the inputs is trivial in this algorithm since <span class="enscript-variable-name">$a$</span> is guaranteed to have at least the same magnitude of <span class="enscript-variable-name">$b$</span>.  Steps 1 and 2 
set the <span class="enscript-variable-name">$min$</span> and <span class="enscript-variable-name">$max$</span> variables.  Unlike the addition routine there is guaranteed to be no carry which means that the final result can be at 
most <span class="enscript-variable-name">$max$</span> digits in length as opposed to <span class="enscript-variable-name">$max + 1$</span>.  Similar to the addition algorithm the <span class="enscript-keyword">\textbf</span>{used} count of <span class="enscript-variable-name">$c$</span> is copied locally and 
set to the maximal count for the operation.

The subtraction loop that begins on step seven is essentially the same as the addition loop of algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add except single precision 
subtraction is used instead.  Note the use of the <span class="enscript-variable-name">$\gamma$</span> variable to extract the carry (<span class="enscript-keyword">\textit</span>{also known as the borrow}) within the subtraction 
loops.  Under the assumption that two's complement single precision arithmetic is used this will successfully extract the desired carry.  

For example, consider subtracting <span class="enscript-variable-name">$0101_2$</span> from <span class="enscript-variable-name">$0100_2$</span> where <span class="enscript-variable-name">$\gamma = 4$</span> and <span class="enscript-variable-name">$\beta = 2$</span>.  The least significant bit will force a carry upwards to 
the third bit which will be set to zero after the borrow.  After the very first bit has been subtracted <span class="enscript-variable-name">$4 - 1 \equiv 0011_2$</span> will remain,  When the 
third bit of <span class="enscript-variable-name">$0101_2$</span> is subtracted from the result it will cause another carry.  In this case though the carry will be forced to propagate all the 
way to the most significant bit.  

Recall that <span class="enscript-variable-name">$\beta &lt; 2^{\gamma}$</span>.  This means that if a carry does occur just before the <span class="enscript-variable-name">$lg(\beta)$</span>'th bit it will propagate all the way to the most 
significant bit.  Thus, the high order bits of the mp<span class="enscript-keyword">\_</span>digit that are not part of the actual digit will either be all zero, or all one. All that
is needed is a single zero or one bit for the carry.  Therefore a single logical shift right by <span class="enscript-variable-name">$\gamma - 1$</span> positions is sufficient to extract the 
carry.  This method of carry extraction may seem awkward but the reason for it becomes apparent when the implementation is discussed.  

If <span class="enscript-variable-name">$b$</span> has a smaller magnitude than <span class="enscript-variable-name">$a$</span> then step 9 will force the carry and copy operation to propagate through the larger input <span class="enscript-variable-name">$a$</span> into <span class="enscript-variable-name">$c$</span>.  Step
10 will ensure that any leading digits of <span class="enscript-variable-name">$c$</span> above the <span class="enscript-variable-name">$max$</span>'th position are zeroed.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Like low level addition we ``sort'' the inputs.  Except in this case the sorting is hardcoded 
(lines 25 and 26).  In reality the <span class="enscript-variable-name">$min$</span> and <span class="enscript-variable-name">$max$</span> variables are only aliases and are only 
used to make the source code easier to read.  Again the pointer alias optimization is used 
within this algorithm.  The aliases <span class="enscript-variable-name">$tmpa$</span>, <span class="enscript-variable-name">$tmpb$</span> and <span class="enscript-variable-name">$tmpc$</span> are initialized
(lines 42, 43 and 44) for <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$c$</span> respectively.

The first subtraction loop (lines 47 through 61) subtract digits from both inputs until the smaller of
the two inputs has been exhausted.  As remarked earlier there is an implementation reason for using the ``awkward'' 
method of extracting the carry (line 57).  The traditional method for extracting the carry would be to shift 
by <span class="enscript-variable-name">$lg(\beta)$</span> positions and logically AND the least significant bit.  The AND operation is required because all of 
the bits above the <span class="enscript-variable-name">$\lg(\beta)$</span>'th bit will be set to one after a carry occurs from subtraction.  This carry 
extraction requires two relatively cheap operations to extract the carry.  The other method is to simply shift the 
most significant bit to the least significant bit thus extracting the carry with a single cheap operation.  This 
optimization only works on twos compliment machines which is a safe assumption to make.

If <span class="enscript-variable-name">$a$</span> has a larger magnitude than <span class="enscript-variable-name">$b$</span> an additional loop (lines 64 through 73) is required to propagate 
the carry through <span class="enscript-variable-name">$a$</span> and copy the result to <span class="enscript-variable-name">$c$</span>.  

<span class="enscript-keyword">\subsection</span>{High Level Addition}
Now that both lower level addition and subtraction algorithms have been established an effective high level signed addition algorithm can be
established.  This high level addition algorithm will be what other algorithms and developers will use to perform addition of mp<span class="enscript-keyword">\_</span>int data 
types.  

Recall from section 5.2 that an mp<span class="enscript-keyword">\_</span>int represents an integer with an unsigned mantissa (<span class="enscript-keyword">\textit</span>{the array of digits}) and a <span class="enscript-keyword">\textbf</span>{sign} 
flag.  A high level addition is actually performed as a series of eight separate cases which can be optimized down to three unique cases.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>add}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two mp<span class="enscript-keyword">\_</span>ints <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The signed addition <span class="enscript-variable-name">$c = a + b$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  if <span class="enscript-variable-name">$a.sign = b.sign$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$c.sign \leftarrow a.sign$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  <span class="enscript-variable-name">$c \leftarrow \vert a \vert + \vert b \vert$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add})<span class="enscript-keyword">\\</span>
2.  else do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  if <span class="enscript-variable-name">$\vert a \vert &lt; \vert b \vert$</span> then do (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag})  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.1.1  <span class="enscript-variable-name">$c.sign \leftarrow b.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.1.2  <span class="enscript-variable-name">$c \leftarrow \vert b \vert - \vert a \vert$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  else do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.2.1  <span class="enscript-variable-name">$c.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.2.2  <span class="enscript-variable-name">$c \leftarrow \vert a \vert - \vert b \vert$</span> <span class="enscript-keyword">\\</span>
3.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>add}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>add.}
This algorithm performs the signed addition of two mp<span class="enscript-keyword">\_</span>int variables.  There is no reference algorithm to draw upon from 
either <span class="enscript-keyword">\cite</span>{TAOCPV2} or <span class="enscript-keyword">\cite</span>{HAC} since they both only provide unsigned operations.  The algorithm is fairly 
straightforward but restricted since subtraction can only produce positive results.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Sign of <span class="enscript-variable-name">$a$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Sign of <span class="enscript-variable-name">$b$</span>} &amp; <span class="enscript-keyword">\textbf</span>{<span class="enscript-variable-name">$\vert a \vert &gt; \vert b \vert $</span>} &amp; <span class="enscript-keyword">\textbf</span>{Unsigned Operation} &amp; <span class="enscript-keyword">\textbf</span>{Result Sign Flag} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; Yes &amp; <span class="enscript-variable-name">$c = a + b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; No  &amp; <span class="enscript-variable-name">$c = a + b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$-$</span> &amp; <span class="enscript-variable-name">$-$</span> &amp; Yes &amp; <span class="enscript-variable-name">$c = a + b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$-$</span> &amp; <span class="enscript-variable-name">$-$</span> &amp; No  &amp; <span class="enscript-variable-name">$c = a + b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> &amp;&amp;&amp;&amp;<span class="enscript-keyword">\\</span>

<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$-$</span> &amp; No  &amp; <span class="enscript-variable-name">$c = b - a$</span> &amp; <span class="enscript-variable-name">$b.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$-$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; No  &amp; <span class="enscript-variable-name">$c = b - a$</span> &amp; <span class="enscript-variable-name">$b.sign$</span> <span class="enscript-keyword">\\</span>

<span class="enscript-keyword">\hline</span> &amp;&amp;&amp;&amp;<span class="enscript-keyword">\\</span>

<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$-$</span> &amp; Yes &amp; <span class="enscript-variable-name">$c = a - b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$-$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; Yes &amp; <span class="enscript-variable-name">$c = a - b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>

<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Addition Guide Chart}
<span class="enscript-keyword">\label</span>{fig:AddChart}
<span class="enscript-keyword">\end</span>{figure}

Figure~<span class="enscript-keyword">\ref</span>{fig:AddChart} lists all of the eight possible input combinations and is sorted to show that only three 
specific cases need to be handled.  The return code of the unsigned operations at step 1.2, 2.1.2 and 2.2.2 are 
forwarded to step three to check for errors.  This simplifies the description of the algorithm considerably and best 
follows how the implementation actually was achieved.

Also note how the <span class="enscript-keyword">\textbf</span>{sign} is set before the unsigned addition or subtraction is performed.  Recall from the descriptions of algorithms
s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add and s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub that the mp<span class="enscript-keyword">\_</span>clamp function is used at the end to trim excess digits.  The mp<span class="enscript-keyword">\_</span>clamp algorithm will set the <span class="enscript-keyword">\textbf</span>{sign}
to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>ZPOS} when the <span class="enscript-keyword">\textbf</span>{used} digit count reaches zero.

For example, consider performing <span class="enscript-variable-name">$-a + a$</span> with algorithm mp<span class="enscript-keyword">\_</span>add.  By the description of the algorithm the sign is set to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>NEG} which would
produce a result of <span class="enscript-variable-name">$-0$</span>.  However, since the sign is set first then the unsigned addition is performed the subsequent usage of algorithm mp<span class="enscript-keyword">\_</span>clamp 
within algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add will force <span class="enscript-variable-name">$-0$</span> to become <span class="enscript-variable-name">$0$</span>.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The source code follows the algorithm fairly closely.  The most notable new source code addition is the usage of the <span class="enscript-variable-name">$res$</span> integer variable which
is used to pass result of the unsigned operations forward.  Unlike in the algorithm, the variable <span class="enscript-variable-name">$res$</span> is merely returned as is without
explicitly checking it and returning the constant <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>OKAY}.  The observation is this algorithm will succeed or fail only if the lower
level functions do so.  Returning their return code is sufficient.

<span class="enscript-keyword">\subsection</span>{High Level Subtraction}
The high level signed subtraction algorithm is essentially the same as the high level signed addition algorithm.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>sub}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two mp<span class="enscript-keyword">\_</span>ints <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The signed subtraction <span class="enscript-variable-name">$c = a - b$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  if <span class="enscript-variable-name">$a.sign \ne b.sign$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$c.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  <span class="enscript-variable-name">$c \leftarrow \vert a \vert + \vert b \vert$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add}) <span class="enscript-keyword">\\</span>
2.  else do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  if <span class="enscript-variable-name">$\vert a \vert \ge \vert b \vert$</span> then do (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.1.1  <span class="enscript-variable-name">$c.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.1.2  <span class="enscript-variable-name">$c \leftarrow \vert a \vert  - \vert b \vert$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  else do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.2.1  $c.sign <span class="enscript-keyword">\leftarrow</span>  <span class="enscript-keyword">\left</span> <span class="enscript-keyword">\lbrace</span> <span class="enscript-keyword">\begin</span>{array}{ll}
                              MP<span class="enscript-keyword">\_</span>ZPOS &amp;  <span class="enscript-keyword">\mbox</span>{if }a.sign = MP<span class="enscript-keyword">\_</span>NEG <span class="enscript-keyword">\\</span>
                              MP<span class="enscript-keyword">\_</span>NEG  &amp;  <span class="enscript-keyword">\mbox</span>{otherwise} <span class="enscript-keyword">\\</span>
                              <span class="enscript-keyword">\end</span>{array} <span class="enscript-keyword">\right</span> .$ <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.2.2  <span class="enscript-variable-name">$c \leftarrow \vert b \vert  - \vert a \vert$</span> <span class="enscript-keyword">\\</span>
3.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>sub}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>sub.}
This algorithm performs the signed subtraction of two inputs.  Similar to algorithm mp<span class="enscript-keyword">\_</span>add there is no reference in either <span class="enscript-keyword">\cite</span>{TAOCPV2} or 
<span class="enscript-keyword">\cite</span>{HAC}.  Also this algorithm is restricted by algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub.  Chart <span class="enscript-keyword">\ref</span>{fig:SubChart} lists the eight possible inputs and
the operations required.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Sign of <span class="enscript-variable-name">$a$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Sign of <span class="enscript-variable-name">$b$</span>} &amp; <span class="enscript-keyword">\textbf</span>{<span class="enscript-variable-name">$\vert a \vert \ge \vert b \vert $</span>} &amp; <span class="enscript-keyword">\textbf</span>{Unsigned Operation} &amp; <span class="enscript-keyword">\textbf</span>{Result Sign Flag} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$-$</span> &amp; Yes &amp; <span class="enscript-variable-name">$c = a + b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$-$</span> &amp; No  &amp; <span class="enscript-variable-name">$c = a + b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$-$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; Yes &amp; <span class="enscript-variable-name">$c = a + b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$-$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; No  &amp; <span class="enscript-variable-name">$c = a + b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> &amp;&amp;&amp;&amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; Yes &amp; <span class="enscript-variable-name">$c = a - b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$-$</span> &amp; <span class="enscript-variable-name">$-$</span> &amp; Yes &amp; <span class="enscript-variable-name">$c = a - b$</span> &amp; <span class="enscript-variable-name">$a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> &amp;&amp;&amp;&amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; No  &amp; <span class="enscript-variable-name">$c = b - a$</span> &amp; <span class="enscript-variable-name">$\mbox{opposite of }a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$-$</span> &amp; <span class="enscript-variable-name">$-$</span> &amp; No  &amp; <span class="enscript-variable-name">$c = b - a$</span> &amp; <span class="enscript-variable-name">$\mbox{opposite of }a.sign$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Subtraction Guide Chart}
<span class="enscript-keyword">\label</span>{fig:SubChart}
<span class="enscript-keyword">\end</span>{figure}

Similar to the case of algorithm mp<span class="enscript-keyword">\_</span>add the <span class="enscript-keyword">\textbf</span>{sign} is set first before the unsigned addition or subtraction.  That is to prevent the 
algorithm from producing <span class="enscript-variable-name">$-a - -a = -0$</span> as a result.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Much like the implementation of algorithm mp<span class="enscript-keyword">\_</span>add the variable <span class="enscript-variable-name">$res$</span> is used to catch the return code of the unsigned addition or subtraction operations
and forward it to the end of the function.  On line 39 the ``not equal to'' <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>LT} expression is used to emulate a 
``greater than or equal to'' comparison.  

<span class="enscript-keyword">\section</span>{Bit and Digit Shifting}
It is quite common to think of a multiple precision integer as a polynomial in <span class="enscript-variable-name">$x$</span>, that is <span class="enscript-variable-name">$y = f(\beta)$</span> where <span class="enscript-variable-name">$f(x) = \sum_{i=0}^{n-1} a_i x^i$</span>.  
This notation arises within discussion of Montgomery and Diminished Radix Reduction as well as Karatsuba multiplication and squaring.  

In order to facilitate operations on polynomials in <span class="enscript-variable-name">$x$</span> as above a series of simple ``digit'' algorithms have to be established.  That is to shift
the digits left or right as well to shift individual bits of the digits left and right.  It is important to note that not all ``shift'' operations
are on radix-<span class="enscript-variable-name">$\beta$</span> digits.  

<span class="enscript-keyword">\subsection</span>{Multiplication by Two}

In a binary system where the radix is a power of two multiplication by two not only arises often in other algorithms it is a fairly efficient 
operation to perform.  A single precision logical shift left is sufficient to multiply a single digit by two.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   One mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$b = 2a$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b.alloc &lt; a.used + 1$</span> then grow <span class="enscript-variable-name">$b$</span> to hold <span class="enscript-variable-name">$a.used + 1$</span> digits.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>grow}) <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$oldused \leftarrow b.used$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$b.used \leftarrow a.used$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$r \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
5.  for <span class="enscript-variable-name">$n$</span> from 0 to <span class="enscript-variable-name">$a.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$rr \leftarrow a_n &gt;&gt; (lg(\beta) - 1)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$b_n \leftarrow (a_n &lt;&lt; 1) + r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  <span class="enscript-variable-name">$r \leftarrow rr$</span> <span class="enscript-keyword">\\</span>
6.  If <span class="enscript-variable-name">$r \ne 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$b_{n + 1} \leftarrow r$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  <span class="enscript-variable-name">$b.used \leftarrow b.used + 1$</span> <span class="enscript-keyword">\\</span>
7.  If <span class="enscript-variable-name">$b.used &lt; oldused - 1$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$b.used$</span> to <span class="enscript-variable-name">$oldused - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.1.1  <span class="enscript-variable-name">$b_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$b.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
9.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}).<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2.}
This algorithm will quickly multiply a mp<span class="enscript-keyword">\_</span>int by two provided <span class="enscript-variable-name">$\beta$</span> is a power of two.  Neither <span class="enscript-keyword">\cite</span>{TAOCPV2} nor <span class="enscript-keyword">\cite</span>{HAC} describe such 
an algorithm despite the fact it arises often in other algorithms.  The algorithm is setup much like the lower level algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add since 
it is for all intents and purposes equivalent to the operation <span class="enscript-variable-name">$b = \vert a \vert + \vert a \vert$</span>.  

Step 1 and 2 grow the input as required to accomodate the maximum number of <span class="enscript-keyword">\textbf</span>{used} digits in the result.  The initial <span class="enscript-keyword">\textbf</span>{used} count
is set to <span class="enscript-variable-name">$a.used$</span> at step 4.  Only if there is a final carry will the <span class="enscript-keyword">\textbf</span>{used} count require adjustment.

Step 6 is an optimization implementation of the addition loop for this specific case.  That is since the two values being added together 
are the same there is no need to perform two reads from the digits of <span class="enscript-variable-name">$a$</span>.  Step 6.1 performs a single precision shift on the current digit <span class="enscript-variable-name">$a_n$</span> to
obtain what will be the carry for the next iteration.  Step 6.2 calculates the <span class="enscript-variable-name">$n$</span>'th digit of the result as single precision shift of <span class="enscript-variable-name">$a_n$</span> plus
the previous carry.  Recall from section 4.1 that <span class="enscript-variable-name">$a_n &lt;&lt; 1$</span> is equivalent to <span class="enscript-variable-name">$a_n \cdot 2$</span>.  An iteration of the addition loop is finished with 
forwarding the carry to the next iteration.

Step 7 takes care of any final carry by setting the <span class="enscript-variable-name">$a.used$</span>'th digit of the result to the carry and augmenting the <span class="enscript-keyword">\textbf</span>{used} count of <span class="enscript-variable-name">$b$</span>.  
Step 8 clears any leading digits of <span class="enscript-variable-name">$b$</span> in case it originally had a larger magnitude than <span class="enscript-variable-name">$a$</span>.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This implementation is essentially an optimized implementation of s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add for the case of doubling an input.  The only noteworthy difference
is the use of the logical shift operator on line 52 to perform a single precision doubling.  

<span class="enscript-keyword">\subsection</span>{Division by Two}
A division by two can just as easily be accomplished with a logical shift right as multiplication by two can be with a logical shift left.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   One mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$b = a/2$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b.alloc &lt; a.used$</span> then grow <span class="enscript-variable-name">$b$</span> to hold <span class="enscript-variable-name">$a.used$</span> digits.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>grow}) <span class="enscript-keyword">\\</span>
2.  If the reallocation failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$oldused \leftarrow b.used$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$b.used \leftarrow a.used$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$r \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
6.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$b.used - 1$</span> to <span class="enscript-variable-name">$0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$rr \leftarrow a_n \mbox{ (mod }2\mbox{)}$</span><span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  <span class="enscript-variable-name">$b_n \leftarrow (a_n &gt;&gt; 1) + (r &lt;&lt; (lg(\beta) - 1)) \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.3  <span class="enscript-variable-name">$r \leftarrow rr$</span> <span class="enscript-keyword">\\</span>
7.  If <span class="enscript-variable-name">$b.used &lt; oldused - 1$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$b.used$</span> to <span class="enscript-variable-name">$oldused - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.1.1  <span class="enscript-variable-name">$b_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$b.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
9.  Clamp excess digits of <span class="enscript-variable-name">$b$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clamp}) <span class="enscript-keyword">\\</span>
10.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}).<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2.}
This algorithm will divide an mp<span class="enscript-keyword">\_</span>int by two using logical shifts to the right.  Like mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2 it uses a modified low level addition
core as the basis of the algorithm.  Unlike mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2 the shift operations work from the leading digit to the trailing digit.  The algorithm
could be written to work from the trailing digit to the leading digit however, it would have to stop one short of <span class="enscript-variable-name">$a.used - 1$</span> digits to prevent
reading past the end of the array of digits.

Essentially the loop at step 6 is similar to that of mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2 except the logical shifts go in the opposite direction and the carry is at the 
least significant bit not the most significant bit.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\section</span>{Polynomial Basis Operations}
Recall from section 4.3 that any integer can be represented as a polynomial in <span class="enscript-variable-name">$x$</span> as <span class="enscript-variable-name">$y = f(\beta)$</span>.  Such a representation is also known as
the polynomial basis <span class="enscript-keyword">\cite</span>[pp. 48]{ROSE}. Given such a notation a multiplication or division by <span class="enscript-variable-name">$x$</span> amounts to shifting whole digits a single 
place.  The need for such operations arises in several other higher level algorithms such as Barrett and Montgomery reduction, integer
division and Karatsuba multiplication.  

Converting from an array of digits to polynomial basis is very simple.  Consider the integer <span class="enscript-variable-name">$y \equiv (a_2, a_1, a_0)_{\beta}$</span> and recall that
<span class="enscript-variable-name">$y = \sum_{i=0}^{2} a_i \beta^i$</span>.  Simply replace <span class="enscript-variable-name">$\beta$</span> with <span class="enscript-variable-name">$x$</span> and the expression is in polynomial basis.  For example, <span class="enscript-variable-name">$f(x) = 8x + 9$</span> is the
polynomial basis representation for <span class="enscript-variable-name">$89$</span> using radix ten.  That is, <span class="enscript-variable-name">$f(10) = 8(10) + 9 = 89$</span>.  

<span class="enscript-keyword">\subsection</span>{Multiplication by <span class="enscript-variable-name">$x$</span>}

Given a polynomial in <span class="enscript-variable-name">$x$</span> such as <span class="enscript-variable-name">$f(x) = a_n x^n + a_{n-1} x^{n-1} + ... + a_0$</span> multiplying by <span class="enscript-variable-name">$x$</span> amounts to shifting the coefficients up one 
degree.  In this case <span class="enscript-variable-name">$f(x) \cdot x = a_n x^{n+1} + a_{n-1} x^n + ... + a_0 x$</span>.  From a scalar basis point of view multiplying by <span class="enscript-variable-name">$x$</span> is equivalent to
multiplying by the integer <span class="enscript-variable-name">$\beta$</span>.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>lshd}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   One mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and an integer <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$a \leftarrow a \cdot \beta^b$</span> (equivalent to multiplication by <span class="enscript-variable-name">$x^b$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b \le 0$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$a.alloc &lt; a.used + b$</span> then grow <span class="enscript-variable-name">$a$</span> to at least <span class="enscript-variable-name">$a.used + b$</span> digits.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>grow}). <span class="enscript-keyword">\\</span>
3.  If the reallocation failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$a.used \leftarrow a.used + b$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$i \leftarrow a.used - 1$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$j \leftarrow a.used - 1 - b$</span> <span class="enscript-keyword">\\</span>
7.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$a.used - 1$</span> to <span class="enscript-variable-name">$b$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  <span class="enscript-variable-name">$a_{i} \leftarrow a_{j}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.2  <span class="enscript-variable-name">$i \leftarrow i - 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.3  <span class="enscript-variable-name">$j \leftarrow j - 1$</span> <span class="enscript-keyword">\\</span>
8.  for <span class="enscript-variable-name">$n$</span> from 0 to <span class="enscript-variable-name">$b - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  <span class="enscript-variable-name">$a_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
9.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>lshd}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>lshd.}
This algorithm multiplies an mp<span class="enscript-keyword">\_</span>int by the <span class="enscript-variable-name">$b$</span>'th power of <span class="enscript-variable-name">$x$</span>.  This is equivalent to multiplying by <span class="enscript-variable-name">$\beta^b$</span>.  The algorithm differs 
from the other algorithms presented so far as it performs the operation in place instead storing the result in a separate location.  The
motivation behind this change is due to the way this function is typically used.  Algorithms such as mp<span class="enscript-keyword">\_</span>add store the result in an optionally
different third mp<span class="enscript-keyword">\_</span>int because the original inputs are often still required.  Algorithm mp<span class="enscript-keyword">\_</span>lshd (<span class="enscript-keyword">\textit</span>{and similarly algorithm mp<span class="enscript-keyword">\_</span>rshd}) is
typically used on values where the original value is no longer required.  The algorithm will return success immediately if 
<span class="enscript-variable-name">$b \le 0$</span> since the rest of algorithm is only valid when <span class="enscript-variable-name">$b &gt; 0$</span>.  

First the destination <span class="enscript-variable-name">$a$</span> is grown as required to accomodate the result.  The counters <span class="enscript-variable-name">$i$</span> and <span class="enscript-variable-name">$j$</span> are used to form a <span class="enscript-keyword">\textit</span>{sliding window} over
the digits of <span class="enscript-variable-name">$a$</span> of length <span class="enscript-variable-name">$b$</span>.  The head of the sliding window is at <span class="enscript-variable-name">$i$</span> (<span class="enscript-keyword">\textit</span>{the leading digit}) and the tail at <span class="enscript-variable-name">$j$</span> (<span class="enscript-keyword">\textit</span>{the trailing digit}).  
The loop on step 7 copies the digit from the tail to the head.  In each iteration the window is moved down one digit.   The last loop on 
step 8 sets the lower <span class="enscript-variable-name">$b$</span> digits to zero.

<span class="enscript-keyword">\newpage</span>
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\includegraphics</span>{pics/sliding_window.ps}
<span class="enscript-keyword">\caption</span>{Sliding Window Movement}
<span class="enscript-keyword">\label</span>{pic:sliding_window}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\end</span>{center}

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>lshd.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The if statement (line 24) ensures that the <span class="enscript-variable-name">$b$</span> variable is greater than zero since we do not interpret negative
shift counts properly.  The <span class="enscript-keyword">\textbf</span>{used} count is incremented by <span class="enscript-variable-name">$b$</span> before the copy loop begins.  This elminates 
the need for an additional variable in the for loop.  The variable <span class="enscript-variable-name">$top$</span> (line 42) is an alias
for the leading digit while <span class="enscript-variable-name">$bottom$</span> (line 45) is an alias for the trailing edge.  The aliases form a 
window of exactly <span class="enscript-variable-name">$b$</span> digits over the input.  

<span class="enscript-keyword">\subsection</span>{Division by <span class="enscript-variable-name">$x$</span>}

Division by powers of <span class="enscript-variable-name">$x$</span> is easily achieved by shifting the digits right and removing any that will end up to the right of the zero'th digit.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>rshd}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   One mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and an integer <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$a \leftarrow a / \beta^b$</span> (Divide by <span class="enscript-variable-name">$x^b$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b \le 0$</span> then return. <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$a.used \le b$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  Zero <span class="enscript-variable-name">$a$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>zero}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  Return. <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$i \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$j \leftarrow b$</span> <span class="enscript-keyword">\\</span>
5.  for <span class="enscript-variable-name">$n$</span> from 0 to <span class="enscript-variable-name">$a.used - b - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$a_i \leftarrow a_j$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$i \leftarrow i + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  <span class="enscript-variable-name">$j \leftarrow j + 1$</span> <span class="enscript-keyword">\\</span>
6.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$a.used - b$</span> to <span class="enscript-variable-name">$a.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$a_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$a.used \leftarrow a.used - b$</span> <span class="enscript-keyword">\\</span>
8.  Return. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>rshd}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>rshd.}
This algorithm divides the input in place by the <span class="enscript-variable-name">$b$</span>'th power of <span class="enscript-variable-name">$x$</span>.  It is analogous to dividing by a <span class="enscript-variable-name">$\beta^b$</span> but much quicker since
it does not require single precision division.  This algorithm does not actually return an error code as it cannot fail.  

If the input <span class="enscript-variable-name">$b$</span> is less than one the algorithm quickly returns without performing any work.  If the <span class="enscript-keyword">\textbf</span>{used} count is less than or equal
to the shift count <span class="enscript-variable-name">$b$</span> then it will simply zero the input and return.

After the trivial cases of inputs have been handled the sliding window is setup.  Much like the case of algorithm mp<span class="enscript-keyword">\_</span>lshd a sliding window that
is <span class="enscript-variable-name">$b$</span> digits wide is used to copy the digits.  Unlike mp<span class="enscript-keyword">\_</span>lshd the window slides in the opposite direction from the trailing to the leading digit.  
Also the digits are copied from the leading to the trailing edge.

Once the window copy is complete the upper digits must be zeroed and the <span class="enscript-keyword">\textbf</span>{used} count decremented.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>rshd.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The only noteworthy element of this routine is the lack of a return type since it cannot fail.  Like mp<span class="enscript-keyword">\_</span>lshd() we
form a sliding window except we copy in the other direction.  After the window (line 60) we then zero
the upper digits of the input to make sure the result is correct.

<span class="enscript-keyword">\section</span>{Powers of Two}

Now that algorithms for moving single bits as well as whole digits exist algorithms for moving the ``in between'' distances are required.  For 
example, to quickly multiply by <span class="enscript-variable-name">$2^k$</span> for any <span class="enscript-variable-name">$k$</span> without using a full multiplier algorithm would prove useful.  Instead of performing single
shifts <span class="enscript-variable-name">$k$</span> times to achieve a multiplication by <span class="enscript-variable-name">$2^{\pm k}$</span> a mixture of whole digit shifting and partial digit shifting is employed.  

<span class="enscript-keyword">\subsection</span>{Multiplication by Power of Two}

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2d}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   One mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and an integer <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow a \cdot 2^b$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$c \leftarrow a$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>copy}) <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$c.alloc &lt; c.used + \lfloor b / lg(\beta) \rfloor + 2$</span> then grow <span class="enscript-variable-name">$c$</span> accordingly. <span class="enscript-keyword">\\</span>
3.  If the reallocation failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
4.  If <span class="enscript-variable-name">$b \ge lg(\beta)$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$c \leftarrow c \cdot \beta^{\lfloor b / lg(\beta) \rfloor}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>lshd}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.2  If step 4.1 failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$d \leftarrow b \mbox{ (mod }lg(\beta)\mbox{)}$</span> <span class="enscript-keyword">\\</span>
6.  If <span class="enscript-variable-name">$d \ne 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$mask \leftarrow 2^d$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  <span class="enscript-variable-name">$r \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.3  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$c.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.3.1  <span class="enscript-variable-name">$rr \leftarrow c_n &gt;&gt; (lg(\beta) - d) \mbox{ (mod }mask\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.3.2  <span class="enscript-variable-name">$c_n \leftarrow (c_n &lt;&lt; d) + r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.3.3  <span class="enscript-variable-name">$r \leftarrow rr$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.4  If <span class="enscript-variable-name">$r &gt; 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.4.1  <span class="enscript-variable-name">$c_{c.used} \leftarrow r$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.4.2  <span class="enscript-variable-name">$c.used \leftarrow c.used + 1$</span> <span class="enscript-keyword">\\</span>
7.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2d}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2d.}
This algorithm multiplies <span class="enscript-variable-name">$a$</span> by <span class="enscript-variable-name">$2^b$</span> and stores the result in <span class="enscript-variable-name">$c$</span>.  The algorithm uses algorithm mp<span class="enscript-keyword">\_</span>lshd and a derivative of algorithm mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2 to
quickly compute the product.

First the algorithm will multiply <span class="enscript-variable-name">$a$</span> by <span class="enscript-variable-name">$x^{\lfloor b / lg(\beta) \rfloor}$</span> which will ensure that the remainder multiplicand is less than 
<span class="enscript-variable-name">$\beta$</span>.  For example, if <span class="enscript-variable-name">$b = 37$</span> and <span class="enscript-variable-name">$\beta = 2^{28}$</span> then this step will multiply by <span class="enscript-variable-name">$x$</span> leaving a multiplication by <span class="enscript-variable-name">$2^{37 - 28} = 2^{9}$</span> 
left.

After the digits have been shifted appropriately at most <span class="enscript-variable-name">$lg(\beta) - 1$</span> shifts are left to perform.  Step 5 calculates the number of remaining shifts 
required.  If it is non-zero a modified shift loop is used to calculate the remaining product.  
Essentially the loop is a generic version of algorithm mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2 designed to handle any shift count in the range <span class="enscript-variable-name">$1 \le x &lt; lg(\beta)$</span>.  The <span class="enscript-variable-name">$mask$</span>
variable is used to extract the upper <span class="enscript-variable-name">$d$</span> bits to form the carry for the next iteration.  

This algorithm is loosely measured as a <span class="enscript-variable-name">$O(2n)$</span> algorithm which means that if the input is <span class="enscript-variable-name">$n$</span>-digits that it takes <span class="enscript-variable-name">$2n$</span> ``time'' to 
complete.  It is possible to optimize this algorithm down to a <span class="enscript-variable-name">$O(n)$</span> algorithm at a cost of making the algorithm slightly harder to follow.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2d.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The shifting is performed in--place which means the first step (line 25) is to copy the input to the 
destination.  We avoid calling mp<span class="enscript-keyword">\_</span>copy() by making sure the mp<span class="enscript-keyword">\_</span>ints are different.  The destination then
has to be grown (line 32) to accomodate the result.

If the shift count <span class="enscript-variable-name">$b$</span> is larger than <span class="enscript-variable-name">$lg(\beta)$</span> then a call to mp<span class="enscript-keyword">\_</span>lshd() is used to handle all of the multiples 
of <span class="enscript-variable-name">$lg(\beta)$</span>.  Leaving only a remaining shift of <span class="enscript-variable-name">$lg(\beta) - 1$</span> or fewer bits left.  Inside the actual shift 
loop (lines 46 to 76) we make use of pre--computed values <span class="enscript-variable-name">$shift$</span> and <span class="enscript-variable-name">$mask$</span>.   These are used to
extract the carry bit(s) to pass into the next iteration of the loop.  The <span class="enscript-variable-name">$r$</span> and <span class="enscript-variable-name">$rr$</span> variables form a 
chain between consecutive iterations to propagate the carry.  

<span class="enscript-keyword">\subsection</span>{Division by Power of Two}

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2d}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   One mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and an integer <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow \lfloor a / 2^b \rfloor, d \leftarrow a \mbox{ (mod }2^b\mbox{)}$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b \le 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$c \leftarrow a$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>copy}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  <span class="enscript-variable-name">$d \leftarrow 0$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>zero}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.3  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$c \leftarrow a$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$d \leftarrow a \mbox{ (mod }2^b\mbox{)}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d}) <span class="enscript-keyword">\\</span>
4.  If <span class="enscript-variable-name">$b \ge lg(\beta)$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$c \leftarrow \lfloor c/\beta^{\lfloor b/lg(\beta) \rfloor} \rfloor$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>rshd}). <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$k \leftarrow b \mbox{ (mod }lg(\beta)\mbox{)}$</span> <span class="enscript-keyword">\\</span>
6.  If <span class="enscript-variable-name">$k \ne 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$mask \leftarrow 2^k$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  <span class="enscript-variable-name">$r \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.3  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$c.used - 1$</span> to <span class="enscript-variable-name">$0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.3.1  <span class="enscript-variable-name">$rr \leftarrow c_n \mbox{ (mod }mask\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.3.2  <span class="enscript-variable-name">$c_n \leftarrow (c_n &gt;&gt; k) + (r &lt;&lt; (lg(\beta) - k))$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.3.3  <span class="enscript-variable-name">$r \leftarrow rr$</span> <span class="enscript-keyword">\\</span>
7.  Clamp excess digits of <span class="enscript-variable-name">$c$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clamp}) <span class="enscript-keyword">\\</span>
8.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2d}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2d.}
This algorithm will divide an input <span class="enscript-variable-name">$a$</span> by <span class="enscript-variable-name">$2^b$</span> and produce the quotient and remainder.  The algorithm is designed much like algorithm 
mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2d by first using whole digit shifts then single precision shifts.  This algorithm will also produce the remainder of the division
by using algorithm mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2d.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The implementation of algorithm mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2d is slightly different than the algorithm specifies.  The remainder <span class="enscript-variable-name">$d$</span> may be optionally 
ignored by passing <span class="enscript-keyword">\textbf</span>{NULL} as the pointer to the mp<span class="enscript-keyword">\_</span>int variable.    The temporary mp<span class="enscript-keyword">\_</span>int variable <span class="enscript-variable-name">$t$</span> is used to hold the 
result of the remainder operation until the end.  This allows <span class="enscript-variable-name">$d$</span> and <span class="enscript-variable-name">$a$</span> to represent the same mp<span class="enscript-keyword">\_</span>int without modifying <span class="enscript-variable-name">$a$</span> before
the quotient is obtained.

The remainder of the source code is essentially the same as the source code for mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2d.  The only significant difference is
the direction of the shifts.

<span class="enscript-keyword">\subsection</span>{Remainder of Division by Power of Two}

The last algorithm in the series of polynomial basis power of two algorithms is calculating the remainder of division by <span class="enscript-variable-name">$2^b$</span>.  This
algorithm benefits from the fact that in twos complement arithmetic <span class="enscript-variable-name">$a \mbox{ (mod }2^b\mbox{)}$</span> is the same as <span class="enscript-variable-name">$a$</span> AND <span class="enscript-variable-name">$2^b - 1$</span>.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   One mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and an integer <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow a \mbox{ (mod }2^b\mbox{)}$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b \le 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$c \leftarrow 0$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>zero}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$b &gt; a.used \cdot lg(\beta)$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$c \leftarrow a$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>copy}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  Return the result of step 2.1. <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$c \leftarrow a$</span> <span class="enscript-keyword">\\</span>
4.  If step 3 failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
5.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$\lceil b / lg(\beta) \rceil$</span> to <span class="enscript-variable-name">$c.used$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$c_n \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$k \leftarrow b \mbox{ (mod }lg(\beta)\mbox{)}$</span> <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$c_{\lfloor b / lg(\beta) \rfloor} \leftarrow c_{\lfloor b / lg(\beta) \rfloor} \mbox{ (mod }2^{k}\mbox{)}$</span>. <span class="enscript-keyword">\\</span>
8.  Clamp excess digits of <span class="enscript-variable-name">$c$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clamp}) <span class="enscript-keyword">\\</span>
9.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d.}
This algorithm will quickly calculate the value of <span class="enscript-variable-name">$a \mbox{ (mod }2^b\mbox{)}$</span>.  First if <span class="enscript-variable-name">$b$</span> is less than or equal to zero the 
result is set to zero.  If <span class="enscript-variable-name">$b$</span> is greater than the number of bits in <span class="enscript-variable-name">$a$</span> then it simply copies <span class="enscript-variable-name">$a$</span> to <span class="enscript-variable-name">$c$</span> and returns.  Otherwise, <span class="enscript-variable-name">$a$</span> 
is copied to <span class="enscript-variable-name">$b$</span>, leading digits are removed and the remaining leading digit is trimed to the exact bit count.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

We first avoid cases of <span class="enscript-variable-name">$b \le 0$</span> by simply mp<span class="enscript-keyword">\_</span>zero()'ing the destination in such cases.  Next if <span class="enscript-variable-name">$2^b$</span> is larger
than the input we just mp<span class="enscript-keyword">\_</span>copy() the input and return right away.  After this point we know we must actually
perform some work to produce the remainder.

Recalling that reducing modulo <span class="enscript-variable-name">$2^k$</span> and a binary ``and'' with <span class="enscript-variable-name">$2^k - 1$</span> are numerically equivalent we can quickly reduce 
the number.  First we zero any digits above the last digit in <span class="enscript-variable-name">$2^b$</span> (line 42).  Next we reduce the 
leading digit of both (line 46) and then mp<span class="enscript-keyword">\_</span>clamp().

<span class="enscript-keyword">\section</span>*{Exercises}
<span class="enscript-keyword">\begin</span>{tabular}{cl}
<span class="enscript-variable-name">$\left [ 3 \right ] $</span> &amp; Devise an algorithm that performs <span class="enscript-variable-name">$a \cdot 2^b$</span> for generic values of <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
                      &amp; in <span class="enscript-variable-name">$O(n)$</span> time. <span class="enscript-keyword">\\</span>
                      &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 3 \right ] $</span> &amp; Devise an efficient algorithm to multiply by small low hamming  <span class="enscript-keyword">\\</span>
                      &amp; weight values such as <span class="enscript-variable-name">$3$</span>, <span class="enscript-variable-name">$5$</span> and <span class="enscript-variable-name">$9$</span>.  Extend it to handle all values <span class="enscript-keyword">\\</span>
                      &amp; upto <span class="enscript-variable-name">$64$</span> with a hamming weight less than three. <span class="enscript-keyword">\\</span>
                      &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 2 \right ] $</span> &amp; Modify the preceding algorithm to handle values of the form <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-variable-name">$2^k - 1$</span> as well. <span class="enscript-keyword">\\</span>
                      &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 3 \right ] $</span> &amp; Using only algorithms mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>2, mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2 and mp<span class="enscript-keyword">\_</span>add create an <span class="enscript-keyword">\\</span>
                      &amp; algorithm to multiply two integers in roughly <span class="enscript-variable-name">$O(2n^2)$</span> time for <span class="enscript-keyword">\\</span>
                      &amp; any <span class="enscript-variable-name">$n$</span>-bit input.  Note that the time of addition is ignored in the <span class="enscript-keyword">\\</span>
                      &amp; calculation.  <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 5 \right ] $</span> &amp; Improve the previous algorithm to have a working time of at most <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-variable-name">$O \left (2^{(k-1)}n + \left ({2n^2 \over k} \right ) \right )$</span> for an appropriate choice of <span class="enscript-variable-name">$k$</span>.  Again ignore <span class="enscript-keyword">\\</span>
                      &amp; the cost of addition. <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 2 \right ] $</span> &amp; Devise a chart to find optimal values of <span class="enscript-variable-name">$k$</span> for the previous problem <span class="enscript-keyword">\\</span>
                      &amp; for <span class="enscript-variable-name">$n = 64 \ldots 1024$</span> in steps of <span class="enscript-variable-name">$64$</span>. <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 2 \right ] $</span> &amp; Using only algorithms mp<span class="enscript-keyword">\_</span>abs and mp<span class="enscript-keyword">\_</span>sub devise another method for <span class="enscript-keyword">\\</span>
                      &amp; calculating the result of a signed comparison. <span class="enscript-keyword">\\</span>
                      &amp;
<span class="enscript-keyword">\end</span>{tabular}

<span class="enscript-keyword">\chapter</span>{Multiplication and Squaring}
<span class="enscript-keyword">\section</span>{The Multipliers}
For most number theoretic problems including certain public key cryptographic algorithms, the ``multipliers'' form the most important subset of 
algorithms of any multiple precision integer package.  The set of multiplier algorithms include integer multiplication, squaring and modular reduction 
where in each of the algorithms single precision multiplication is the dominant operation performed.  This chapter will discuss integer multiplication 
and squaring, leaving modular reductions for the subsequent chapter.  

The importance of the multiplier algorithms is for the most part driven by the fact that certain popular public key algorithms are based on modular 
exponentiation, that is computing <span class="enscript-variable-name">$d \equiv a^b \mbox{ (mod }c\mbox{)}$</span> for some arbitrary choice of <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span>, <span class="enscript-variable-name">$c$</span> and <span class="enscript-variable-name">$d$</span>.  During a modular
exponentiation the majority<span class="enscript-keyword">\footnote</span>{Roughly speaking a modular exponentiation will spend about 40\% of the time performing modular reductions, 
35\% of the time performing squaring and 25\% of the time performing multiplications.} of the processor time is spent performing single precision 
multiplications.

For centuries general purpose multiplication has required a lengthly <span class="enscript-variable-name">$O(n^2)$</span> process, whereby each digit of one multiplicand has to be multiplied 
against every digit of the other multiplicand.  Traditional long-hand multiplication is based on this process;  while the techniques can differ the 
overall algorithm used is essentially the same.  Only ``recently'' have faster algorithms been studied.  First Karatsuba multiplication was discovered in 
1962.  This algorithm can multiply two numbers with considerably fewer single precision multiplications when compared to the long-hand approach.  
This technique led to the discovery of polynomial basis algorithms (<span class="enscript-keyword">\textit</span>{good reference?}) and subquently Fourier Transform based solutions.  

<span class="enscript-keyword">\section</span>{Multiplication}
<span class="enscript-keyword">\subsection</span>{The Baseline Multiplication}
<span class="enscript-keyword">\label</span>{sec:basemult}
<span class="enscript-keyword">\index</span>{baseline multiplication}
Computing the product of two integers in software can be achieved using a trivial adaptation of the standard <span class="enscript-variable-name">$O(n^2)$</span> long-hand multiplication
algorithm that school children are taught.  The algorithm is considered an <span class="enscript-variable-name">$O(n^2)$</span> algorithm since for two <span class="enscript-variable-name">$n$</span>-digit inputs <span class="enscript-variable-name">$n^2$</span> single precision 
multiplications are required.  More specifically for a <span class="enscript-variable-name">$m$</span> and <span class="enscript-variable-name">$n$</span> digit input <span class="enscript-variable-name">$m \cdot n$</span> single precision multiplications are required.  To 
simplify most discussions, it will be assumed that the inputs have comparable number of digits.  

The ``baseline multiplication'' algorithm is designed to act as the ``catch-all'' algorithm, only to be used when the faster algorithms cannot be 
used.  This algorithm does not use any particularly interesting optimizations and should ideally be avoided if possible.    One important 
facet of this algorithm, is that it has been modified to only produce a certain amount of output digits as resolution.  The importance of this 
modification will become evident during the discussion of Barrett modular reduction.  Recall that for a <span class="enscript-variable-name">$n$</span> and <span class="enscript-variable-name">$m$</span> digit input the product 
will be at most <span class="enscript-variable-name">$n + m$</span> digits.  Therefore, this algorithm can be reduced to a full multiplier by having it produce <span class="enscript-variable-name">$n + m$</span> digits of the product.  

Recall from sub-section 4.2.2 the definition of <span class="enscript-variable-name">$\gamma$</span> as the number of bits in the type <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>digit}.  We shall now extend the variable set to 
include <span class="enscript-variable-name">$\alpha$</span> which shall represent the number of bits in the type <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>word}.  This implies that <span class="enscript-variable-name">$2^{\alpha} &gt; 2 \cdot \beta^2$</span>.  The 
constant <span class="enscript-variable-name">$\delta = 2^{\alpha - 2lg(\beta)}$</span> will represent the maximal weight of any column in a product (<span class="enscript-keyword">\textit</span>{see sub-section 5.2.2 for more information}).

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>, mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> and an integer <span class="enscript-variable-name">$digs$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow \vert a \vert \cdot \vert b \vert \mbox{ (mod }\beta^{digs}\mbox{)}$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If min<span class="enscript-variable-name">$(a.used, b.used) &lt; \delta$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  Calculate <span class="enscript-variable-name">$c = \vert a \vert \cdot \vert b \vert$</span> by the Comba method (<span class="enscript-keyword">\textit</span>{see algorithm~<span class="enscript-keyword">\ref</span>{fig:COMBAMULT}}).  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  Return the result of step 1.1 <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Allocate and initialize a temporary mp<span class="enscript-keyword">\_</span>int. <span class="enscript-keyword">\\</span>
2.  Init <span class="enscript-variable-name">$t$</span> to be of size <span class="enscript-variable-name">$digs$</span> <span class="enscript-keyword">\\</span>
3.  If step 2 failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$t.used \leftarrow digs$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Compute the product. <span class="enscript-keyword">\\</span>
5.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$a.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$u \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$pb \leftarrow \mbox{min}(b.used, digs - ix)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  If <span class="enscript-variable-name">$pb &lt; 1$</span> then goto step 6. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.4  for <span class="enscript-variable-name">$iy$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$pb - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.4.1  <span class="enscript-variable-name">$\hat r \leftarrow t_{iy + ix} + a_{ix} \cdot b_{iy} + u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.4.2  <span class="enscript-variable-name">$t_{iy + ix} \leftarrow \hat r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.4.3  <span class="enscript-variable-name">$u \leftarrow \lfloor \hat r / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.5  if <span class="enscript-variable-name">$ix + pb &lt; digs$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.5.1  <span class="enscript-variable-name">$t_{ix + pb} \leftarrow u$</span> <span class="enscript-keyword">\\</span>
6.  Clamp excess digits of <span class="enscript-variable-name">$t$</span>. <span class="enscript-keyword">\\</span>
7.  Swap <span class="enscript-variable-name">$c$</span> with <span class="enscript-variable-name">$t$</span> <span class="enscript-keyword">\\</span>
8.  Clear <span class="enscript-variable-name">$t$</span> <span class="enscript-keyword">\\</span>
9.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs.}
This algorithm computes the unsigned product of two inputs <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>, limited to an output precision of <span class="enscript-variable-name">$digs$</span> digits.  While it may seem
a bit awkward to modify the function from its simple <span class="enscript-variable-name">$O(n^2)$</span> description, the usefulness of partial multipliers will arise in a subsequent 
algorithm.  The algorithm is loosely based on algorithm 14.12 from <span class="enscript-keyword">\cite</span>[pp. 595]{HAC} and is similar to Algorithm M of Knuth <span class="enscript-keyword">\cite</span>[pp. 268]{TAOCPV2}.  
Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs differs from these cited references since it can produce a variable output precision regardless of the precision of the 
inputs.

The first thing this algorithm checks for is whether a Comba multiplier can be used instead.   If the minimum digit count of either
input is less than <span class="enscript-variable-name">$\delta$</span>, then the Comba method may be used instead.    After the Comba method is ruled out, the baseline algorithm begins.  A 
temporary mp<span class="enscript-keyword">\_</span>int variable <span class="enscript-variable-name">$t$</span> is used to hold the intermediate result of the product.  This allows the algorithm to be used to 
compute products when either <span class="enscript-variable-name">$a = c$</span> or <span class="enscript-variable-name">$b = c$</span> without overwriting the inputs.  

All of step 5 is the infamous <span class="enscript-variable-name">$O(n^2)$</span> multiplication loop slightly modified to only produce upto <span class="enscript-variable-name">$digs$</span> digits of output.  The <span class="enscript-variable-name">$pb$</span> variable
is given the count of digits to read from <span class="enscript-variable-name">$b$</span> inside the nested loop.  If <span class="enscript-variable-name">$pb \le 1$</span> then no more output digits can be produced and the algorithm
will exit the loop.  The best way to think of the loops are as a series of <span class="enscript-variable-name">$pb \times 1$</span> multiplications.    That is, in each pass of the 
innermost loop <span class="enscript-variable-name">$a_{ix}$</span> is multiplied against <span class="enscript-variable-name">$b$</span> and the result is added (<span class="enscript-keyword">\textit</span>{with an appropriate shift}) to <span class="enscript-variable-name">$t$</span>.  

For example, consider multiplying <span class="enscript-variable-name">$576$</span> by <span class="enscript-variable-name">$241$</span>.  That is equivalent to computing <span class="enscript-variable-name">$10^0(1)(576) + 10^1(4)(576) + 10^2(2)(576)$</span> which is best
visualized in the following table.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|c|c|c|l|}
<span class="enscript-keyword">\hline</span>   &amp;&amp;          &amp; 5 &amp; 7 &amp; 6 &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>   <span class="enscript-variable-name">$\times$</span>&amp;&amp;  &amp; 2 &amp; 4 &amp; 1 &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> &amp;&amp;&amp;&amp;&amp;&amp;<span class="enscript-keyword">\\</span>
  &amp;&amp;          &amp; 5 &amp; 7 &amp; 6 &amp; <span class="enscript-variable-name">$10^0(1)(576)$</span> <span class="enscript-keyword">\\</span>
  &amp;2 &amp;   3    &amp; 6 &amp; 1 &amp; 6 &amp; <span class="enscript-variable-name">$10^1(4)(576) + 10^0(1)(576)$</span> <span class="enscript-keyword">\\</span>
  1 &amp; 3 &amp; 8 &amp; 8 &amp; 1 &amp; 6 &amp;   <span class="enscript-variable-name">$10^2(2)(576) + 10^1(4)(576) + 10^0(1)(576)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>  
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Long-Hand Multiplication Diagram}
<span class="enscript-keyword">\end</span>{figure}

Each row of the product is added to the result after being shifted to the left (<span class="enscript-keyword">\textit</span>{multiplied by a power of the radix}) by the appropriate 
count.  That is in pass <span class="enscript-variable-name">$ix$</span> of the inner loop the product is added starting at the <span class="enscript-variable-name">$ix$</span>'th digit of the reult.

Step 5.4.1 introduces the hat symbol (<span class="enscript-keyword">\textit</span>{e.g. <span class="enscript-variable-name">$\hat r$</span>}) which represents a double precision variable.  The multiplication on that step
is assumed to be a double wide output single precision multiplication.  That is, two single precision variables are multiplied to produce a
double precision result.  The step is somewhat optimized from a long-hand multiplication algorithm because the carry from the addition in step
5.4.1 is propagated through the nested loop.  If the carry was not propagated immediately it would overflow the single precision digit 
<span class="enscript-variable-name">$t_{ix+iy}$</span> and the result would be lost.  

At step 5.5 the nested loop is finished and any carry that was left over should be forwarded.  The carry does not have to be added to the <span class="enscript-variable-name">$ix+pb$</span>'th
digit since that digit is assumed to be zero at this point.  However, if <span class="enscript-variable-name">$ix + pb \ge digs$</span> the carry is not set as it would make the result
exceed the precision requested.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

First we determine (line 31) if the Comba method can be used first since it's faster.  The conditions for 
sing the Comba routine are that min<span class="enscript-variable-name">$(a.used, b.used) &lt; \delta$</span> and the number of digits of output is less than 
<span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>WARRAY}.  This new constant is used to control the stack usage in the Comba routines.  By default it is 
set to <span class="enscript-variable-name">$\delta$</span> but can be reduced when memory is at a premium.

If we cannot use the Comba method we proceed to setup the baseline routine.  We allocate the the destination mp<span class="enscript-keyword">\_</span>int
<span class="enscript-variable-name">$t$</span> (line 37) to the exact size of the output to avoid further re--allocations.  At this point we now 
begin the <span class="enscript-variable-name">$O(n^2)$</span> loop.

This implementation of multiplication has the caveat that it can be trimmed to only produce a variable number of
digits as output.  In each iteration of the outer loop the <span class="enscript-variable-name">$pb$</span> variable is set (line 49) to the maximum 
number of inner loop iterations.  

Inside the inner loop we calculate <span class="enscript-variable-name">$\hat r$</span> as the mp<span class="enscript-keyword">\_</span>word product of the two mp<span class="enscript-keyword">\_</span>digits and the addition of the
carry from the previous iteration.  A particularly important observation is that most modern optimizing 
C compilers (GCC for instance) can recognize that a <span class="enscript-variable-name">$N \times N \rightarrow 2N$</span> multiplication is all that 
is required for the product.  In x86 terms for example, this means using the MUL instruction.

Each digit of the product is stored in turn (line 69) and the carry propagated (line 72) to the 
next iteration.

<span class="enscript-keyword">\subsection</span>{Faster Multiplication by the ``Comba'' Method}

One of the huge drawbacks of the ``baseline'' algorithms is that at the <span class="enscript-variable-name">$O(n^2)$</span> level the carry must be 
computed and propagated upwards.  This makes the nested loop very sequential and hard to unroll and implement 
in parallel.  The ``Comba'' <span class="enscript-keyword">\cite</span>{COMBA} method is named after little known (<span class="enscript-keyword">\textit</span>{in cryptographic venues}) Paul G. 
Comba who described a method of implementing fast multipliers that do not require nested carry fixup operations.  As an 
interesting aside it seems that Paul Barrett describes a similar technique in his 1986 paper <span class="enscript-keyword">\cite</span>{BARRETT} written 
five years before.

At the heart of the Comba technique is once again the long-hand algorithm.  Except in this case a slight 
twist is placed on how the columns of the result are produced.  In the standard long-hand algorithm rows of products 
are produced then added together to form the final result.  In the baseline algorithm the columns are added together 
after each iteration to get the result instantaneously.  

In the Comba algorithm the columns of the result are produced entirely independently of each other.  That is at 
the <span class="enscript-variable-name">$O(n^2)$</span> level a simple multiplication and addition step is performed.  The carries of the columns are propagated 
after the nested loop to reduce the amount of work requiored. Succintly the first step of the algorithm is to compute 
the product vector <span class="enscript-variable-name">$\vec x$</span> as follows. 

<span class="enscript-keyword">\begin</span>{equation}
<span class="enscript-keyword">\vec</span> x_n = <span class="enscript-keyword">\sum</span>_{i+j = n} a_ib_j, <span class="enscript-keyword">\forall</span> n <span class="enscript-keyword">\in</span> <span class="enscript-keyword">\lbrace</span> 0, 1, 2, <span class="enscript-keyword">\ldots</span>, i + j <span class="enscript-keyword">\rbrace</span>
<span class="enscript-keyword">\end</span>{equation}

Where <span class="enscript-variable-name">$\vec x_n$</span> is the <span class="enscript-variable-name">$n'th$</span> column of the output vector.  Consider the following example which computes the vector <span class="enscript-variable-name">$\vec x$</span> for the multiplication
of <span class="enscript-variable-name">$576$</span> and <span class="enscript-variable-name">$241$</span>.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|c|c|c|}
  <span class="enscript-keyword">\hline</span> &amp;          &amp; 5 &amp; 7 &amp; 6 &amp; First Input<span class="enscript-keyword">\\</span>
  <span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$\times$</span> &amp; &amp; 2 &amp; 4 &amp; 1 &amp; Second Input<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>            &amp;                        &amp; <span class="enscript-variable-name">$1 \cdot 5 = 5$</span>   &amp; <span class="enscript-variable-name">$1 \cdot 7 = 7$</span>   &amp; <span class="enscript-variable-name">$1 \cdot 6 = 6$</span> &amp; First pass <span class="enscript-keyword">\\</span>
                  &amp;  <span class="enscript-variable-name">$4 \cdot 5 = 20$</span>      &amp; <span class="enscript-variable-name">$4 \cdot 7+5=33$</span>  &amp; <span class="enscript-variable-name">$4 \cdot 6+7=31$</span>  &amp; 6               &amp; Second pass <span class="enscript-keyword">\\</span>
   <span class="enscript-variable-name">$2 \cdot 5 = 10$</span> &amp;  <span class="enscript-variable-name">$2 \cdot 7 + 20 = 34$</span> &amp; <span class="enscript-variable-name">$2 \cdot 6+33=45$</span> &amp; 31                &amp; 6             &amp; Third pass <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> 10 &amp; 34 &amp; 45 &amp; 31 &amp; 6 &amp; Final Result <span class="enscript-keyword">\\</span>   
<span class="enscript-keyword">\hline</span>   
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Comba Multiplication Diagram}
<span class="enscript-keyword">\end</span>{figure}

At this point the vector <span class="enscript-variable-name">$x = \left &lt; 10, 34, 45, 31, 6 \right &gt;$</span> is the result of the first step of the Comba multipler.  
Now the columns must be fixed by propagating the carry upwards.  The resultant vector will have one extra dimension over the input vector which is
congruent to adding a leading zero digit.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Comba Fixup}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Vector <span class="enscript-variable-name">$\vec x$</span> of dimension <span class="enscript-variable-name">$k$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  Vector <span class="enscript-variable-name">$\vec x$</span> such that the carries have been propagated. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$k - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1 <span class="enscript-variable-name">$\vec x_{n+1} \leftarrow \vec x_{n+1} + \lfloor \vec x_{n}/\beta \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2 <span class="enscript-variable-name">$\vec x_{n} \leftarrow \vec x_{n} \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
2.  Return(<span class="enscript-variable-name">$\vec x$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Comba Fixup}
<span class="enscript-keyword">\end</span>{figure}

With that algorithm and <span class="enscript-variable-name">$k = 5$</span> and <span class="enscript-variable-name">$\beta = 10$</span> the following vector is produced <span class="enscript-variable-name">$\vec x= \left &lt; 1, 3, 8, 8, 1, 6 \right &gt;$</span>.  In this case 
<span class="enscript-variable-name">$241 \cdot 576$</span> is in fact <span class="enscript-variable-name">$138816$</span> and the procedure succeeded.  If the algorithm is correct and as will be demonstrated shortly more
efficient than the baseline algorithm why not simply always use this algorithm?

<span class="enscript-keyword">\subsubsection</span>{Column Weight.}
At the nested <span class="enscript-variable-name">$O(n^2)$</span> level the Comba method adds the product of two single precision variables to each column of the output 
independently.  A serious obstacle is if the carry is lost, due to lack of precision before the algorithm has a chance to fix
the carries.  For example, in the multiplication of two three-digit numbers the third column of output will be the sum of
three single precision multiplications.  If the precision of the accumulator for the output digits is less then <span class="enscript-variable-name">$3 \cdot (\beta - 1)^2$</span> then
an overflow can occur and the carry information will be lost.  For any <span class="enscript-variable-name">$m$</span> and <span class="enscript-variable-name">$n$</span> digit inputs the maximum weight of any column is 
min<span class="enscript-variable-name">$(m, n)$</span> which is fairly obvious.

The maximum number of terms in any column of a product is known as the ``column weight'' and strictly governs when the algorithm can be used.  Recall
from earlier that a double precision type has <span class="enscript-variable-name">$\alpha$</span> bits of resolution and a single precision digit has <span class="enscript-variable-name">$lg(\beta)$</span> bits of precision.  Given these
two quantities we must not violate the following

<span class="enscript-keyword">\begin</span>{equation}
k <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\left</span> (<span class="enscript-keyword">\beta</span> - 1 <span class="enscript-keyword">\right</span> )^2 &lt; 2^{<span class="enscript-keyword">\alpha</span>}
<span class="enscript-keyword">\end</span>{equation}

Which reduces to 

<span class="enscript-keyword">\begin</span>{equation}
k <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\left</span> ( <span class="enscript-keyword">\beta</span>^2 - 2<span class="enscript-keyword">\beta</span> + 1 <span class="enscript-keyword">\right</span> ) &lt; 2^{<span class="enscript-keyword">\alpha</span>}
<span class="enscript-keyword">\end</span>{equation}

Let <span class="enscript-variable-name">$\rho = lg(\beta)$</span> represent the number of bits in a single precision digit.  By further re-arrangement of the equation the final solution is
found.

<span class="enscript-keyword">\begin</span>{equation}
k  &lt; {{2^{<span class="enscript-keyword">\alpha</span>}} <span class="enscript-keyword">\over</span> {<span class="enscript-keyword">\left</span> (2^{2<span class="enscript-keyword">\rho</span>} - 2^{<span class="enscript-keyword">\rho</span> + 1} + 1 <span class="enscript-keyword">\right</span> )}}
<span class="enscript-keyword">\end</span>{equation}

The defaults for LibTomMath are <span class="enscript-variable-name">$\beta = 2^{28}$</span> and <span class="enscript-variable-name">$\alpha = 2^{64}$</span> which means that <span class="enscript-variable-name">$k$</span> is bounded by <span class="enscript-variable-name">$k &lt; 257$</span>.  In this configuration 
the smaller input may not have more than <span class="enscript-variable-name">$256$</span> digits if the Comba method is to be used.  This is quite satisfactory for most applications since 
<span class="enscript-variable-name">$256$</span> digits would allow for numbers in the range of <span class="enscript-variable-name">$0 \le x &lt; 2^{7168}$</span> which, is much larger than most public key cryptographic algorithms require.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>, mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> and an integer <span class="enscript-variable-name">$digs$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow \vert a \vert \cdot \vert b \vert \mbox{ (mod }\beta^{digs}\mbox{)}$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
Place an array of <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>WARRAY} single precision digits named <span class="enscript-variable-name">$W$</span> on the stack. <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$c.alloc &lt; digs$</span> then grow <span class="enscript-variable-name">$c$</span> to <span class="enscript-variable-name">$digs$</span> digits. (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>grow}) <span class="enscript-keyword">\\</span>
2.  If step 1 failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}).<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$pa \leftarrow \mbox{MIN}(digs, a.used + b.used)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$\_ \hat W \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
5.  for <span class="enscript-variable-name">$ix$</span> from 0 to <span class="enscript-variable-name">$pa - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$ty \leftarrow \mbox{MIN}(b.used - 1, ix)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$tx \leftarrow ix - ty$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  <span class="enscript-variable-name">$iy \leftarrow \mbox{MIN}(a.used - tx, ty + 1)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.4  for <span class="enscript-variable-name">$iz$</span> from 0 to <span class="enscript-variable-name">$iy - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.4.1  <span class="enscript-variable-name">$\_ \hat W \leftarrow \_ \hat W + a_{tx+iy}b_{ty-iy}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.5  <span class="enscript-variable-name">$W_{ix} \leftarrow \_ \hat W (\mbox{mod }\beta)$</span><span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.6  <span class="enscript-variable-name">$\_ \hat W \leftarrow \lfloor \_ \hat W / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$oldused \leftarrow c.used$</span> <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$c.used \leftarrow digs$</span> <span class="enscript-keyword">\\</span>
8.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$pa$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  <span class="enscript-variable-name">$c_{ix} \leftarrow W_{ix}$</span> <span class="enscript-keyword">\\</span>
9.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$pa + 1$</span> to <span class="enscript-variable-name">$oldused - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.1 <span class="enscript-variable-name">$c_{ix} \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
10.  Clamp <span class="enscript-variable-name">$c$</span>. <span class="enscript-keyword">\\</span>
11.  Return MP<span class="enscript-keyword">\_</span>OKAY. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs}
<span class="enscript-keyword">\label</span>{fig:COMBAMULT}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs.}
This algorithm performs the unsigned multiplication of <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> using the Comba method limited to <span class="enscript-variable-name">$digs$</span> digits of precision.

The outer loop of this algorithm is more complicated than that of the baseline multiplier.  This is because on the inside of the 
loop we want to produce one column per pass.  This allows the accumulator <span class="enscript-variable-name">$\_ \hat W$</span> to be placed in CPU registers and
reduce the memory bandwidth to two <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>digit} reads per iteration.

The <span class="enscript-variable-name">$ty$</span> variable is set to the minimum count of <span class="enscript-variable-name">$ix$</span> or the number of digits in <span class="enscript-variable-name">$b$</span>.  That way if <span class="enscript-variable-name">$a$</span> has more digits than
<span class="enscript-variable-name">$b$</span> this will be limited to <span class="enscript-variable-name">$b.used - 1$</span>.  The <span class="enscript-variable-name">$tx$</span> variable is set to the to the distance past <span class="enscript-variable-name">$b.used$</span> the variable
<span class="enscript-variable-name">$ix$</span> is.  This is used for the immediately subsequent statement where we find <span class="enscript-variable-name">$iy$</span>.  

The variable <span class="enscript-variable-name">$iy$</span> is the minimum digits we can read from either <span class="enscript-variable-name">$a$</span> or <span class="enscript-variable-name">$b$</span> before running out.  Computing one column at a time
means we have to scan one integer upwards and the other downwards.  <span class="enscript-variable-name">$a$</span> starts at <span class="enscript-variable-name">$tx$</span> and <span class="enscript-variable-name">$b$</span> starts at <span class="enscript-variable-name">$ty$</span>.  In each
pass we are producing the <span class="enscript-variable-name">$ix$</span>'th output column and we note that <span class="enscript-variable-name">$tx + ty = ix$</span>.  As we move <span class="enscript-variable-name">$tx$</span> upwards we have to 
move <span class="enscript-variable-name">$ty$</span> downards so the equality remains valid.  The <span class="enscript-variable-name">$iy$</span> variable is the number of iterations until 
<span class="enscript-variable-name">$tx \ge a.used$</span> or <span class="enscript-variable-name">$ty &lt; 0$</span> occurs.

After every inner pass we store the lower half of the accumulator into <span class="enscript-variable-name">$W_{ix}$</span> and then propagate the carry of the accumulator
into the next round by dividing <span class="enscript-variable-name">$\_ \hat W$</span> by <span class="enscript-variable-name">$\beta$</span>.

To measure the benefits of the Comba method over the baseline method consider the number of operations that are required.  If the 
cost in terms of time of a multiply and addition is <span class="enscript-variable-name">$p$</span> and the cost of a carry propagation is <span class="enscript-variable-name">$q$</span> then a baseline multiplication would require 
<span class="enscript-variable-name">$O \left ((p + q)n^2 \right )$</span> time to multiply two <span class="enscript-variable-name">$n$</span>-digit numbers.  The Comba method requires only <span class="enscript-variable-name">$O(pn^2 + qn)$</span> time, however in practice, 
the speed increase is actually much more.  With <span class="enscript-variable-name">$O(n)$</span> space the algorithm can be reduced to <span class="enscript-variable-name">$O(pn + qn)$</span> time by implementing the <span class="enscript-variable-name">$n$</span> multiply
and addition operations in the nested loop in parallel.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

As per the pseudo--code we first calculate <span class="enscript-variable-name">$pa$</span> (line 48) as the number of digits to output.  Next we begin the outer loop
to produce the individual columns of the product.  We use the two aliases <span class="enscript-variable-name">$tmpx$</span> and <span class="enscript-variable-name">$tmpy$</span> (lines 62, 63) to point
inside the two multiplicands quickly.  

The inner loop (lines 71 to 74) of this implementation is where the tradeoff come into play.  Originally this comba 
implementation was ``row--major'' which means it adds to each of the columns in each pass.  After the outer loop it would then fix 
the carries.  This was very fast except it had an annoying drawback.  You had to read a mp<span class="enscript-keyword">\_</span>word and two mp<span class="enscript-keyword">\_</span>digits and write 
one mp<span class="enscript-keyword">\_</span>word per iteration.  On processors such as the Athlon XP and P4 this did not matter much since the cache bandwidth 
is very high and it can keep the ALU fed with data.  It did, however, matter on older and embedded cpus where cache is often 
slower and also often doesn't exist.  This new algorithm only performs two reads per iteration under the assumption that the 
compiler has aliased <span class="enscript-variable-name">$\_ \hat W$</span> to a CPU register.

After the inner loop we store the current accumulator in <span class="enscript-variable-name">$W$</span> and shift <span class="enscript-variable-name">$\_ \hat W$</span> (lines 77, 80) to forward it as 
a carry for the next pass.  After the outer loop we use the final carry (line 77) as the last digit of the product.  

<span class="enscript-keyword">\subsection</span>{Polynomial Basis Multiplication}
To break the <span class="enscript-variable-name">$O(n^2)$</span> barrier in multiplication requires a completely different look at integer multiplication.  In the following algorithms
the use of polynomial basis representation for two integers <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> as <span class="enscript-variable-name">$f(x) = \sum_{i=0}^{n} a_i x^i$</span> and  
<span class="enscript-variable-name">$g(x) = \sum_{i=0}^{n} b_i x^i$</span> respectively, is required.  In this system both <span class="enscript-variable-name">$f(x)$</span> and <span class="enscript-variable-name">$g(x)$</span> have <span class="enscript-variable-name">$n + 1$</span> terms and are of the <span class="enscript-variable-name">$n$</span>'th degree.
 
The product <span class="enscript-variable-name">$a \cdot b \equiv f(x)g(x)$</span> is the polynomial <span class="enscript-variable-name">$W(x) = \sum_{i=0}^{2n} w_i x^i$</span>.  The coefficients <span class="enscript-variable-name">$w_i$</span> will
directly yield the desired product when <span class="enscript-variable-name">$\beta$</span> is substituted for <span class="enscript-variable-name">$x$</span>.  The direct solution to solve for the <span class="enscript-variable-name">$2n + 1$</span> coefficients
requires <span class="enscript-variable-name">$O(n^2)$</span> time and would in practice be slower than the Comba technique.

However, numerical analysis theory indicates that only <span class="enscript-variable-name">$2n + 1$</span> distinct points in <span class="enscript-variable-name">$W(x)$</span> are required to determine the values of the <span class="enscript-variable-name">$2n + 1$</span> unknown 
coefficients.   This means by finding <span class="enscript-variable-name">$\zeta_y = W(y)$</span> for <span class="enscript-variable-name">$2n + 1$</span> small values of <span class="enscript-variable-name">$y$</span> the coefficients of <span class="enscript-variable-name">$W(x)$</span> can be found with 
Gaussian elimination.  This technique is also occasionally refered to as the <span class="enscript-keyword">\textit</span>{interpolation technique} (<span class="enscript-keyword">\textit</span>{references please...}) since in 
effect an interpolation based on <span class="enscript-variable-name">$2n + 1$</span> points will yield a polynomial equivalent to <span class="enscript-variable-name">$W(x)$</span>.  

The coefficients of the polynomial <span class="enscript-variable-name">$W(x)$</span> are unknown which makes finding <span class="enscript-variable-name">$W(y)$</span> for any value of <span class="enscript-variable-name">$y$</span> impossible.  However, since 
<span class="enscript-variable-name">$W(x) = f(x)g(x)$</span> the equivalent <span class="enscript-variable-name">$\zeta_y = f(y) g(y)$</span> can be used in its place.  The benefit of this technique stems from the 
fact that <span class="enscript-variable-name">$f(y)$</span> and <span class="enscript-variable-name">$g(y)$</span> are much smaller than either <span class="enscript-variable-name">$a$</span> or <span class="enscript-variable-name">$b$</span> respectively.  As a result finding the <span class="enscript-variable-name">$2n + 1$</span> relations required 
by multiplying <span class="enscript-variable-name">$f(y)g(y)$</span> involves multiplying integers that are much smaller than either of the inputs.

When picking points to gather relations there are always three obvious points to choose, <span class="enscript-variable-name">$y = 0, 1$</span> and <span class="enscript-variable-name">$ \infty$</span>.  The <span class="enscript-variable-name">$\zeta_0$</span> term
is simply the product <span class="enscript-variable-name">$W(0) = w_0 = a_0 \cdot b_0$</span>.  The <span class="enscript-variable-name">$\zeta_1$</span> term is the product 
<span class="enscript-variable-name">$W(1) = \left (\sum_{i = 0}^{n} a_i \right ) \left (\sum_{i = 0}^{n} b_i \right )$</span>.  The third point <span class="enscript-variable-name">$\zeta_{\infty}$</span> is less obvious but rather
simple to explain.  The <span class="enscript-variable-name">$2n + 1$</span>'th coefficient of <span class="enscript-variable-name">$W(x)$</span> is numerically equivalent to the most significant column in an integer multiplication.  
The point at <span class="enscript-variable-name">$\infty$</span> is used symbolically to represent the most significant column, that is <span class="enscript-variable-name">$W(\infty) = w_{2n} = a_nb_n$</span>.  Note that the 
points at <span class="enscript-variable-name">$y = 0$</span> and <span class="enscript-variable-name">$\infty$</span> yield the coefficients <span class="enscript-variable-name">$w_0$</span> and <span class="enscript-variable-name">$w_{2n}$</span> directly.

If more points are required they should be of small values and powers of two such as <span class="enscript-variable-name">$2^q$</span> and the related <span class="enscript-keyword">\textit</span>{mirror points} 
<span class="enscript-variable-name">$\left (2^q \right )^{2n}  \cdot \zeta_{2^{-q}}$</span> for small values of <span class="enscript-variable-name">$q$</span>.  The term ``mirror point'' stems from the fact that 
<span class="enscript-variable-name">$\left (2^q \right )^{2n}  \cdot \zeta_{2^{-q}}$</span> can be calculated in the exact opposite fashion as <span class="enscript-variable-name">$\zeta_{2^q}$</span>.  For
example, when <span class="enscript-variable-name">$n = 2$</span> and <span class="enscript-variable-name">$q = 1$</span> then following two equations are equivalent to the point <span class="enscript-variable-name">$\zeta_{2}$</span> and its mirror.

<span class="enscript-keyword">\begin</span>{eqnarray}
<span class="enscript-keyword">\zeta</span>_{2}                  = f(2)g(2) = (4a_2 + 2a_1 + a_0)(4b_2 + 2b_1 + b_0) <span class="enscript-keyword">\nonumber</span> <span class="enscript-keyword">\\</span>
16 <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\zeta</span>_{1 <span class="enscript-keyword">\over</span> 2} = 4f({1<span class="enscript-keyword">\over</span> 2}) <span class="enscript-keyword">\cdot</span> 4g({1 <span class="enscript-keyword">\over</span> 2}) = (a_2 + 2a_1 + 4a_0)(b_2 + 2b_1 + 4b_0)
<span class="enscript-keyword">\end</span>{eqnarray}

Using such points will allow the values of <span class="enscript-variable-name">$f(y)$</span> and <span class="enscript-variable-name">$g(y)$</span> to be independently calculated using only left shifts.  For example, when <span class="enscript-variable-name">$n = 2$</span> the
polynomial <span class="enscript-variable-name">$f(2^q)$</span> is equal to <span class="enscript-variable-name">$2^q((2^qa_2) + a_1) + a_0$</span>.  This technique of polynomial representation is known as Horner's method.  

As a general rule of the algorithm when the inputs are split into <span class="enscript-variable-name">$n$</span> parts each there are <span class="enscript-variable-name">$2n - 1$</span> multiplications.  Each multiplication is of 
multiplicands that have <span class="enscript-variable-name">$n$</span> times fewer digits than the inputs.  The asymptotic running time of this algorithm is 
<span class="enscript-variable-name">$O \left ( k^{lg_n(2n - 1)} \right )$</span> for <span class="enscript-variable-name">$k$</span> digit inputs (<span class="enscript-keyword">\textit</span>{assuming they have the same number of digits}).  Figure~<span class="enscript-keyword">\ref</span>{fig:exponent}
summarizes the exponents for various values of <span class="enscript-variable-name">$n$</span>.

<span class="enscript-keyword">\begin</span>{figure}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Split into <span class="enscript-variable-name">$n$</span> Parts} &amp; <span class="enscript-keyword">\textbf</span>{Exponent}  &amp; <span class="enscript-keyword">\textbf</span>{Notes}<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$2$</span> &amp; <span class="enscript-variable-name">$1.584962501$</span> &amp; This is Karatsuba Multiplication. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$3$</span> &amp; <span class="enscript-variable-name">$1.464973520$</span> &amp; This is Toom-Cook Multiplication. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$4$</span> &amp; <span class="enscript-variable-name">$1.403677461$</span> &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$5$</span> &amp; <span class="enscript-variable-name">$1.365212389$</span> &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$10$</span> &amp; <span class="enscript-variable-name">$1.278753601$</span> &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$100$</span> &amp; <span class="enscript-variable-name">$1.149426538$</span> &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1000$</span> &amp; <span class="enscript-variable-name">$1.100270931$</span> &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$10000$</span> &amp; <span class="enscript-variable-name">$1.075252070$</span> &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Asymptotic Running Time of Polynomial Basis Multiplication}
<span class="enscript-keyword">\label</span>{fig:exponent}
<span class="enscript-keyword">\end</span>{figure}

At first it may seem like a good idea to choose <span class="enscript-variable-name">$n = 1000$</span> since the exponent is approximately <span class="enscript-variable-name">$1.1$</span>.  However, the overhead
of solving for the 2001 terms of <span class="enscript-variable-name">$W(x)$</span> will certainly consume any savings the algorithm could offer for all but exceedingly large
numbers.  

<span class="enscript-keyword">\subsubsection</span>{Cutoff Point}
The polynomial basis multiplication algorithms all require fewer single precision multiplications than a straight Comba approach.  However, 
the algorithms incur an overhead (<span class="enscript-keyword">\textit</span>{at the <span class="enscript-variable-name">$O(n)$</span> work level}) since they require a system of equations to be solved.  This makes the
polynomial basis approach more costly to use with small inputs.

Let <span class="enscript-variable-name">$m$</span> represent the number of digits in the multiplicands (<span class="enscript-keyword">\textit</span>{assume both multiplicands have the same number of digits}).  There exists a 
point <span class="enscript-variable-name">$y$</span> such that when <span class="enscript-variable-name">$m &lt; y$</span> the polynomial basis algorithms are more costly than Comba, when <span class="enscript-variable-name">$m = y$</span> they are roughly the same cost and 
when <span class="enscript-variable-name">$m &gt; y$</span> the Comba methods are slower than the polynomial basis algorithms.  

The exact location of <span class="enscript-variable-name">$y$</span> depends on several key architectural elements of the computer platform in question.

<span class="enscript-keyword">\begin</span>{enumerate}
<span class="enscript-keyword">\item</span>  The ratio of clock cycles for single precision multiplication versus other simpler operations such as addition, shifting, etc.  For example
on the AMD Athlon the ratio is roughly <span class="enscript-variable-name">$17 : 1$</span> while on the Intel P4 it is <span class="enscript-variable-name">$29 : 1$</span>.  The higher the ratio in favour of multiplication the lower
the cutoff point <span class="enscript-variable-name">$y$</span> will be.  

<span class="enscript-keyword">\item</span>  The complexity of the linear system of equations (<span class="enscript-keyword">\textit</span>{for the coefficients of <span class="enscript-variable-name">$W(x)$</span>}) is.  Generally speaking as the number of splits
grows the complexity grows substantially.  Ideally solving the system will only involve addition, subtraction and shifting of integers.  This
directly reflects on the ratio previous mentioned.

<span class="enscript-keyword">\item</span>  To a lesser extent memory bandwidth and function call overheads.  Provided the values are in the processor cache this is less of an
influence over the cutoff point.

<span class="enscript-keyword">\end</span>{enumerate}

A clean cutoff point separation occurs when a point <span class="enscript-variable-name">$y$</span> is found such that all of the cutoff point conditions are met.  For example, if the point
is too low then there will be values of <span class="enscript-variable-name">$m$</span> such that <span class="enscript-variable-name">$m &gt; y$</span> and the Comba method is still faster.  Finding the cutoff points is fairly simple when
a high resolution timer is available.  

<span class="enscript-keyword">\subsection</span>{Karatsuba Multiplication}
Karatsuba <span class="enscript-keyword">\cite</span>{KARA} multiplication when originally proposed in 1962 was among the first set of algorithms to break the <span class="enscript-variable-name">$O(n^2)$</span> barrier for
general purpose multiplication.  Given two polynomial basis representations <span class="enscript-variable-name">$f(x) = ax + b$</span> and <span class="enscript-variable-name">$g(x) = cx + d$</span>, Karatsuba proved with 
light algebra <span class="enscript-keyword">\cite</span>{KARAP} that the following polynomial is equivalent to multiplication of the two integers the polynomials represent.

<span class="enscript-keyword">\begin</span>{equation}
f(x) <span class="enscript-keyword">\cdot</span> g(x) = acx^2 + ((a + b)(c + d) - (ac + bd))x + bd
<span class="enscript-keyword">\end</span>{equation}

Using the observation that <span class="enscript-variable-name">$ac$</span> and <span class="enscript-variable-name">$bd$</span> could be re-used only three half sized multiplications would be required to produce the product.  Applying
this algorithm recursively, the work factor becomes <span class="enscript-variable-name">$O(n^{lg(3)})$</span> which is substantially better than the work factor <span class="enscript-variable-name">$O(n^2)$</span> of the Comba technique.  It turns 
out what Karatsuba did not know or at least did not publish was that this is simply polynomial basis multiplication with the points 
<span class="enscript-variable-name">$\zeta_0$</span>, <span class="enscript-variable-name">$\zeta_{\infty}$</span> and <span class="enscript-variable-name">$\zeta_{1}$</span>.  Consider the resultant system of equations.

<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{rcrcrcrc}
<span class="enscript-variable-name">$\zeta_{0}$</span> &amp;      <span class="enscript-variable-name">$=$</span> &amp;  &amp;  &amp;  &amp; &amp; <span class="enscript-variable-name">$w_0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\zeta_{1}$</span> &amp;      <span class="enscript-variable-name">$=$</span> &amp; <span class="enscript-variable-name">$w_2$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$w_1$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$w_0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\zeta_{\infty}$</span> &amp; <span class="enscript-variable-name">$=$</span> &amp; <span class="enscript-variable-name">$w_2$</span> &amp;  &amp; &amp;  &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}

By adding the first and last equation to the equation in the middle the term <span class="enscript-variable-name">$w_1$</span> can be isolated and all three coefficients solved for.  The simplicity
of this system of equations has made Karatsuba fairly popular.  In fact the cutoff point is often fairly low<span class="enscript-keyword">\footnote</span>{With LibTomMath 0.18 it is 70 and 109 digits for the Intel P4 and AMD Athlon respectively.}
making it an ideal algorithm to speed up certain public key cryptosystems such as RSA and Diffie-Hellman.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>mul}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow \vert a \vert \cdot \vert b \vert$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Init the following mp<span class="enscript-keyword">\_</span>int variables: <span class="enscript-variable-name">$x0$</span>, <span class="enscript-variable-name">$x1$</span>, <span class="enscript-variable-name">$y0$</span>, <span class="enscript-variable-name">$y1$</span>, <span class="enscript-variable-name">$t1$</span>, <span class="enscript-variable-name">$x0y0$</span>, <span class="enscript-variable-name">$x1y1$</span>.<span class="enscript-keyword">\\</span>
2.  If step 2 failed then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Split the input.  e.g. <span class="enscript-variable-name">$a = x1 \cdot \beta^B + x0$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$B \leftarrow \mbox{min}(a.used, b.used)/2$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$x0 \leftarrow a \mbox{ (mod }\beta^B\mbox{)}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d}) <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$y0 \leftarrow b \mbox{ (mod }\beta^B\mbox{)}$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$x1 \leftarrow \lfloor a / \beta^B \rfloor$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>rshd}) <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$y1 \leftarrow \lfloor b / \beta^B \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Calculate the three products. <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$x0y0 \leftarrow x0 \cdot y0$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mul}) <span class="enscript-keyword">\\</span>
9.  <span class="enscript-variable-name">$x1y1 \leftarrow x1 \cdot y1$</span> <span class="enscript-keyword">\\</span>
10.  <span class="enscript-variable-name">$t1 \leftarrow x1 + x0$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>add}) <span class="enscript-keyword">\\</span>
11.  <span class="enscript-variable-name">$x0 \leftarrow y1 + y0$</span> <span class="enscript-keyword">\\</span>
12.  <span class="enscript-variable-name">$t1 \leftarrow t1 \cdot x0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Calculate the middle term. <span class="enscript-keyword">\\</span>
13.  <span class="enscript-variable-name">$x0 \leftarrow x0y0 + x1y1$</span> <span class="enscript-keyword">\\</span>
14.  <span class="enscript-variable-name">$t1 \leftarrow t1 - x0$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Calculate the final product. <span class="enscript-keyword">\\</span>
15.  <span class="enscript-variable-name">$t1 \leftarrow t1 \cdot \beta^B$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>lshd}) <span class="enscript-keyword">\\</span>
16.  <span class="enscript-variable-name">$x1y1 \leftarrow x1y1 \cdot \beta^{2B}$</span> <span class="enscript-keyword">\\</span>
17.  <span class="enscript-variable-name">$t1 \leftarrow x0y0 + t1$</span> <span class="enscript-keyword">\\</span>
18.  <span class="enscript-variable-name">$c \leftarrow t1 + x1y1$</span> <span class="enscript-keyword">\\</span>
19.  Clear all of the temporary variables. <span class="enscript-keyword">\\</span>
20.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}).<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> 
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>mul}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>mul.}
This algorithm computes the unsigned product of two inputs using the Karatsuba multiplication algorithm.  It is loosely based on the description
from Knuth <span class="enscript-keyword">\cite</span>[pp. 294-295]{TAOCPV2}.  

<span class="enscript-keyword">\index</span>{radix point}
In order to split the two inputs into their respective halves, a suitable <span class="enscript-keyword">\textit</span>{radix point} must be chosen.  The radix point chosen must
be used for both of the inputs meaning that it must be smaller than the smallest input.  Step 3 chooses the radix point <span class="enscript-variable-name">$B$</span> as half of the 
smallest input <span class="enscript-keyword">\textbf</span>{used} count.  After the radix point is chosen the inputs are split into lower and upper halves.  Step 4 and 5 
compute the lower halves.  Step 6 and 7 computer the upper halves.  

After the halves have been computed the three intermediate half-size products must be computed.  Step 8 and 9 compute the trivial products
<span class="enscript-variable-name">$x0 \cdot y0$</span> and <span class="enscript-variable-name">$x1 \cdot y1$</span>.  The mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$x0$</span> is used as a temporary variable after <span class="enscript-variable-name">$x1 + x0$</span> has been computed.  By using <span class="enscript-variable-name">$x0$</span> instead
of an additional temporary variable, the algorithm can avoid an addition memory allocation operation.

The remaining steps 13 through 18 compute the Karatsuba polynomial through a variety of digit shifting and addition operations.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>mul.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The new coding element in this routine, not  seen in previous routines, is the usage of goto statements.  The conventional
wisdom is that goto statements should be avoided.  This is generally true, however when every single function call can fail, it makes sense
to handle error recovery with a single piece of code.  Lines 62 to 76 handle initializing all of the temporary variables 
required.  Note how each of the if statements goes to a different label in case of failure.  This allows the routine to correctly free only
the temporaries that have been successfully allocated so far.

The temporary variables are all initialized using the mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>size routine since they are expected to be large.  This saves the 
additional reallocation that would have been necessary.  Also <span class="enscript-variable-name">$x0$</span>, <span class="enscript-variable-name">$x1$</span>, <span class="enscript-variable-name">$y0$</span> and <span class="enscript-variable-name">$y1$</span> have to be able to hold at least their respective
number of digits for the next section of code.

The first algebraic portion of the algorithm is to split the two inputs into their halves.  However, instead of using mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d and mp<span class="enscript-keyword">\_</span>rshd
to extract the halves, the respective code has been placed inline within the body of the function.  To initialize the halves, the <span class="enscript-keyword">\textbf</span>{used} and 
<span class="enscript-keyword">\textbf</span>{sign} members are copied first.  The first for loop on line 96 copies the lower halves.  Since they are both the same magnitude it 
is simpler to calculate both lower halves in a single loop.  The for loop on lines 102 and 107 calculate the upper halves <span class="enscript-variable-name">$x1$</span> and 
<span class="enscript-variable-name">$y1$</span> respectively.

By inlining the calculation of the halves, the Karatsuba multiplier has a slightly lower overhead and can be used for smaller magnitude inputs.

When line 151 is reached, the algorithm has completed succesfully.  The ``error status'' variable <span class="enscript-variable-name">$err$</span> is set to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>OKAY} so that
the same code that handles errors can be used to clear the temporary variables and return.  

<span class="enscript-keyword">\subsection</span>{Toom-Cook <span class="enscript-variable-name">$3$</span>-Way Multiplication}
Toom-Cook <span class="enscript-variable-name">$3$</span>-Way <span class="enscript-keyword">\cite</span>{TOOM} multiplication is essentially the polynomial basis algorithm for <span class="enscript-variable-name">$n = 2$</span> except that the points  are 
chosen such that <span class="enscript-variable-name">$\zeta$</span> is easy to compute and the resulting system of equations easy to reduce.  Here, the points <span class="enscript-variable-name">$\zeta_{0}$</span>, 
<span class="enscript-variable-name">$16 \cdot \zeta_{1 \over 2}$</span>, <span class="enscript-variable-name">$\zeta_1$</span>, <span class="enscript-variable-name">$\zeta_2$</span> and <span class="enscript-variable-name">$\zeta_{\infty}$</span> make up the five required points to solve for the coefficients 
of the <span class="enscript-variable-name">$W(x)$</span>.

With the five relations that Toom-Cook specifies, the following system of equations is formed.

<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{rcrcrcrcrcr}
<span class="enscript-variable-name">$\zeta_0$</span>                    &amp; <span class="enscript-variable-name">$=$</span> &amp; <span class="enscript-variable-name">$0w_4$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$0w_3$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$0w_2$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$0w_1$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$1w_0$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$16 \cdot \zeta_{1 \over 2}$</span> &amp; <span class="enscript-variable-name">$=$</span> &amp; <span class="enscript-variable-name">$1w_4$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$2w_3$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$4w_2$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$8w_1$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$16w_0$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\zeta_1$</span>                    &amp; <span class="enscript-variable-name">$=$</span> &amp; <span class="enscript-variable-name">$1w_4$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$1w_3$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$1w_2$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$1w_1$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$1w_0$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\zeta_2$</span>                    &amp; <span class="enscript-variable-name">$=$</span> &amp; <span class="enscript-variable-name">$16w_4$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$8w_3$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$4w_2$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$2w_1$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$1w_0$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\zeta_{\infty}$</span>             &amp; <span class="enscript-variable-name">$=$</span> &amp; <span class="enscript-variable-name">$1w_4$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$0w_3$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$0w_2$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$0w_1$</span> &amp; <span class="enscript-variable-name">$+$</span> &amp; <span class="enscript-variable-name">$0w_0$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}

A trivial solution to this matrix requires <span class="enscript-variable-name">$12$</span> subtractions, two multiplications by a small power of two, two divisions by a small power
of two, two divisions by three and one multiplication by three.  All of these <span class="enscript-variable-name">$19$</span> sub-operations require less than quadratic time, meaning that
the algorithm can be faster than a baseline multiplication.  However, the greater complexity of this algorithm places the cutoff point
(<span class="enscript-keyword">\textbf</span>{TOOM<span class="enscript-keyword">\_</span>MUL<span class="enscript-keyword">\_</span>CUTOFF}) where Toom-Cook becomes more efficient much higher than the Karatsuba cutoff point.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>mul}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow  a  \cdot  b $</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
Split <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> into three pieces.  E.g. <span class="enscript-variable-name">$a = a_2 \beta^{2k} + a_1 \beta^{k} + a_0$</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$k \leftarrow \lfloor \mbox{min}(a.used, b.used) / 3 \rfloor$</span> <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$a_0 \leftarrow a \mbox{ (mod }\beta^{k}\mbox{)}$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$a_1 \leftarrow \lfloor a / \beta^k \rfloor$</span>, <span class="enscript-variable-name">$a_1 \leftarrow a_1 \mbox{ (mod }\beta^{k}\mbox{)}$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$a_2 \leftarrow \lfloor a / \beta^{2k} \rfloor$</span>, <span class="enscript-variable-name">$a_2 \leftarrow a_2 \mbox{ (mod }\beta^{k}\mbox{)}$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$b_0 \leftarrow a \mbox{ (mod }\beta^{k}\mbox{)}$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$b_1 \leftarrow \lfloor a / \beta^k \rfloor$</span>, <span class="enscript-variable-name">$b_1 \leftarrow b_1 \mbox{ (mod }\beta^{k}\mbox{)}$</span> <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$b_2 \leftarrow \lfloor a / \beta^{2k} \rfloor$</span>, <span class="enscript-variable-name">$b_2 \leftarrow b_2 \mbox{ (mod }\beta^{k}\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Find the five equations for <span class="enscript-variable-name">$w_0, w_1, ..., w_4$</span>. <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$w_0 \leftarrow a_0 \cdot b_0$</span> <span class="enscript-keyword">\\</span>
9.  <span class="enscript-variable-name">$w_4 \leftarrow a_2 \cdot b_2$</span> <span class="enscript-keyword">\\</span>
10. <span class="enscript-variable-name">$tmp_1 \leftarrow 2 \cdot a_0$</span>, <span class="enscript-variable-name">$tmp_1 \leftarrow a_1 + tmp_1$</span>, <span class="enscript-variable-name">$tmp_1 \leftarrow 2 \cdot tmp_1$</span>, <span class="enscript-variable-name">$tmp_1 \leftarrow tmp_1 + a_2$</span> <span class="enscript-keyword">\\</span>
11. <span class="enscript-variable-name">$tmp_2 \leftarrow 2 \cdot b_0$</span>, <span class="enscript-variable-name">$tmp_2 \leftarrow b_1 + tmp_2$</span>, <span class="enscript-variable-name">$tmp_2 \leftarrow 2 \cdot tmp_2$</span>, <span class="enscript-variable-name">$tmp_2 \leftarrow tmp_2 + b_2$</span> <span class="enscript-keyword">\\</span>
12. <span class="enscript-variable-name">$w_1 \leftarrow tmp_1 \cdot tmp_2$</span> <span class="enscript-keyword">\\</span>
13. <span class="enscript-variable-name">$tmp_1 \leftarrow 2 \cdot a_2$</span>, <span class="enscript-variable-name">$tmp_1 \leftarrow a_1 + tmp_1$</span>, <span class="enscript-variable-name">$tmp_1 \leftarrow 2 \cdot tmp_1$</span>, <span class="enscript-variable-name">$tmp_1 \leftarrow tmp_1 + a_0$</span> <span class="enscript-keyword">\\</span>
14. <span class="enscript-variable-name">$tmp_2 \leftarrow 2 \cdot b_2$</span>, <span class="enscript-variable-name">$tmp_2 \leftarrow b_1 + tmp_2$</span>, <span class="enscript-variable-name">$tmp_2 \leftarrow 2 \cdot tmp_2$</span>, <span class="enscript-variable-name">$tmp_2 \leftarrow tmp_2 + b_0$</span> <span class="enscript-keyword">\\</span>
15. <span class="enscript-variable-name">$w_3 \leftarrow tmp_1 \cdot tmp_2$</span> <span class="enscript-keyword">\\</span>
16. <span class="enscript-variable-name">$tmp_1 \leftarrow a_0 + a_1$</span>, <span class="enscript-variable-name">$tmp_1 \leftarrow tmp_1 + a_2$</span>, <span class="enscript-variable-name">$tmp_2 \leftarrow b_0 + b_1$</span>, <span class="enscript-variable-name">$tmp_2 \leftarrow tmp_2 + b_2$</span> <span class="enscript-keyword">\\</span>
17. <span class="enscript-variable-name">$w_2 \leftarrow tmp_1 \cdot tmp_2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Continued on the next page.<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>mul}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>mul} (continued). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow a \cdot  b $</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
Now solve the system of equations. <span class="enscript-keyword">\\</span>
18. <span class="enscript-variable-name">$w_1 \leftarrow w_4 - w_1$</span>, <span class="enscript-variable-name">$w_3 \leftarrow w_3 - w_0$</span> <span class="enscript-keyword">\\</span>
19. <span class="enscript-variable-name">$w_1 \leftarrow \lfloor w_1 / 2 \rfloor$</span>, <span class="enscript-variable-name">$w_3 \leftarrow \lfloor w_3 / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
20. <span class="enscript-variable-name">$w_2 \leftarrow w_2 - w_0$</span>, <span class="enscript-variable-name">$w_2 \leftarrow w_2 - w_4$</span> <span class="enscript-keyword">\\</span>
21. <span class="enscript-variable-name">$w_1 \leftarrow w_1 - w_2$</span>, <span class="enscript-variable-name">$w_3 \leftarrow w_3 - w_2$</span> <span class="enscript-keyword">\\</span>
22. <span class="enscript-variable-name">$tmp_1 \leftarrow 8 \cdot w_0$</span>, <span class="enscript-variable-name">$w_1 \leftarrow w_1 - tmp_1$</span>, <span class="enscript-variable-name">$tmp_1 \leftarrow 8 \cdot w_4$</span>, <span class="enscript-variable-name">$w_3 \leftarrow w_3 - tmp_1$</span> <span class="enscript-keyword">\\</span>
23. <span class="enscript-variable-name">$w_2 \leftarrow 3 \cdot w_2$</span>, <span class="enscript-variable-name">$w_2 \leftarrow w_2 - w_1$</span>, <span class="enscript-variable-name">$w_2 \leftarrow w_2 - w_3$</span> <span class="enscript-keyword">\\</span>
24. <span class="enscript-variable-name">$w_1 \leftarrow w_1 - w_2$</span>, <span class="enscript-variable-name">$w_3 \leftarrow w_3 - w_2$</span> <span class="enscript-keyword">\\</span>
25. <span class="enscript-variable-name">$w_1 \leftarrow \lfloor w_1 / 3 \rfloor, w_3 \leftarrow \lfloor w_3 / 3 \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Now substitute <span class="enscript-variable-name">$\beta^k$</span> for <span class="enscript-variable-name">$x$</span> by shifting <span class="enscript-variable-name">$w_0, w_1, ..., w_4$</span>. <span class="enscript-keyword">\\</span>
26. for <span class="enscript-variable-name">$n$</span> from <span class="enscript-variable-name">$1$</span> to <span class="enscript-variable-name">$4$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}26.1  <span class="enscript-variable-name">$w_n \leftarrow w_n \cdot \beta^{nk}$</span> <span class="enscript-keyword">\\</span>
27. <span class="enscript-variable-name">$c \leftarrow w_0 + w_1$</span>, <span class="enscript-variable-name">$c \leftarrow c + w_2$</span>, <span class="enscript-variable-name">$c \leftarrow c + w_3$</span>, <span class="enscript-variable-name">$c \leftarrow c + w_4$</span> <span class="enscript-keyword">\\</span>
28. Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>mul (continued)}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>mul.}
This algorithm computes the product of two mp<span class="enscript-keyword">\_</span>int variables <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> using the Toom-Cook approach.  Compared to the Karatsuba multiplication, this 
algorithm has a lower asymptotic running time of approximately <span class="enscript-variable-name">$O(n^{1.464})$</span> but at an obvious cost in overhead.  In this
description, several statements have been compounded to save space.  The intention is that the statements are executed from left to right across
any given step.

The two inputs <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> are first split into three <span class="enscript-variable-name">$k$</span>-digit integers <span class="enscript-variable-name">$a_0, a_1, a_2$</span> and <span class="enscript-variable-name">$b_0, b_1, b_2$</span> respectively.  From these smaller
integers the coefficients of the polynomial basis representations <span class="enscript-variable-name">$f(x)$</span> and <span class="enscript-variable-name">$g(x)$</span> are known and can be used to find the relations required.

The first two relations <span class="enscript-variable-name">$w_0$</span> and <span class="enscript-variable-name">$w_4$</span> are the points <span class="enscript-variable-name">$\zeta_{0}$</span> and <span class="enscript-variable-name">$\zeta_{\infty}$</span> respectively.  The relation <span class="enscript-variable-name">$w_1, w_2$</span> and <span class="enscript-variable-name">$w_3$</span> correspond
to the points <span class="enscript-variable-name">$16 \cdot \zeta_{1 \over 2}, \zeta_{2}$</span> and <span class="enscript-variable-name">$\zeta_{1}$</span> respectively.  These are found using logical shifts to independently find
<span class="enscript-variable-name">$f(y)$</span> and <span class="enscript-variable-name">$g(y)$</span> which significantly speeds up the algorithm.

After the five relations <span class="enscript-variable-name">$w_0, w_1, \ldots, w_4$</span> have been computed, the system they represent must be solved in order for the unknown coefficients 
<span class="enscript-variable-name">$w_1, w_2$</span> and <span class="enscript-variable-name">$w_3$</span> to be isolated.  The steps 18 through 25 perform the system reduction required as previously described.  Each step of
the reduction represents the comparable matrix operation that would be performed had this been performed by pencil.  For example, step 18 indicates
that row <span class="enscript-variable-name">$1$</span> must be subtracted from row <span class="enscript-variable-name">$4$</span> and simultaneously row <span class="enscript-variable-name">$0$</span> subtracted from row <span class="enscript-variable-name">$3$</span>.  

Once the coeffients have been isolated, the polynomial <span class="enscript-variable-name">$W(x) = \sum_{i=0}^{2n} w_i x^i$</span> is known.  By substituting <span class="enscript-variable-name">$\beta^{k}$</span> for <span class="enscript-variable-name">$x$</span>, the integer 
result <span class="enscript-variable-name">$a \cdot b$</span> is produced.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>mul.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The first obvious thing to note is that this algorithm is complicated.  The complexity is worth it if you are multiplying very 
large numbers.  For example, a 10,000 digit multiplication takes approximaly 99,282,205 fewer single precision multiplications with
Toom--Cook than a Comba or baseline approach (this is a savings of more than 99<span class="enscript-variable-name">$\%$</span>).  For most ``crypto'' sized numbers this
algorithm is not practical as Karatsuba has a much lower cutoff point.

First we split <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> into three roughly equal portions.  This has been accomplished (lines 41 to 70) with 
combinations of mp<span class="enscript-keyword">\_</span>rshd() and mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d() function calls.  At this point <span class="enscript-variable-name">$a = a2 \cdot \beta^2 + a1 \cdot \beta + a0$</span> and similiarly
for <span class="enscript-variable-name">$b$</span>.  

Next we compute the five points <span class="enscript-variable-name">$w0, w1, w2, w3$</span> and <span class="enscript-variable-name">$w4$</span>.  Recall that <span class="enscript-variable-name">$w0$</span> and <span class="enscript-variable-name">$w4$</span> can be computed directly from the portions so
we get those out of the way first (lines 73 and 78).  Next we compute <span class="enscript-variable-name">$w1, w2$</span> and <span class="enscript-variable-name">$w3$</span> using Horners method.

After this point we solve for the actual values of <span class="enscript-variable-name">$w1, w2$</span> and <span class="enscript-variable-name">$w3$</span> by reducing the <span class="enscript-variable-name">$5 \times 5$</span> system which is relatively
straight forward.  

<span class="enscript-keyword">\subsection</span>{Signed Multiplication}
Now that algorithms to handle multiplications of every useful dimensions have been developed, a rather simple finishing touch is required.  So far all
of the multiplication algorithms have been unsigned multiplications which leaves only a signed multiplication algorithm to be established.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>mul}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c \leftarrow a \cdot b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$a.sign = b.sign$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$sign = MP\_ZPOS$</span> <span class="enscript-keyword">\\</span>
2.  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$sign = MP\_ZNEG$</span> <span class="enscript-keyword">\\</span>
3.  If min<span class="enscript-variable-name">$(a.used, b.used) \ge TOOM\_MUL\_CUTOFF$</span> then  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$c \leftarrow a \cdot b$</span> using algorithm mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>mul <span class="enscript-keyword">\\</span>
4.  else if min<span class="enscript-variable-name">$(a.used, b.used) \ge KARATSUBA\_MUL\_CUTOFF$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$c \leftarrow a \cdot b$</span> using algorithm mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>mul <span class="enscript-keyword">\\</span>
5.  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$digs \leftarrow a.used + b.used + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  If <span class="enscript-variable-name">$digs &lt; MP\_ARRAY$</span> and min<span class="enscript-variable-name">$(a.used, b.used) \le \delta$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.2.1  <span class="enscript-variable-name">$c \leftarrow a \cdot b \mbox{ (mod }\beta^{digs}\mbox{)}$</span> using algorithm fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.3.1  <span class="enscript-variable-name">$c \leftarrow a \cdot b \mbox{ (mod }\beta^{digs}\mbox{)}$</span> using algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs.  <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$c.sign \leftarrow sign$</span> <span class="enscript-keyword">\\</span>
7.  Return the result of the unsigned multiplication performed. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>mul}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>mul.}
This algorithm performs the signed multiplication of two inputs.  It will make use of any of the three unsigned multiplication algorithms 
available when the input is of appropriate size.  The <span class="enscript-keyword">\textbf</span>{sign} of the result is not set until the end of the algorithm since algorithm
s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs will clear it.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The implementation is rather simplistic and is not particularly noteworthy.  Line 22 computes the sign of the result using the ``?'' 
operator from the C programming language.  Line 48 computes <span class="enscript-variable-name">$\delta$</span> using the fact that <span class="enscript-variable-name">$1 &lt;&lt; k$</span> is equal to <span class="enscript-variable-name">$2^k$</span>.  

<span class="enscript-keyword">\section</span>{Squaring}
<span class="enscript-keyword">\label</span>{sec:basesquare}

Squaring is a special case of multiplication where both multiplicands are equal.  At first it may seem like there is no significant optimization
available but in fact there is.  Consider the multiplication of <span class="enscript-variable-name">$576$</span> against <span class="enscript-variable-name">$241$</span>.  In total there will be nine single precision multiplications
performed which are <span class="enscript-variable-name">$1\cdot 6$</span>, <span class="enscript-variable-name">$1 \cdot 7$</span>, <span class="enscript-variable-name">$1 \cdot 5$</span>, <span class="enscript-variable-name">$4 \cdot 6$</span>, <span class="enscript-variable-name">$4 \cdot 7$</span>, <span class="enscript-variable-name">$4 \cdot 5$</span>, <span class="enscript-variable-name">$2 \cdot  6$</span>, <span class="enscript-variable-name">$2 \cdot 7$</span> and <span class="enscript-variable-name">$2 \cdot 5$</span>.  Now consider 
the multiplication of <span class="enscript-variable-name">$123$</span> against <span class="enscript-variable-name">$123$</span>.  The nine products are <span class="enscript-variable-name">$3 \cdot 3$</span>, <span class="enscript-variable-name">$3 \cdot 2$</span>, <span class="enscript-variable-name">$3 \cdot 1$</span>, <span class="enscript-variable-name">$2 \cdot 3$</span>, <span class="enscript-variable-name">$2 \cdot 2$</span>, <span class="enscript-variable-name">$2 \cdot 1$</span>, 
<span class="enscript-variable-name">$1 \cdot 3$</span>, <span class="enscript-variable-name">$1 \cdot 2$</span> and <span class="enscript-variable-name">$1 \cdot 1$</span>.  On closer inspection some of the products are equivalent.  For example, <span class="enscript-variable-name">$3 \cdot 2 = 2 \cdot 3$</span> 
and <span class="enscript-variable-name">$3 \cdot 1 = 1 \cdot 3$</span>. 

For any <span class="enscript-variable-name">$n$</span>-digit input, there are <span class="enscript-variable-name">${{\left (n^2 + n \right)}\over 2}$</span> possible unique single precision multiplications required compared to the <span class="enscript-variable-name">$n^2$</span>
required for multiplication.  The following diagram gives an example of the operations required.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{ccccc|c}
&amp;&amp;1&amp;2&amp;3&amp;<span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\times$</span> &amp;&amp;1&amp;2&amp;3&amp;<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> &amp;&amp; <span class="enscript-variable-name">$3 \cdot 1$</span> &amp; <span class="enscript-variable-name">$3 \cdot 2$</span> &amp; <span class="enscript-variable-name">$3 \cdot 3$</span> &amp; Row 0<span class="enscript-keyword">\\</span>
       &amp; <span class="enscript-variable-name">$2 \cdot 1$</span>  &amp; <span class="enscript-variable-name">$2 \cdot 2$</span> &amp; <span class="enscript-variable-name">$2 \cdot 3$</span> &amp;&amp; Row 1 <span class="enscript-keyword">\\</span>
         <span class="enscript-variable-name">$1 \cdot 1$</span>  &amp; <span class="enscript-variable-name">$1 \cdot 2$</span> &amp; <span class="enscript-variable-name">$1 \cdot 3$</span> &amp;&amp;&amp; Row 2 <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Squaring Optimization Diagram}
<span class="enscript-keyword">\end</span>{figure}

Starting from zero and numbering the columns from right to left a very simple pattern becomes obvious.  For the purposes of this discussion let <span class="enscript-variable-name">$x$</span>
represent the number being squared.  The first observation is that in row <span class="enscript-variable-name">$k$</span> the <span class="enscript-variable-name">$2k$</span>'th column of the product has a <span class="enscript-variable-name">$\left (x_k \right)^2$</span> term in it.  

The second observation is that every column <span class="enscript-variable-name">$j$</span> in row <span class="enscript-variable-name">$k$</span> where <span class="enscript-variable-name">$j \ne 2k$</span> is part of a double product.  Every non-square term of a column will
appear twice hence the name ``double product''.  Every odd column is made up entirely of double products.  In fact every column is made up of double 
products and at most one square (<span class="enscript-keyword">\textit</span>{see the exercise section}).  

The third and final observation is that for row <span class="enscript-variable-name">$k$</span> the first unique non-square term, that is, one that hasn't already appeared in an earlier row, 
occurs at column <span class="enscript-variable-name">$2k + 1$</span>.  For example, on row <span class="enscript-variable-name">$1$</span> of the previous squaring, column one is part of the double product with column one from row zero. 
Column two of row one is a square and column three is the first unique column.

<span class="enscript-keyword">\subsection</span>{The Baseline Squaring Algorithm}
The baseline squaring algorithm is meant to be a catch-all squaring algorithm.  It will handle any of the input sizes that the faster routines
will not handle.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$b \leftarrow a^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Init a temporary mp<span class="enscript-keyword">\_</span>int of at least <span class="enscript-variable-name">$2 \cdot a.used +1$</span> digits.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>size}) <span class="enscript-keyword">\\</span>
2.  If step 1 failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}) <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$t.used \leftarrow 2 \cdot a.used + 1$</span> <span class="enscript-keyword">\\</span>
4.  For <span class="enscript-variable-name">$ix$</span> from 0 to <span class="enscript-variable-name">$a.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}Calculate the square. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$\hat r \leftarrow t_{2ix} + \left (a_{ix} \right )^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.2  <span class="enscript-variable-name">$t_{2ix} \leftarrow \hat r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}Calculate the double products after the square. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.3  <span class="enscript-variable-name">$u \leftarrow \lfloor \hat r / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.4  For <span class="enscript-variable-name">$iy$</span> from <span class="enscript-variable-name">$ix + 1$</span> to <span class="enscript-variable-name">$a.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}4.4.1  <span class="enscript-variable-name">$\hat r \leftarrow 2 \cdot a_{ix}a_{iy} + t_{ix + iy} + u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}4.4.2  <span class="enscript-variable-name">$t_{ix + iy} \leftarrow \hat r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}4.4.3  <span class="enscript-variable-name">$u \leftarrow \lfloor \hat r / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}Set the last carry. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.5  While <span class="enscript-variable-name">$u &gt; 0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}4.5.1  <span class="enscript-variable-name">$iy \leftarrow iy + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}4.5.2  <span class="enscript-variable-name">$\hat r \leftarrow t_{ix + iy} + u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}4.5.3  <span class="enscript-variable-name">$t_{ix + iy} \leftarrow \hat r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}4.5.4  <span class="enscript-variable-name">$u \leftarrow \lfloor \hat r / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
5.  Clamp excess digits of <span class="enscript-variable-name">$t$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clamp}) <span class="enscript-keyword">\\</span>
6.  Exchange <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$t$</span>. <span class="enscript-keyword">\\</span>
7.  Clear <span class="enscript-variable-name">$t$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clear}) <span class="enscript-keyword">\\</span>
8.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr.}
This algorithm computes the square of an input using the three observations on squaring.  It is based fairly faithfully on  algorithm 14.16 of HAC
<span class="enscript-keyword">\cite</span>[pp.596-597]{HAC}.  Similar to algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs, a temporary mp<span class="enscript-keyword">\_</span>int is allocated to hold the result of the squaring.  This allows the 
destination mp<span class="enscript-keyword">\_</span>int to be the same as the source mp<span class="enscript-keyword">\_</span>int.

The outer loop of this algorithm begins on step 4. It is best to think of the outer loop as walking down the rows of the partial results, while
the inner loop computes the columns of the partial result.  Step 4.1 and 4.2 compute the square term for each row, and step 4.3 and 4.4 propagate
the carry and compute the double products.  

The requirement that a mp<span class="enscript-keyword">\_</span>word be able to represent the range <span class="enscript-variable-name">$0 \le x &lt; 2 \beta^2$</span> arises from this
very algorithm.  The product <span class="enscript-variable-name">$a_{ix}a_{iy}$</span> will lie in the range <span class="enscript-variable-name">$0 \le x \le \beta^2 - 2\beta + 1$</span> which is obviously less than <span class="enscript-variable-name">$\beta^2$</span> meaning that
when it is multiplied by two, it can be properly represented by a mp<span class="enscript-keyword">\_</span>word.

Similar to algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs, after every pass of the inner loop, the destination is correctly set to the sum of all of the partial 
results calculated so far.  This involves expensive carry propagation which will be eliminated in the next algorithm.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Inside the outer loop (line 34) the square term is calculated on line 37.  The carry (line 44) has been
extracted from the mp<span class="enscript-keyword">\_</span>word accumulator using a right shift.  Aliases for <span class="enscript-variable-name">$a_{ix}$</span> and <span class="enscript-variable-name">$t_{ix+iy}$</span> are initialized 
(lines 47 and 50) to simplify the inner loop.  The doubling is performed using two
additions (line 59) since it is usually faster than shifting, if not at least as fast.  

The important observation is that the inner loop does not begin at <span class="enscript-variable-name">$iy = 0$</span> like for multiplication.  As such the inner loops
get progressively shorter as the algorithm proceeds.  This is what leads to the savings compared to using a multiplication to
square a number. 

<span class="enscript-keyword">\subsection</span>{Faster Squaring by the ``Comba'' Method}
A major drawback to the baseline method is the requirement for single precision shifting inside the <span class="enscript-variable-name">$O(n^2)$</span> nested loop.  Squaring has an additional
drawback that it must double the product inside the inner loop as well.  As for multiplication, the Comba technique can be used to eliminate these
performance hazards.

The first obvious solution is to make an array of mp<span class="enscript-keyword">\_</span>words which will hold all of the columns.  This will indeed eliminate all of the carry
propagation operations from the inner loop.  However, the inner product must still be doubled <span class="enscript-variable-name">$O(n^2)$</span> times.  The solution stems from the simple fact
that <span class="enscript-variable-name">$2a + 2b + 2c = 2(a + b + c)$</span>.  That is the sum of all of the double products is equal to double the sum of all the products.  For example,
<span class="enscript-variable-name">$ab + ba + ac + ca = 2ab + 2ac = 2(ab + ac)$</span>.  

However, we cannot simply double all of the columns, since the squares appear only once per row.  The most practical solution is to have two 
mp<span class="enscript-keyword">\_</span>word arrays.  One array will hold the squares and the other array will hold the double products.  With both arrays the doubling and 
carry propagation can be moved to a <span class="enscript-variable-name">$O(n)$</span> work level outside the <span class="enscript-variable-name">$O(n^2)$</span> level.  In this case, we have an even simpler solution in mind.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$b \leftarrow a^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
Place an array of <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>WARRAY} mp<span class="enscript-keyword">\_</span>digits named <span class="enscript-variable-name">$W$</span> on the stack. <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b.alloc &lt; 2a.used + 1$</span> then grow <span class="enscript-variable-name">$b$</span> to <span class="enscript-variable-name">$2a.used + 1$</span> digits.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>grow}). <span class="enscript-keyword">\\</span>
2.  If step 1 failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$pa \leftarrow 2 \cdot a.used$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$\hat W1 \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
5.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$pa - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$\_ \hat W \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$ty \leftarrow \mbox{MIN}(a.used - 1, ix)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  <span class="enscript-variable-name">$tx \leftarrow ix - ty$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.4  <span class="enscript-variable-name">$iy \leftarrow \mbox{MIN}(a.used - tx, ty + 1)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.5  <span class="enscript-variable-name">$iy \leftarrow \mbox{MIN}(iy, \lfloor \left (ty - tx + 1 \right )/2 \rfloor)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.6  for <span class="enscript-variable-name">$iz$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$iz - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.6.1  <span class="enscript-variable-name">$\_ \hat W \leftarrow \_ \hat W + a_{tx + iz}a_{ty - iz}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.7  <span class="enscript-variable-name">$\_ \hat W \leftarrow 2 \cdot \_ \hat W  + \hat W1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.8  if <span class="enscript-variable-name">$ix$</span> is even then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.8.1  <span class="enscript-variable-name">$\_ \hat W \leftarrow \_ \hat W + \left ( a_{\lfloor ix/2 \rfloor}\right )^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.9  <span class="enscript-variable-name">$W_{ix} \leftarrow \_ \hat W (\mbox{mod }\beta)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.10  <span class="enscript-variable-name">$\hat W1 \leftarrow \lfloor \_ \hat W / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$oldused \leftarrow b.used$</span> <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$b.used \leftarrow 2 \cdot a.used$</span> <span class="enscript-keyword">\\</span>
8.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$pa - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  <span class="enscript-variable-name">$b_{ix} \leftarrow W_{ix}$</span> <span class="enscript-keyword">\\</span>
9.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$pa$</span> to <span class="enscript-variable-name">$oldused - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.1  <span class="enscript-variable-name">$b_{ix} \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
10.  Clamp excess digits from <span class="enscript-variable-name">$b$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>clamp}) <span class="enscript-keyword">\\</span>
11.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span> 
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr.}
This algorithm computes the square of an input using the Comba technique.  It is designed to be a replacement for algorithm 
s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr when the number of input digits is less than <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>WARRAY} and less than <span class="enscript-variable-name">$\delta \over 2$</span>.  
This algorithm is very similar to the Comba multiplier except with a few key differences we shall make note of.

First, we have an accumulator and carry variables <span class="enscript-variable-name">$\_ \hat W$</span> and <span class="enscript-variable-name">$\hat W1$</span> respectively.  This is because the inner loop
products are to be doubled.  If we had added the previous carry in we would be doubling too much.  Next we perform an
addition MIN condition on <span class="enscript-variable-name">$iy$</span> (step 5.5) to prevent overlapping digits.  For example, <span class="enscript-variable-name">$a_3 \cdot a_5$</span> is equal
<span class="enscript-variable-name">$a_5 \cdot a_3$</span>.  Whereas in the multiplication case we would have <span class="enscript-variable-name">$5 &lt; a.used$</span> and <span class="enscript-variable-name">$3 \ge 0$</span> is maintained since we double the sum
of the products just outside the inner loop we have to avoid doing this.  This is also a good thing since we perform
fewer multiplications and the routine ends up being faster.

Finally the last difference is the addition of the ``square'' term outside the inner loop (step 5.8).  We add in the square
only to even outputs and it is the square of the term at the <span class="enscript-variable-name">$\lfloor ix / 2 \rfloor$</span> position.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This implementation is essentially a copy of Comba multiplication with the appropriate changes added to make it faster for 
the special case of squaring.  

<span class="enscript-keyword">\subsection</span>{Polynomial Basis Squaring}
The same algorithm that performs optimal polynomial basis multiplication can be used to perform polynomial basis squaring.  The minor exception
is that <span class="enscript-variable-name">$\zeta_y = f(y)g(y)$</span> is actually equivalent to <span class="enscript-variable-name">$\zeta_y = f(y)^2$</span> since <span class="enscript-variable-name">$f(y) = g(y)$</span>.  Instead of performing <span class="enscript-variable-name">$2n + 1$</span>
multiplications to find the <span class="enscript-variable-name">$\zeta$</span> relations, squaring operations are performed instead.  

<span class="enscript-keyword">\subsection</span>{Karatsuba Squaring}
Let <span class="enscript-variable-name">$f(x) = ax + b$</span> represent the polynomial basis representation of a number to square.  
Let <span class="enscript-variable-name">$h(x) = \left ( f(x) \right )^2$</span> represent the square of the polynomial.  The Karatsuba equation can be modified to square a 
number with the following equation.

<span class="enscript-keyword">\begin</span>{equation}
h(x) = a^2x^2 + <span class="enscript-keyword">\left</span> ((a + b)^2 - (a^2 + b^2) <span class="enscript-keyword">\right</span> )x + b^2
<span class="enscript-keyword">\end</span>{equation}

Upon closer inspection this equation only requires the calculation of three half-sized squares: <span class="enscript-variable-name">$a^2$</span>, <span class="enscript-variable-name">$b^2$</span> and <span class="enscript-variable-name">$(a + b)^2$</span>.  As in 
Karatsuba multiplication, this algorithm can be applied recursively on the input and will achieve an asymptotic running time of 
<span class="enscript-variable-name">$O \left ( n^{lg(3)} \right )$</span>.

If the asymptotic times of Karatsuba squaring and multiplication are the same, why not simply use the multiplication algorithm 
instead?  The answer to this arises from the cutoff point for squaring.  As in multiplication there exists a cutoff point, at which the 
time required for a Comba based squaring and a Karatsuba based squaring meet.  Due to the overhead inherent in the Karatsuba method, the cutoff 
point is fairly high.  For example, on an AMD Athlon XP processor with <span class="enscript-variable-name">$\beta = 2^{28}$</span>, the cutoff point is around 127 digits.  

Consider squaring a 200 digit number with this technique.  It will be split into two 100 digit halves which are subsequently squared.  
The 100 digit halves will not be squared using Karatsuba, but instead using the faster Comba based squaring algorithm.  If Karatsuba multiplication
were used instead, the 100 digit numbers would be squared with a slower Comba based multiplication.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>sqr}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$b \leftarrow a^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  Initialize the following temporary mp<span class="enscript-keyword">\_</span>ints:  <span class="enscript-variable-name">$x0$</span>, <span class="enscript-variable-name">$x1$</span>, <span class="enscript-variable-name">$t1$</span>, <span class="enscript-variable-name">$t2$</span>, <span class="enscript-variable-name">$x0x0$</span> and <span class="enscript-variable-name">$x1x1$</span>. <span class="enscript-keyword">\\</span>
2.  If any of the initializations on step 1 failed return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>MEM}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Split the input.  e.g. <span class="enscript-variable-name">$a = x1\beta^B + x0$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$B \leftarrow \lfloor a.used / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$x0 \leftarrow a \mbox{ (mod }\beta^B\mbox{)}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d}) <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$x1 \leftarrow \lfloor a / \beta^B \rfloor$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>lshd}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Calculate the three squares. <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$x0x0 \leftarrow x0^2$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>sqr}) <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$x1x1 \leftarrow x1^2$</span> <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$t1 \leftarrow x1 + x0$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add}) <span class="enscript-keyword">\\</span>
9.  <span class="enscript-variable-name">$t1 \leftarrow t1^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Compute the middle term. <span class="enscript-keyword">\\</span>
10.  <span class="enscript-variable-name">$t2 \leftarrow x0x0 + x1x1$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add}) <span class="enscript-keyword">\\</span>
11.  <span class="enscript-variable-name">$t1 \leftarrow t1 - t2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Compute final product. <span class="enscript-keyword">\\</span>
12.  <span class="enscript-variable-name">$t1 \leftarrow t1\beta^B$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>lshd}) <span class="enscript-keyword">\\</span>
13.  <span class="enscript-variable-name">$x1x1 \leftarrow x1x1\beta^{2B}$</span> <span class="enscript-keyword">\\</span>
14.  <span class="enscript-variable-name">$t1 \leftarrow t1 + x0x0$</span> <span class="enscript-keyword">\\</span>
15.  <span class="enscript-variable-name">$b \leftarrow t1 + x1x1$</span> <span class="enscript-keyword">\\</span>
16.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>sqr}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>sqr.}
This algorithm computes the square of an input <span class="enscript-variable-name">$a$</span> using the Karatsuba technique.  This algorithm is very similar to the Karatsuba based
multiplication algorithm with the exception that the three half-size multiplications have been replaced with three half-size squarings.

The radix point for squaring is simply placed exactly in the middle of the digits when the input has an odd number of digits, otherwise it is
placed just below the middle.  Step 3, 4 and 5 compute the two halves required using <span class="enscript-variable-name">$B$</span>
as the radix point.  The first two squares in steps 6 and 7 are rather straightforward while the last square is of a more compact form.

By expanding <span class="enscript-variable-name">$\left (x1 + x0 \right )^2$</span>, the <span class="enscript-variable-name">$x1^2$</span> and <span class="enscript-variable-name">$x0^2$</span> terms in the middle disappear, that is <span class="enscript-variable-name">$(x0 - x1)^2 - (x1^2 + x0^2)  = 2 \cdot x0 \cdot x1$</span>.
Now if <span class="enscript-variable-name">$5n$</span> single precision additions and a squaring of <span class="enscript-variable-name">$n$</span>-digits is faster than multiplying two <span class="enscript-variable-name">$n$</span>-digit numbers and doubling then
this method is faster.  Assuming no further recursions occur, the difference can be estimated with the following inequality.

Let <span class="enscript-variable-name">$p$</span> represent the cost of a single precision addition and <span class="enscript-variable-name">$q$</span> the cost of a single precision multiplication both in terms of time<span class="enscript-keyword">\footnote</span>{Or
machine clock cycles.}. 

<span class="enscript-keyword">\begin</span>{equation}
5pn +{{q(n^2 + n)} <span class="enscript-keyword">\over</span> 2} <span class="enscript-keyword">\le</span> pn + qn^2
<span class="enscript-keyword">\end</span>{equation}

For example, on an AMD Athlon XP processor <span class="enscript-variable-name">$p = {1 \over 3}$</span> and <span class="enscript-variable-name">$q = 6$</span>.  This implies that the following inequality should hold.
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{rcl}
<span class="enscript-variable-name">${5n \over 3} + 3n^2 + 3n$</span>     &amp; <span class="enscript-variable-name">$&lt;$</span> &amp; <span class="enscript-variable-name">${n \over 3} + 6n^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">${5 \over 3} + 3n + 3$</span>     &amp; <span class="enscript-variable-name">$&lt;$</span> &amp; <span class="enscript-variable-name">${1 \over 3} + 6n$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">${13 \over 9}$</span>     &amp; <span class="enscript-variable-name">$&lt;$</span> &amp; <span class="enscript-variable-name">$n$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}

This results in a cutoff point around <span class="enscript-variable-name">$n = 2$</span>.  As a consequence it is actually faster to compute the middle term the ``long way'' on processors
where multiplication is substantially slower<span class="enscript-keyword">\footnote</span>{On the Athlon there is a 1:17 ratio between clock cycles for addition and multiplication.  On
the Intel P4 processor this ratio is 1:29 making this method even more beneficial.  The only common exception is the ARMv4 processor which has a
ratio of 1:7.  } than simpler operations such as addition.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>sqr.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This implementation is largely based on the implementation of algorithm mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>mul.  It uses the same inline style to copy and 
shift the input into the two halves.  The loop from line 54 to line 70 has been modified since only one input exists.  The <span class="enscript-keyword">\textbf</span>{used}
count of both <span class="enscript-variable-name">$x0$</span> and <span class="enscript-variable-name">$x1$</span> is fixed up and <span class="enscript-variable-name">$x0$</span> is clamped before the calculations begin.  At this point <span class="enscript-variable-name">$x1$</span> and <span class="enscript-variable-name">$x0$</span> are valid equivalents
to the respective halves as if mp<span class="enscript-keyword">\_</span>rshd and mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d had been used.  

By inlining the copy and shift operations the cutoff point for Karatsuba multiplication can be lowered.  On the Athlon the cutoff point
is exactly at the point where Comba squaring can no longer be used (<span class="enscript-keyword">\textit</span>{128 digits}).  On slower processors such as the Intel P4
it is actually below the Comba limit (<span class="enscript-keyword">\textit</span>{at 110 digits}).

This routine uses the same error trap coding style as mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>sqr.  As the temporary variables are initialized errors are 
redirected to the error trap higher up.  If the algorithm completes without error the error code is set to <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>OKAY} and 
mp<span class="enscript-keyword">\_</span>clears are executed normally.

<span class="enscript-keyword">\subsection</span>{Toom-Cook Squaring}
The Toom-Cook squaring algorithm mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>sqr is heavily based on the algorithm mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>mul with the exception that squarings are used
instead of multiplication to find the five relations.  The reader is encouraged to read the description of the latter algorithm and try to 
derive their own Toom-Cook squaring algorithm.  

<span class="enscript-keyword">\subsection</span>{High Level Squaring}
<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>sqr}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$b \leftarrow a^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$a.used \ge TOOM\_SQR\_CUTOFF$</span> then  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$b \leftarrow a^2$</span> using algorithm mp<span class="enscript-keyword">\_</span>toom<span class="enscript-keyword">\_</span>sqr <span class="enscript-keyword">\\</span>
2.  else if <span class="enscript-variable-name">$a.used \ge KARATSUBA\_SQR\_CUTOFF$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$b \leftarrow a^2$</span> using algorithm mp<span class="enscript-keyword">\_</span>karatsuba<span class="enscript-keyword">\_</span>sqr <span class="enscript-keyword">\\</span>
3.  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$digs \leftarrow a.used + b.used + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.2  If <span class="enscript-variable-name">$digs &lt; MP\_ARRAY$</span> and <span class="enscript-variable-name">$a.used \le \delta$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}3.2.1  <span class="enscript-variable-name">$b \leftarrow a^2$</span> using algorithm fast<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.3  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}3.3.1  <span class="enscript-variable-name">$b \leftarrow a^2$</span> using algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr.  <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$b.sign \leftarrow MP\_ZPOS$</span> <span class="enscript-keyword">\\</span>
5.  Return the result of the unsigned squaring performed. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>sqr}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>sqr.}
This algorithm computes the square of the input using one of four different algorithms.  If the input is very large and has at least
<span class="enscript-keyword">\textbf</span>{TOOM<span class="enscript-keyword">\_</span>SQR<span class="enscript-keyword">\_</span>CUTOFF} or <span class="enscript-keyword">\textbf</span>{KARATSUBA<span class="enscript-keyword">\_</span>SQR<span class="enscript-keyword">\_</span>CUTOFF} digits then either the Toom-Cook or the Karatsuba Squaring algorithm is used.  If
neither of the polynomial basis algorithms should be used then either the Comba or baseline algorithm is used.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sqr.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\section</span>*{Exercises}
<span class="enscript-keyword">\begin</span>{tabular}{cl}
<span class="enscript-variable-name">$\left [ 3 \right ] $</span> &amp; Devise an efficient algorithm for selection of the radix point to handle inputs <span class="enscript-keyword">\\</span>
                      &amp; that have different number of digits in Karatsuba multiplication. <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 2 \right ] $</span> &amp; In section 5.3 the fact that every column of a squaring is made up <span class="enscript-keyword">\\</span>
                      &amp; of double products and at most one square is stated.  Prove this statement. <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span>                      
<span class="enscript-variable-name">$\left [ 3 \right ] $</span> &amp; Prove the equation for Karatsuba squaring. <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 1 \right ] $</span> &amp; Prove that Karatsuba squaring requires <span class="enscript-variable-name">$O \left (n^{lg(3)} \right )$</span> time. <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span> 
<span class="enscript-variable-name">$\left [ 2 \right ] $</span> &amp; Determine the minimal ratio between addition and multiplication clock cycles <span class="enscript-keyword">\\</span>
                      &amp; required for equation <span class="enscript-variable-name">$6.7$</span> to be true.  <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 3 \right ] $</span> &amp; Implement a threaded version of Comba multiplication (and squaring) where you <span class="enscript-keyword">\\</span>
                      &amp; compute subsets of the columns in each thread.  Determine a cutoff point where <span class="enscript-keyword">\\</span>
                      &amp; it is effective and add the logic to mp<span class="enscript-keyword">\_</span>mul() and mp<span class="enscript-keyword">\_</span>sqr(). <span class="enscript-keyword">\\</span>
                      &amp;<span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 4 \right ] $</span> &amp; Same as the previous but also modify the Karatsuba and Toom-Cook.  You must <span class="enscript-keyword">\\</span>
                      &amp; increase the throughput of mp<span class="enscript-keyword">\_</span>exptmod() for random odd moduli in the range <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-variable-name">$512 \ldots 4096$</span> bits significantly (<span class="enscript-variable-name">$&gt; 2x$</span>) to complete this challenge. <span class="enscript-keyword">\\</span>
                      &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}

<span class="enscript-keyword">\chapter</span>{Modular Reduction}
<span class="enscript-keyword">\section</span>{Basics of Modular Reduction}
<span class="enscript-keyword">\index</span>{modular residue}
Modular reduction is an operation that arises quite often within public key cryptography algorithms and various number theoretic algorithms, 
such as factoring.  Modular reduction algorithms are the third class of algorithms of the ``multipliers'' set.  A number <span class="enscript-variable-name">$a$</span> is said to be <span class="enscript-keyword">\textit</span>{reduced}
modulo another number <span class="enscript-variable-name">$b$</span> by finding the remainder of the division <span class="enscript-variable-name">$a/b$</span>.  Full integer division with remainder is a topic to be covered 
in~<span class="enscript-keyword">\ref</span>{sec:division}.

Modular reduction is equivalent to solving for <span class="enscript-variable-name">$r$</span> in the following equation.  <span class="enscript-variable-name">$a = bq + r$</span> where <span class="enscript-variable-name">$q = \lfloor a/b \rfloor$</span>.  The result 
<span class="enscript-variable-name">$r$</span> is said to be ``congruent to <span class="enscript-variable-name">$a$</span> modulo <span class="enscript-variable-name">$b$</span>'' which is also written as <span class="enscript-variable-name">$r \equiv a \mbox{ (mod }b\mbox{)}$</span>.  In other vernacular <span class="enscript-variable-name">$r$</span> is known as the 
``modular residue'' which leads to ``quadratic residue''<span class="enscript-keyword">\footnote</span>{That's fancy talk for <span class="enscript-variable-name">$b \equiv a^2 \mbox{ (mod }p\mbox{)}$</span>.} and
other forms of residues.  

Modular reductions are normally used to create either finite groups, rings or fields.  The most common usage for performance driven modular reductions 
is in modular exponentiation algorithms.  That is to compute <span class="enscript-variable-name">$d = a^b \mbox{ (mod }c\mbox{)}$</span> as fast as possible.  This operation is used in the 
RSA and Diffie-Hellman public key algorithms, for example.  Modular multiplication and squaring also appears as a fundamental operation in 
elliptic curve cryptographic algorithms.  As will be discussed in the subsequent chapter there exist fast algorithms for computing modular 
exponentiations without having to perform (<span class="enscript-keyword">\textit</span>{in this example}) <span class="enscript-variable-name">$b - 1$</span> multiplications.  These algorithms will produce partial results in the 
range <span class="enscript-variable-name">$0 \le x &lt; c^2$</span> which can be taken advantage of to create several efficient algorithms.   They have also been used to create redundancy check 
algorithms known as CRCs, error correction codes such as Reed-Solomon and solve a variety of number theoeretic problems.  

<span class="enscript-keyword">\section</span>{The Barrett Reduction}
The Barrett reduction algorithm <span class="enscript-keyword">\cite</span>{BARRETT} was inspired by fast division algorithms which multiply by the reciprocal to emulate
division.  Barretts observation was that the residue <span class="enscript-variable-name">$c$</span> of <span class="enscript-variable-name">$a$</span> modulo <span class="enscript-variable-name">$b$</span> is equal to 

<span class="enscript-keyword">\begin</span>{equation}
c = a - b <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\lfloor</span> a/b <span class="enscript-keyword">\rfloor</span>
<span class="enscript-keyword">\end</span>{equation}

Since algorithms such as modular exponentiation would be using the same modulus extensively, typical DSP<span class="enscript-keyword">\footnote</span>{It is worth noting that Barrett's paper 
targeted the DSP56K processor.}  intuition would indicate the next step would be to replace <span class="enscript-variable-name">$a/b$</span> by a multiplication by the reciprocal.  However, 
DSP intuition on its own will not work as these numbers are considerably larger than the precision of common DSP floating point data types.  
It would take another common optimization to optimize the algorithm.

<span class="enscript-keyword">\subsection</span>{Fixed Point Arithmetic}
The trick used to optimize the above equation is based on a technique of emulating floating point data types with fixed precision integers.  Fixed
point arithmetic would become very popular as it greatly optimize the ``3d-shooter'' genre of games in the mid 1990s when floating point units were 
fairly slow if not unavailable.   The idea behind fixed point arithmetic is to take a normal <span class="enscript-variable-name">$k$</span>-bit integer data type and break it into <span class="enscript-variable-name">$p$</span>-bit 
integer and a <span class="enscript-variable-name">$q$</span>-bit fraction part (<span class="enscript-keyword">\textit</span>{where <span class="enscript-variable-name">$p+q = k$</span>}).  

In this system a <span class="enscript-variable-name">$k$</span>-bit integer <span class="enscript-variable-name">$n$</span> would actually represent <span class="enscript-variable-name">$n/2^q$</span>.  For example, with <span class="enscript-variable-name">$q = 4$</span> the integer <span class="enscript-variable-name">$n = 37$</span> would actually represent the
value <span class="enscript-variable-name">$2.3125$</span>.  To multiply two fixed point numbers the integers are multiplied using traditional arithmetic and subsequently normalized by 
moving the implied decimal point back to where it should be.  For example, with <span class="enscript-variable-name">$q = 4$</span> to multiply the integers <span class="enscript-variable-name">$9$</span> and <span class="enscript-variable-name">$5$</span> they must be converted 
to fixed point first by multiplying by <span class="enscript-variable-name">$2^q$</span>.  Let <span class="enscript-variable-name">$a = 9(2^q)$</span> represent the fixed point representation of <span class="enscript-variable-name">$9$</span> and <span class="enscript-variable-name">$b = 5(2^q)$</span> represent the 
fixed point representation of <span class="enscript-variable-name">$5$</span>.  The product <span class="enscript-variable-name">$ab$</span> is equal to <span class="enscript-variable-name">$45(2^{2q})$</span> which when normalized by dividing by <span class="enscript-variable-name">$2^q$</span> produces <span class="enscript-variable-name">$45(2^q)$</span>.  

This technique became popular since a normal integer multiplication and logical shift right are the only required operations to perform a multiplication
of two fixed point numbers.  Using fixed point arithmetic, division can be easily approximated by multiplying by the reciprocal.  If <span class="enscript-variable-name">$2^q$</span> is 
equivalent to one than <span class="enscript-variable-name">$2^q/b$</span> is equivalent to the fixed point approximation of <span class="enscript-variable-name">$1/b$</span> using real arithmetic.  Using this fact dividing an integer 
<span class="enscript-variable-name">$a$</span> by another integer <span class="enscript-variable-name">$b$</span> can be achieved with the following expression.

<span class="enscript-keyword">\begin</span>{equation}
<span class="enscript-keyword">\lfloor</span> a / b <span class="enscript-keyword">\rfloor</span> <span class="enscript-keyword">\mbox</span>{ }<span class="enscript-keyword">\approx</span><span class="enscript-keyword">\mbox</span>{ } <span class="enscript-keyword">\lfloor</span> (a <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\lfloor</span> 2^q / b <span class="enscript-keyword">\rfloor</span>)/2^q <span class="enscript-keyword">\rfloor</span>
<span class="enscript-keyword">\end</span>{equation}

The precision of the division is proportional to the value of <span class="enscript-variable-name">$q$</span>.  If the divisor <span class="enscript-variable-name">$b$</span> is used frequently as is the case with 
modular exponentiation pre-computing <span class="enscript-variable-name">$2^q/b$</span> will allow a division to be performed with a multiplication and a right shift.  Both operations
are considerably faster than division on most processors.  

Consider dividing <span class="enscript-variable-name">$19$</span> by <span class="enscript-variable-name">$5$</span>.  The correct result is <span class="enscript-variable-name">$\lfloor 19/5 \rfloor = 3$</span>.  With <span class="enscript-variable-name">$q = 3$</span> the reciprocal is <span class="enscript-variable-name">$\lfloor 2^q/5 \rfloor = 1$</span> which
leads to a product of <span class="enscript-variable-name">$19$</span> which when divided by <span class="enscript-variable-name">$2^q$</span> produces <span class="enscript-variable-name">$2$</span>.  However, with <span class="enscript-variable-name">$q = 4$</span> the reciprocal is <span class="enscript-variable-name">$\lfloor 2^q/5 \rfloor = 3$</span> and
the result of the emulated division is <span class="enscript-variable-name">$\lfloor 3 \cdot 19 / 2^q \rfloor = 3$</span> which is correct.  The value of <span class="enscript-variable-name">$2^q$</span> must be close to or ideally
larger than the dividend.  In effect if <span class="enscript-variable-name">$a$</span> is the dividend then <span class="enscript-variable-name">$q$</span> should allow <span class="enscript-variable-name">$0 \le \lfloor a/2^q \rfloor \le 1$</span> in order for this approach
to work correctly.  Plugging this form of divison into the original equation the following modular residue equation arises.

<span class="enscript-keyword">\begin</span>{equation}
c = a - b <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\lfloor</span> (a <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\lfloor</span> 2^q / b <span class="enscript-keyword">\rfloor</span>)/2^q <span class="enscript-keyword">\rfloor</span>
<span class="enscript-keyword">\end</span>{equation}

Using the notation from <span class="enscript-keyword">\cite</span>{BARRETT} the value of <span class="enscript-variable-name">$\lfloor 2^q / b \rfloor$</span> will be represented by the <span class="enscript-variable-name">$\mu$</span> symbol.  Using the <span class="enscript-variable-name">$\mu$</span>
variable also helps re-inforce the idea that it is meant to be computed once and re-used.

<span class="enscript-keyword">\begin</span>{equation}
c = a - b <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\lfloor</span> (a <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\mu</span>)/2^q <span class="enscript-keyword">\rfloor</span>
<span class="enscript-keyword">\end</span>{equation}

Provided that <span class="enscript-variable-name">$2^q \ge a$</span> this algorithm will produce a quotient that is either exactly correct or off by a value of one.  In the context of Barrett
reduction the value of <span class="enscript-variable-name">$a$</span> is bound by <span class="enscript-variable-name">$0 \le a \le (b - 1)^2$</span> meaning that <span class="enscript-variable-name">$2^q \ge b^2$</span> is sufficient to ensure the reciprocal will have enough
precision.  

Let <span class="enscript-variable-name">$n$</span> represent the number of digits in <span class="enscript-variable-name">$b$</span>.  This algorithm requires approximately <span class="enscript-variable-name">$2n^2$</span> single precision multiplications to produce the quotient and 
another <span class="enscript-variable-name">$n^2$</span> single precision multiplications to find the residue.  In total <span class="enscript-variable-name">$3n^2$</span> single precision multiplications are required to 
reduce the number.  

For example, if <span class="enscript-variable-name">$b = 1179677$</span> and <span class="enscript-variable-name">$q = 41$</span> (<span class="enscript-variable-name">$2^q &gt; b^2$</span>), then the reciprocal <span class="enscript-variable-name">$\mu$</span> is equal to <span class="enscript-variable-name">$\lfloor 2^q / b \rfloor = 1864089$</span>.  Consider reducing
<span class="enscript-variable-name">$a = 180388626447$</span> modulo <span class="enscript-variable-name">$b$</span> using the above reduction equation.  The quotient using the new formula is <span class="enscript-variable-name">$\lfloor (a \cdot \mu) / 2^q \rfloor = 152913$</span>.
By subtracting <span class="enscript-variable-name">$152913b$</span> from <span class="enscript-variable-name">$a$</span> the correct residue <span class="enscript-variable-name">$a \equiv 677346 \mbox{ (mod }b\mbox{)}$</span> is found.

<span class="enscript-keyword">\subsection</span>{Choosing a Radix Point}
Using the fixed point representation a modular reduction can be performed with <span class="enscript-variable-name">$3n^2$</span> single precision multiplications.  If that were the best
that could be achieved a full division<span class="enscript-keyword">\footnote</span>{A division requires approximately <span class="enscript-variable-name">$O(2cn^2)$</span> single precision multiplications for a small value of <span class="enscript-variable-name">$c$</span>.  
See~<span class="enscript-keyword">\ref</span>{sec:division} for further details.} might as well be used in its place.  The key to optimizing the reduction is to reduce the precision of
the initial multiplication that finds the quotient.  

Let <span class="enscript-variable-name">$a$</span> represent the number of which the residue is sought.  Let <span class="enscript-variable-name">$b$</span> represent the modulus used to find the residue.  Let <span class="enscript-variable-name">$m$</span> represent
the number of digits in <span class="enscript-variable-name">$b$</span>.  For the purposes of this discussion we will assume that the number of digits in <span class="enscript-variable-name">$a$</span> is <span class="enscript-variable-name">$2m$</span>, which is generally true if 
two <span class="enscript-variable-name">$m$</span>-digit numbers have been multiplied.  Dividing <span class="enscript-variable-name">$a$</span> by <span class="enscript-variable-name">$b$</span> is the same as dividing a <span class="enscript-variable-name">$2m$</span> digit integer by a <span class="enscript-variable-name">$m$</span> digit integer.  Digits below the 
<span class="enscript-variable-name">$m - 1$</span>'th digit of <span class="enscript-variable-name">$a$</span> will contribute at most a value of <span class="enscript-variable-name">$1$</span> to the quotient because <span class="enscript-variable-name">$\beta^k &lt; b$</span> for any <span class="enscript-variable-name">$0 \le k \le m - 1$</span>.  Another way to
express this is by re-writing <span class="enscript-variable-name">$a$</span> as two parts.  If <span class="enscript-variable-name">$a' \equiv a \mbox{ (mod }b^m\mbox{)}$</span> and <span class="enscript-variable-name">$a'' = a - a'$</span> then 
<span class="enscript-variable-name">${a \over b} \equiv {{a' + a''} \over b}$</span> which is equivalent to <span class="enscript-variable-name">${a' \over b} + {a'' \over b}$</span>.  Since <span class="enscript-variable-name">$a'$</span> is bound to be less than <span class="enscript-variable-name">$b$</span> the quotient
is bound by <span class="enscript-variable-name">$0 \le {a' \over b} &lt; 1$</span>.

Since the digits of <span class="enscript-variable-name">$a'$</span> do not contribute much to the quotient the observation is that they might as well be zero.  However, if the digits 
``might as well be zero'' they might as well not be there in the first place.  Let <span class="enscript-variable-name">$q_0 = \lfloor a/\beta^{m-1} \rfloor$</span> represent the input
with the irrelevant digits trimmed.  Now the modular reduction is trimmed to the almost equivalent equation

<span class="enscript-keyword">\begin</span>{equation}
c = a - b <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\lfloor</span> (q_0 <span class="enscript-keyword">\cdot</span> <span class="enscript-keyword">\mu</span>) / <span class="enscript-keyword">\beta</span>^{m+1} <span class="enscript-keyword">\rfloor</span>
<span class="enscript-keyword">\end</span>{equation}

Note that the original divisor <span class="enscript-variable-name">$2^q$</span> has been replaced with <span class="enscript-variable-name">$\beta^{m+1}$</span> where in this case <span class="enscript-variable-name">$q$</span> is a multiple of <span class="enscript-variable-name">$lg(\beta)$</span>. Also note that the 
exponent on the divisor when added to the amount <span class="enscript-variable-name">$q_0$</span> was shifted by equals <span class="enscript-variable-name">$2m$</span>.  If the optimization had not been performed the divisor 
would have the exponent <span class="enscript-variable-name">$2m$</span> so in the end the exponents do ``add up''. Using the above equation the quotient 
<span class="enscript-variable-name">$\lfloor (q_0 \cdot \mu) / \beta^{m+1} \rfloor$</span> can be off from the true quotient by at most two.  The original fixed point quotient can be off
by as much as one (<span class="enscript-keyword">\textit</span>{provided the radix point is chosen suitably}) and now that the lower irrelevent digits have been trimmed the quotient
can be off by an additional value of one for a total of at most two.  This implies that 
<span class="enscript-variable-name">$0 \le a - b \cdot \lfloor (q_0 \cdot \mu) / \beta^{m+1} \rfloor &lt; 3b$</span>.  By first subtracting <span class="enscript-variable-name">$b$</span> times the quotient and then conditionally subtracting 
<span class="enscript-variable-name">$b$</span> once or twice the residue is found.

The quotient is now found using <span class="enscript-variable-name">$(m + 1)(m) = m^2 + m$</span> single precision multiplications and the residue with an additional <span class="enscript-variable-name">$m^2$</span> single
precision multiplications, ignoring the subtractions required.  In total <span class="enscript-variable-name">$2m^2 + m$</span> single precision multiplications are required to find the residue.  
This is considerably faster than the original attempt.

For example, let <span class="enscript-variable-name">$\beta = 10$</span> represent the radix of the digits.  Let <span class="enscript-variable-name">$b = 9999$</span> represent the modulus which implies <span class="enscript-variable-name">$m = 4$</span>. Let <span class="enscript-variable-name">$a = 99929878$</span> 
represent the value of which the residue is desired.  In this case <span class="enscript-variable-name">$q = 8$</span> since <span class="enscript-variable-name">$10^7 &lt; 9999^2$</span> meaning that <span class="enscript-variable-name">$\mu = \lfloor \beta^{q}/b \rfloor = 10001$</span>.  
With the new observation the multiplicand for the quotient is equal to <span class="enscript-variable-name">$q_0 = \lfloor a / \beta^{m - 1} \rfloor = 99929$</span>.  The quotient is then 
<span class="enscript-variable-name">$\lfloor (q_0 \cdot \mu) / \beta^{m+1} \rfloor = 9993$</span>.  Subtracting <span class="enscript-variable-name">$9993b$</span> from <span class="enscript-variable-name">$a$</span> and the correct residue <span class="enscript-variable-name">$a \equiv 9871 \mbox{ (mod }b\mbox{)}$</span> 
is found.  

<span class="enscript-keyword">\subsection</span>{Trimming the Quotient}
So far the reduction algorithm has been optimized from <span class="enscript-variable-name">$3m^2$</span> single precision multiplications down to <span class="enscript-variable-name">$2m^2 + m$</span> single precision multiplications.  As 
it stands now the algorithm is already fairly fast compared to a full integer division algorithm.  However, there is still room for
optimization.  

After the first multiplication inside the quotient (<span class="enscript-variable-name">$q_0 \cdot \mu$</span>) the value is shifted right by <span class="enscript-variable-name">$m + 1$</span> places effectively nullifying the lower
half of the product.  It would be nice to be able to remove those digits from the product to effectively cut down the number of single precision 
multiplications.  If the number of digits in the modulus <span class="enscript-variable-name">$m$</span> is far less than <span class="enscript-variable-name">$\beta$</span> a full product is not required for the algorithm to work properly.  
In fact the lower <span class="enscript-variable-name">$m - 2$</span> digits will not affect the upper half of the product at all and do not need to be computed.  

The value of <span class="enscript-variable-name">$\mu$</span> is a <span class="enscript-variable-name">$m$</span>-digit number and <span class="enscript-variable-name">$q_0$</span> is a <span class="enscript-variable-name">$m + 1$</span> digit number.  Using a full multiplier <span class="enscript-variable-name">$(m + 1)(m) = m^2 + m$</span> single precision
multiplications would be required.  Using a multiplier that will only produce digits at and above the <span class="enscript-variable-name">$m - 1$</span>'th digit reduces the number
of single precision multiplications to <span class="enscript-variable-name">${m^2 + m} \over 2$</span> single precision multiplications.  

<span class="enscript-keyword">\subsection</span>{Trimming the Residue}
After the quotient has been calculated it is used to reduce the input.  As previously noted the algorithm is not exact and it can be off by a small
multiple of the modulus, that is <span class="enscript-variable-name">$0 \le a - b \cdot \lfloor (q_0 \cdot \mu) / \beta^{m+1} \rfloor &lt; 3b$</span>.  If <span class="enscript-variable-name">$b$</span> is <span class="enscript-variable-name">$m$</span> digits than the 
result of reduction equation is a value of at most <span class="enscript-variable-name">$m + 1$</span> digits (<span class="enscript-keyword">\textit</span>{provided <span class="enscript-variable-name">$3 &lt; \beta$</span>}) implying that the upper <span class="enscript-variable-name">$m - 1$</span> digits are
implicitly zero.  

The next optimization arises from this very fact.  Instead of computing <span class="enscript-variable-name">$b \cdot \lfloor (q_0 \cdot \mu) / \beta^{m+1} \rfloor$</span> using a full
<span class="enscript-variable-name">$O(m^2)$</span> multiplication algorithm only the lower <span class="enscript-variable-name">$m+1$</span> digits of the product have to be computed.  Similarly the value of <span class="enscript-variable-name">$a$</span> can
be reduced modulo <span class="enscript-variable-name">$\beta^{m+1}$</span> before the multiple of <span class="enscript-variable-name">$b$</span> is subtracted which simplifes the subtraction as well.  A multiplication that produces 
only the lower <span class="enscript-variable-name">$m+1$</span> digits requires <span class="enscript-variable-name">${m^2 + 3m - 2} \over 2$</span> single precision multiplications.  

With both optimizations in place the algorithm is the algorithm Barrett proposed.  It requires <span class="enscript-variable-name">$m^2 + 2m - 1$</span> single precision multiplications which
is considerably faster than the straightforward <span class="enscript-variable-name">$3m^2$</span> method.  

<span class="enscript-keyword">\subsection</span>{The Barrett Algorithm}
<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>reduce}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>, mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$\mu = \lfloor \beta^{2m}/b \rfloor, m = \lceil lg_{\beta}(b) \rceil, (0 \le a &lt; b^2, b &gt; 1)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$a \mbox{ (mod }b\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
Let <span class="enscript-variable-name">$m$</span> represent the number of digits in <span class="enscript-variable-name">$b$</span>.  <span class="enscript-keyword">\\</span>
1.  Make a copy of <span class="enscript-variable-name">$a$</span> and store it in <span class="enscript-variable-name">$q$</span>.  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy}) <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$q \leftarrow \lfloor q / \beta^{m - 1} \rfloor$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>rshd}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Produce the quotient. <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$q \leftarrow q \cdot \mu$</span>  (<span class="enscript-keyword">\textit</span>{note: only produce digits at or above <span class="enscript-variable-name">$m-1$</span>}) <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$q \leftarrow \lfloor q / \beta^{m + 1} \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Subtract the multiple of modulus from the input. <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$a \leftarrow a \mbox{ (mod }\beta^{m+1}\mbox{)}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d}) <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$q \leftarrow q \cdot b \mbox{ (mod }\beta^{m+1}\mbox{)}$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs}) <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$a \leftarrow a - q$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>sub}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Add <span class="enscript-variable-name">$\beta^{m+1}$</span> if a carry occured. <span class="enscript-keyword">\\</span>
8.  If <span class="enscript-variable-name">$a &lt; 0$</span> then (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>d}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  <span class="enscript-variable-name">$q \leftarrow 1$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>set}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.2  <span class="enscript-variable-name">$q \leftarrow q \cdot \beta^{m+1}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>lshd}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.3  <span class="enscript-variable-name">$a \leftarrow a + q$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Now subtract the modulus if the residue is too large (e.g. quotient too small). <span class="enscript-keyword">\\</span>
9.  While <span class="enscript-variable-name">$a \ge b$</span> do (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>cmp}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.1  <span class="enscript-variable-name">$c \leftarrow a - b$</span> <span class="enscript-keyword">\\</span>
10.  Clear <span class="enscript-variable-name">$q$</span>. <span class="enscript-keyword">\\</span>
11.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce.}
This algorithm will reduce the input <span class="enscript-variable-name">$a$</span> modulo <span class="enscript-variable-name">$b$</span> in place using the Barrett algorithm.  It is loosely based on algorithm 14.42 of HAC
<span class="enscript-keyword">\cite</span>[pp.  602]{HAC} which is based on the paper from Paul Barrett <span class="enscript-keyword">\cite</span>{BARRETT}.  The algorithm has several restrictions and assumptions which must 
be adhered to for the algorithm to work.

First the modulus <span class="enscript-variable-name">$b$</span> is assumed to be positive and greater than one.  If the modulus were less than or equal to one than subtracting
a multiple of it would either accomplish nothing or actually enlarge the input.  The input <span class="enscript-variable-name">$a$</span> must be in the range <span class="enscript-variable-name">$0 \le a &lt; b^2$</span> in order
for the quotient to have enough precision.  If <span class="enscript-variable-name">$a$</span> is the product of two numbers that were already reduced modulo <span class="enscript-variable-name">$b$</span>, this will not be a problem.
Technically the algorithm will still work if <span class="enscript-variable-name">$a \ge b^2$</span> but it will take much longer to finish.  The value of <span class="enscript-variable-name">$\mu$</span> is passed as an argument to this 
algorithm and is assumed to be calculated and stored before the algorithm is used.  

Recall that the multiplication for the quotient on step 3 must only produce digits at or above the <span class="enscript-variable-name">$m-1$</span>'th position.  An algorithm called 
<span class="enscript-variable-name">$s\_mp\_mul\_high\_digs$</span> which has not been presented is used to accomplish this task.  The algorithm is based on <span class="enscript-variable-name">$s\_mp\_mul\_digs$</span> except that
instead of stopping at a given level of precision it starts at a given level of precision.  This optimal algorithm can only be used if the number
of digits in <span class="enscript-variable-name">$b$</span> is very much smaller than <span class="enscript-variable-name">$\beta$</span>.  

While it is known that 
<span class="enscript-variable-name">$a \ge b \cdot \lfloor (q_0 \cdot \mu) / \beta^{m+1} \rfloor$</span> only the lower <span class="enscript-variable-name">$m+1$</span> digits are being used to compute the residue, so an implied 
``borrow'' from the higher digits might leave a negative result.  After the multiple of the modulus has been subtracted from <span class="enscript-variable-name">$a$</span> the residue must be 
fixed up in case it is negative.  The invariant <span class="enscript-variable-name">$\beta^{m+1}$</span> must be added to the residue to make it positive again.  

The while loop at step 9 will subtract <span class="enscript-variable-name">$b$</span> until the residue is less than <span class="enscript-variable-name">$b$</span>.  If the algorithm is performed correctly this step is 
performed at most twice, and on average once. However, if <span class="enscript-variable-name">$a \ge b^2$</span> than it will iterate substantially more times than it should.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>reduce.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The first multiplication that determines the quotient can be performed by only producing the digits from <span class="enscript-variable-name">$m - 1$</span> and up.  This essentially halves
the number of single precision multiplications required.  However, the optimization is only safe if <span class="enscript-variable-name">$\beta$</span> is much larger than the number of digits
in the modulus.  In the source code this is evaluated on lines 36 to 44 where algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>high<span class="enscript-keyword">\_</span>digs is used when it is
safe to do so.  

<span class="enscript-keyword">\subsection</span>{The Barrett Setup Algorithm}
In order to use algorithm mp<span class="enscript-keyword">\_</span>reduce the value of <span class="enscript-variable-name">$\mu$</span> must be calculated in advance.  Ideally this value should be computed once and stored for
future use so that the Barrett algorithm can be used without delay.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>setup}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> (<span class="enscript-variable-name">$a &gt; 1$</span>)  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$\mu \leftarrow \lfloor \beta^{2m}/a \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$\mu \leftarrow 2^{2 \cdot lg(\beta) \cdot  m}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>2expt}) <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$\mu \leftarrow \lfloor \mu / b \rfloor$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>div}) <span class="enscript-keyword">\\</span>
3.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>setup}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>setup.}
This algorithm computes the reciprocal <span class="enscript-variable-name">$\mu$</span> required for Barrett reduction.  First <span class="enscript-variable-name">$\beta^{2m}$</span> is calculated as <span class="enscript-variable-name">$2^{2 \cdot lg(\beta) \cdot  m}$</span> which
is equivalent and much faster.  The final value is computed by taking the integer quotient of <span class="enscript-variable-name">$\lfloor \mu / b \rfloor$</span>.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>setup.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This simple routine calculates the reciprocal <span class="enscript-variable-name">$\mu$</span> required by Barrett reduction.  Note the extended usage of algorithm mp<span class="enscript-keyword">\_</span>div where the variable
which would received the remainder is passed as NULL.  As will be discussed in~<span class="enscript-keyword">\ref</span>{sec:division} the division routine allows both the quotient and the 
remainder to be passed as NULL meaning to ignore the value.  

<span class="enscript-keyword">\section</span>{The Montgomery Reduction}
Montgomery reduction<span class="enscript-keyword">\footnote</span>{Thanks to Niels Ferguson for his insightful explanation of the algorithm.} <span class="enscript-keyword">\cite</span>{MONT} is by far the most interesting 
form of reduction in common use.  It computes a modular residue which is not actually equal to the residue of the input yet instead equal to a 
residue times a constant.  However, as perplexing as this may sound the algorithm is relatively simple and very efficient.  

Throughout this entire section the variable <span class="enscript-variable-name">$n$</span> will represent the modulus used to form the residue.  As will be discussed shortly the value of
<span class="enscript-variable-name">$n$</span> must be odd.  The variable <span class="enscript-variable-name">$x$</span> will represent the quantity of which the residue is sought.  Similar to the Barrett algorithm the input
is restricted to <span class="enscript-variable-name">$0 \le x &lt; n^2$</span>.  To begin the description some simple number theory facts must be established.

<span class="enscript-keyword">\textbf</span>{Fact 1.}  Adding <span class="enscript-variable-name">$n$</span> to <span class="enscript-variable-name">$x$</span> does not change the residue since in effect it adds one to the quotient <span class="enscript-variable-name">$\lfloor x / n \rfloor$</span>.  Another way
to explain this is that <span class="enscript-variable-name">$n$</span> is (<span class="enscript-keyword">\textit</span>{or multiples of <span class="enscript-variable-name">$n$</span> are}) congruent to zero modulo <span class="enscript-variable-name">$n$</span>.  Adding zero will not change the value of the residue.  

<span class="enscript-keyword">\textbf</span>{Fact 2.}  If <span class="enscript-variable-name">$x$</span> is even then performing a division by two in <span class="enscript-variable-name">$\Z$</span> is congruent to <span class="enscript-variable-name">$x \cdot 2^{-1} \mbox{ (mod }n\mbox{)}$</span>.  Actually
this is an application of the fact that if <span class="enscript-variable-name">$x$</span> is evenly divisible by any <span class="enscript-variable-name">$k \in \Z$</span> then division in <span class="enscript-variable-name">$\Z$</span> will be congruent to 
multiplication by <span class="enscript-variable-name">$k^{-1}$</span> modulo <span class="enscript-variable-name">$n$</span>.  

From these two simple facts the following simple algorithm can be derived.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Montgomery Reduction}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Integer <span class="enscript-variable-name">$x$</span>, <span class="enscript-variable-name">$n$</span> and <span class="enscript-variable-name">$k$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$2^{-k}x \mbox{ (mod }n\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  for <span class="enscript-variable-name">$t$</span> from <span class="enscript-variable-name">$1$</span> to <span class="enscript-variable-name">$k$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  If <span class="enscript-variable-name">$x$</span> is odd then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}1.1.1  <span class="enscript-variable-name">$x \leftarrow x + n$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  <span class="enscript-variable-name">$x \leftarrow x/2$</span> <span class="enscript-keyword">\\</span>
2.  Return <span class="enscript-variable-name">$x$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Montgomery Reduction}
<span class="enscript-keyword">\end</span>{figure}

The algorithm reduces the input one bit at a time using the two congruencies stated previously.  Inside the loop <span class="enscript-variable-name">$n$</span>, which is odd, is
added to <span class="enscript-variable-name">$x$</span> if <span class="enscript-variable-name">$x$</span> is odd.  This forces <span class="enscript-variable-name">$x$</span> to be even which allows the division by two in <span class="enscript-variable-name">$\Z$</span> to be congruent to a modular division by two.  Since
<span class="enscript-variable-name">$x$</span> is assumed to be initially much larger than <span class="enscript-variable-name">$n$</span> the addition of <span class="enscript-variable-name">$n$</span> will contribute an insignificant magnitude to <span class="enscript-variable-name">$x$</span>.  Let <span class="enscript-variable-name">$r$</span> represent the 
final result of the Montgomery algorithm.  If <span class="enscript-variable-name">$k &gt; lg(n)$</span> and <span class="enscript-variable-name">$0 \le x &lt; n^2$</span> then the final result is limited to 
<span class="enscript-variable-name">$0 \le r &lt; \lfloor x/2^k \rfloor + n$</span>.  As a result at most a single subtraction is required to get the residue desired.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|l|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Step number (<span class="enscript-variable-name">$t$</span>)} &amp; <span class="enscript-keyword">\textbf</span>{Result (<span class="enscript-variable-name">$x$</span>)} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1$</span> &amp; <span class="enscript-variable-name">$x + n = 5812$</span>, <span class="enscript-variable-name">$x/2 = 2906$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$2$</span> &amp; <span class="enscript-variable-name">$x/2 = 1453$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$3$</span> &amp; <span class="enscript-variable-name">$x + n = 1710$</span>, <span class="enscript-variable-name">$x/2 = 855$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$4$</span> &amp; <span class="enscript-variable-name">$x + n = 1112$</span>, <span class="enscript-variable-name">$x/2 = 556$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$5$</span> &amp; <span class="enscript-variable-name">$x/2 = 278$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$6$</span> &amp; <span class="enscript-variable-name">$x/2 = 139$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$7$</span> &amp; <span class="enscript-variable-name">$x + n = 396$</span>, <span class="enscript-variable-name">$x/2 = 198$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$8$</span> &amp; <span class="enscript-variable-name">$x/2 = 99$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$9$</span> &amp; <span class="enscript-variable-name">$x + n = 356$</span>, <span class="enscript-variable-name">$x/2 = 178$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Example of Montgomery Reduction (I)}
<span class="enscript-keyword">\label</span>{fig:MONT1}
<span class="enscript-keyword">\end</span>{figure}

Consider the example in figure~<span class="enscript-keyword">\ref</span>{fig:MONT1} which reduces <span class="enscript-variable-name">$x = 5555$</span> modulo <span class="enscript-variable-name">$n = 257$</span> when <span class="enscript-variable-name">$k = 9$</span> (note <span class="enscript-variable-name">$\beta^k = 512$</span> which is larger than <span class="enscript-variable-name">$n$</span>).  The result of 
the algorithm <span class="enscript-variable-name">$r = 178$</span> is congruent to the value of <span class="enscript-variable-name">$2^{-9} \cdot 5555 \mbox{ (mod }257\mbox{)}$</span>.  When <span class="enscript-variable-name">$r$</span> is multiplied by <span class="enscript-variable-name">$2^9$</span> modulo <span class="enscript-variable-name">$257$</span> the correct residue 
<span class="enscript-variable-name">$r \equiv 158$</span> is produced.  

Let <span class="enscript-variable-name">$k = \lfloor lg(n) \rfloor + 1$</span> represent the number of bits in <span class="enscript-variable-name">$n$</span>.  The current algorithm requires <span class="enscript-variable-name">$2k^2$</span> single precision shifts
and <span class="enscript-variable-name">$k^2$</span> single precision additions.  At this rate the algorithm is most certainly slower than Barrett reduction and not terribly useful.  
Fortunately there exists an alternative representation of the algorithm.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Montgomery Reduction} (modified I). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Integer <span class="enscript-variable-name">$x$</span>, <span class="enscript-variable-name">$n$</span> and <span class="enscript-variable-name">$k$</span> (<span class="enscript-variable-name">$2^k &gt; n$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$2^{-k}x \mbox{ (mod }n\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  for <span class="enscript-variable-name">$t$</span> from <span class="enscript-variable-name">$1$</span> to <span class="enscript-variable-name">$k$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  If the <span class="enscript-variable-name">$t$</span>'th bit of <span class="enscript-variable-name">$x$</span> is one then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}1.1.1  <span class="enscript-variable-name">$x \leftarrow x + 2^tn$</span> <span class="enscript-keyword">\\</span>
2.  Return <span class="enscript-variable-name">$x/2^k$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Montgomery Reduction (modified I)}
<span class="enscript-keyword">\end</span>{figure}

This algorithm is equivalent since <span class="enscript-variable-name">$2^tn$</span> is a multiple of <span class="enscript-variable-name">$n$</span> and the lower <span class="enscript-variable-name">$k$</span> bits of <span class="enscript-variable-name">$x$</span> are zero by step 2.  The number of single
precision shifts has now been reduced from <span class="enscript-variable-name">$2k^2$</span> to <span class="enscript-variable-name">$k^2 + k$</span> which is only a small improvement.

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|l|r|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Step number (<span class="enscript-variable-name">$t$</span>)} &amp; <span class="enscript-keyword">\textbf</span>{Result (<span class="enscript-variable-name">$x$</span>)} &amp; <span class="enscript-keyword">\textbf</span>{Result (<span class="enscript-variable-name">$x$</span>) in Binary} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> -- &amp; <span class="enscript-variable-name">$5555$</span> &amp; <span class="enscript-variable-name">$1010110110011$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1$</span> &amp; <span class="enscript-variable-name">$x + 2^{0}n = 5812$</span> &amp;  <span class="enscript-variable-name">$1011010110100$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$2$</span> &amp; <span class="enscript-variable-name">$5812$</span> &amp; <span class="enscript-variable-name">$1011010110100$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$3$</span> &amp; <span class="enscript-variable-name">$x + 2^{2}n = 6840$</span> &amp; <span class="enscript-variable-name">$1101010111000$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$4$</span> &amp; <span class="enscript-variable-name">$x + 2^{3}n = 8896$</span> &amp; <span class="enscript-variable-name">$10001011000000$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$5$</span> &amp; <span class="enscript-variable-name">$8896$</span> &amp; <span class="enscript-variable-name">$10001011000000$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$6$</span> &amp; <span class="enscript-variable-name">$8896$</span> &amp; <span class="enscript-variable-name">$10001011000000$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$7$</span> &amp; <span class="enscript-variable-name">$x + 2^{6}n = 25344$</span> &amp; <span class="enscript-variable-name">$110001100000000$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$8$</span> &amp; <span class="enscript-variable-name">$25344$</span> &amp; <span class="enscript-variable-name">$110001100000000$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$9$</span> &amp; <span class="enscript-variable-name">$x + 2^{7}n = 91136$</span> &amp; <span class="enscript-variable-name">$10110010000000000$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> -- &amp; <span class="enscript-variable-name">$x/2^k = 178$</span> &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Example of Montgomery Reduction (II)}
<span class="enscript-keyword">\label</span>{fig:MONT2}
<span class="enscript-keyword">\end</span>{figure}

Figure~<span class="enscript-keyword">\ref</span>{fig:MONT2} demonstrates the modified algorithm reducing <span class="enscript-variable-name">$x = 5555$</span> modulo <span class="enscript-variable-name">$n = 257$</span> with <span class="enscript-variable-name">$k = 9$</span>. 
With this algorithm a single shift right at the end is the only right shift required to reduce the input instead of <span class="enscript-variable-name">$k$</span> right shifts inside the 
loop.  Note that for the iterations <span class="enscript-variable-name">$t = 2, 5, 6$</span> and <span class="enscript-variable-name">$8$</span> where the result <span class="enscript-variable-name">$x$</span> is not changed.  In those iterations the <span class="enscript-variable-name">$t$</span>'th bit of <span class="enscript-variable-name">$x$</span> is 
zero and the appropriate multiple of <span class="enscript-variable-name">$n$</span> does not need to be added to force the <span class="enscript-variable-name">$t$</span>'th bit of the result to zero.  

<span class="enscript-keyword">\subsection</span>{Digit Based Montgomery Reduction}
Instead of computing the reduction on a bit-by-bit basis it is actually much faster to compute it on digit-by-digit basis.  Consider the
previous algorithm re-written to compute the Montgomery reduction in this new fashion.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Montgomery Reduction} (modified II). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Integer <span class="enscript-variable-name">$x$</span>, <span class="enscript-variable-name">$n$</span> and <span class="enscript-variable-name">$k$</span> (<span class="enscript-variable-name">$\beta^k &gt; n$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$\beta^{-k}x \mbox{ (mod }n\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  for <span class="enscript-variable-name">$t$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$k - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$x \leftarrow x + \mu n \beta^t$</span> <span class="enscript-keyword">\\</span>
2.  Return <span class="enscript-variable-name">$x/\beta^k$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Montgomery Reduction (modified II)}
<span class="enscript-keyword">\end</span>{figure}

The value <span class="enscript-variable-name">$\mu n \beta^t$</span> is a multiple of the modulus <span class="enscript-variable-name">$n$</span> meaning that it will not change the residue.  If the first digit of 
the value <span class="enscript-variable-name">$\mu n \beta^t$</span> equals the negative (modulo <span class="enscript-variable-name">$\beta$</span>) of the <span class="enscript-variable-name">$t$</span>'th digit of <span class="enscript-variable-name">$x$</span> then the addition will result in a zero digit.  This
problem breaks down to solving the following congruency.  

<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{rcl}
<span class="enscript-variable-name">$x_t + \mu n_0$</span> &amp; <span class="enscript-variable-name">$\equiv$</span> &amp; <span class="enscript-variable-name">$0 \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\mu n_0$</span> &amp; <span class="enscript-variable-name">$\equiv$</span> &amp; <span class="enscript-variable-name">$-x_t \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\mu$</span> &amp; <span class="enscript-variable-name">$\equiv$</span> &amp; <span class="enscript-variable-name">$-x_t/n_0 \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}

In each iteration of the loop on step 1 a new value of <span class="enscript-variable-name">$\mu$</span> must be calculated.  The value of <span class="enscript-variable-name">$-1/n_0 \mbox{ (mod }\beta\mbox{)}$</span> is used 
extensively in this algorithm and should be precomputed.  Let <span class="enscript-variable-name">$\rho$</span> represent the negative of the modular inverse of <span class="enscript-variable-name">$n_0$</span> modulo <span class="enscript-variable-name">$\beta$</span>.  

For example, let <span class="enscript-variable-name">$\beta = 10$</span> represent the radix.  Let <span class="enscript-variable-name">$n = 17$</span> represent the modulus which implies <span class="enscript-variable-name">$k = 2$</span> and <span class="enscript-variable-name">$\rho \equiv 7$</span>.  Let <span class="enscript-variable-name">$x = 33$</span> 
represent the value to reduce.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Step (<span class="enscript-variable-name">$t$</span>)} &amp; <span class="enscript-keyword">\textbf</span>{Value of <span class="enscript-variable-name">$x$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Value of <span class="enscript-variable-name">$\mu$</span>} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> --                 &amp; <span class="enscript-variable-name">$33$</span> &amp; --<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$0$</span>                 &amp; <span class="enscript-variable-name">$33 + \mu n = 50$</span> &amp; <span class="enscript-variable-name">$1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1$</span>                 &amp; <span class="enscript-variable-name">$50 + \mu n \beta = 900$</span> &amp; <span class="enscript-variable-name">$5$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Example of Montgomery Reduction}
<span class="enscript-keyword">\end</span>{figure}

The final result <span class="enscript-variable-name">$900$</span> is then divided by <span class="enscript-variable-name">$\beta^k$</span> to produce the final result <span class="enscript-variable-name">$9$</span>.  The first observation is that <span class="enscript-variable-name">$9 \nequiv x \mbox{ (mod }n\mbox{)}$</span> 
which implies the result is not the modular residue of <span class="enscript-variable-name">$x$</span> modulo <span class="enscript-variable-name">$n$</span>.  However, recall that the residue is actually multiplied by <span class="enscript-variable-name">$\beta^{-k}$</span> in
the algorithm.  To get the true residue the value must be multiplied by <span class="enscript-variable-name">$\beta^k$</span>.  In this case <span class="enscript-variable-name">$\beta^k \equiv 15 \mbox{ (mod }n\mbox{)}$</span> and
the correct residue is <span class="enscript-variable-name">$9 \cdot 15 \equiv 16 \mbox{ (mod }n\mbox{)}$</span>.  

<span class="enscript-keyword">\subsection</span>{Baseline Montgomery Reduction}
The baseline Montgomery reduction algorithm will produce the residue for any size input.  It is designed to be a catch-all algororithm for 
Montgomery reductions.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$x$</span>, mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$n$</span> and a digit <span class="enscript-variable-name">$\rho \equiv -1/n_0 \mbox{ (mod }n\mbox{)}$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{11.5mm}(<span class="enscript-variable-name">$0 \le x &lt; n^2, n &gt; 1, (n, \beta) = 1, \beta^k &gt; n$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$\beta^{-k}x \mbox{ (mod }n\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$digs \leftarrow 2n.used + 1$</span> <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$digs &lt; MP\_ARRAY$</span> and <span class="enscript-variable-name">$m.used &lt; \delta$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  Use algorithm fast<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce instead. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Setup <span class="enscript-variable-name">$x$</span> for the reduction. <span class="enscript-keyword">\\</span>
3.  If <span class="enscript-variable-name">$x.alloc &lt; digs$</span> then grow <span class="enscript-variable-name">$x$</span> to <span class="enscript-variable-name">$digs$</span> digits. <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$x.used \leftarrow digs$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Eliminate the lower <span class="enscript-variable-name">$k$</span> digits. <span class="enscript-keyword">\\</span>
5.  For <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$k - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$\mu \leftarrow x_{ix} \cdot \rho \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$u \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  For <span class="enscript-variable-name">$iy$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$k - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.3.1  <span class="enscript-variable-name">$\hat r \leftarrow \mu n_{iy} + x_{ix + iy} + u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.3.2  <span class="enscript-variable-name">$x_{ix + iy} \leftarrow \hat r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.3.3  <span class="enscript-variable-name">$u \leftarrow \lfloor \hat r / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.4  While <span class="enscript-variable-name">$u &gt; 0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.4.1  <span class="enscript-variable-name">$iy \leftarrow iy + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.4.2  <span class="enscript-variable-name">$x_{ix + iy} \leftarrow x_{ix + iy} + u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.4.3  <span class="enscript-variable-name">$u \leftarrow \lfloor x_{ix+iy} / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.4.4  <span class="enscript-variable-name">$x_{ix + iy} \leftarrow x_{ix+iy} \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Divide by <span class="enscript-variable-name">$\beta^k$</span> and fix up as required. <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$x \leftarrow \lfloor x / \beta^k \rfloor$</span> <span class="enscript-keyword">\\</span>
7.  If <span class="enscript-variable-name">$x \ge n$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  <span class="enscript-variable-name">$x \leftarrow x - n$</span> <span class="enscript-keyword">\\</span>
8.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce.}
This algorithm reduces the input <span class="enscript-variable-name">$x$</span> modulo <span class="enscript-variable-name">$n$</span> in place using the Montgomery reduction algorithm.  The algorithm is loosely based
on algorithm 14.32 of <span class="enscript-keyword">\cite</span>[pp.601]{HAC} except it merges the multiplication of <span class="enscript-variable-name">$\mu n \beta^t$</span> with the addition in the inner loop.  The
restrictions on this algorithm are fairly easy to adapt to.  First <span class="enscript-variable-name">$0 \le x &lt; n^2$</span> bounds the input to numbers in the same range as 
for the Barrett algorithm.  Additionally if <span class="enscript-variable-name">$n &gt; 1$</span> and <span class="enscript-variable-name">$n$</span> is odd there will exist a modular inverse <span class="enscript-variable-name">$\rho$</span>.  <span class="enscript-variable-name">$\rho$</span> must be calculated in
advance of this algorithm.  Finally the variable <span class="enscript-variable-name">$k$</span> is fixed and a pseudonym for <span class="enscript-variable-name">$n.used$</span>.  

Step 2 decides whether a faster Montgomery algorithm can be used.  It is based on the Comba technique meaning that there are limits on
the size of the input.  This algorithm is discussed in sub-section 6.3.3.

Step 5 is the main reduction loop of the algorithm.  The value of <span class="enscript-variable-name">$\mu$</span> is calculated once per iteration in the outer loop.  The inner loop
calculates <span class="enscript-variable-name">$x + \mu n \beta^{ix}$</span> by multiplying <span class="enscript-variable-name">$\mu n$</span> and adding the result to <span class="enscript-variable-name">$x$</span> shifted by <span class="enscript-variable-name">$ix$</span> digits.  Both the addition and
multiplication are performed in the same loop to save time and memory.  Step 5.4 will handle any additional carries that escape the inner loop.

Using a quick inspection this algorithm requires <span class="enscript-variable-name">$n$</span> single precision multiplications for the outer loop and <span class="enscript-variable-name">$n^2$</span> single precision multiplications 
in the inner loop.  In total <span class="enscript-variable-name">$n^2 + n$</span> single precision multiplications which compares favourably to Barrett at <span class="enscript-variable-name">$n^2 + 2n - 1$</span> single precision
multiplications.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This is the baseline implementation of the Montgomery reduction algorithm.  Lines 31 to 36 determine if the Comba based
routine can be used instead.  Line 47 computes the value of <span class="enscript-variable-name">$\mu$</span> for that particular iteration of the outer loop.  

The multiplication <span class="enscript-variable-name">$\mu n \beta^{ix}$</span> is performed in one step in the inner loop.  The alias <span class="enscript-variable-name">$tmpx$</span> refers to the <span class="enscript-variable-name">$ix$</span>'th digit of <span class="enscript-variable-name">$x$</span> and
the alias <span class="enscript-variable-name">$tmpn$</span> refers to the modulus <span class="enscript-variable-name">$n$</span>.  

<span class="enscript-keyword">\subsection</span>{Faster ``Comba'' Montgomery Reduction}

The Montgomery reduction requires fewer single precision multiplications than a Barrett reduction, however it is much slower due to the serial
nature of the inner loop.  The Barrett reduction algorithm requires two slightly modified multipliers which can be implemented with the Comba
technique.  The Montgomery reduction algorithm cannot directly use the Comba technique to any significant advantage since the inner loop calculates
a <span class="enscript-variable-name">$k \times 1$</span> product <span class="enscript-variable-name">$k$</span> times. 

The biggest obstacle is that at the <span class="enscript-variable-name">$ix$</span>'th iteration of the outer loop the value of <span class="enscript-variable-name">$x_{ix}$</span> is required to calculate <span class="enscript-variable-name">$\mu$</span>.  This means the 
carries from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$ix - 1$</span> must have been propagated upwards to form a valid <span class="enscript-variable-name">$ix$</span>'th digit.  The solution as it turns out is very simple.  
Perform a Comba like multiplier and inside the outer loop just after the inner loop fix up the <span class="enscript-variable-name">$ix + 1$</span>'th digit by forwarding the carry.  

With this change in place the Montgomery reduction algorithm can be performed with a Comba style multiplication loop which substantially increases
the speed of the algorithm.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{fast<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$x$</span>, mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$n$</span> and a digit <span class="enscript-variable-name">$\rho \equiv -1/n_0 \mbox{ (mod }n\mbox{)}$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{11.5mm}(<span class="enscript-variable-name">$0 \le x &lt; n^2, n &gt; 1, (n, \beta) = 1, \beta^k &gt; n$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$\beta^{-k}x \mbox{ (mod }n\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
Place an array of <span class="enscript-keyword">\textbf</span>{MP<span class="enscript-keyword">\_</span>WARRAY} mp<span class="enscript-keyword">\_</span>word variables called <span class="enscript-variable-name">$\hat W$</span> on the stack. <span class="enscript-keyword">\\</span>
1.  if <span class="enscript-variable-name">$x.alloc &lt; n.used + 1$</span> then grow <span class="enscript-variable-name">$x$</span> to <span class="enscript-variable-name">$n.used + 1$</span> digits. <span class="enscript-keyword">\\</span>
Copy the digits of <span class="enscript-variable-name">$x$</span> into the array <span class="enscript-variable-name">$\hat W$</span> <span class="enscript-keyword">\\</span>
2.  For <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$x.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$\hat W_{ix} \leftarrow x_{ix}$</span> <span class="enscript-keyword">\\</span>
3.  For <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$x.used$</span> to <span class="enscript-variable-name">$2n.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$\hat W_{ix} \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
Elimiate the lower <span class="enscript-variable-name">$k$</span> digits. <span class="enscript-keyword">\\</span>
4.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$n.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$\mu \leftarrow \hat W_{ix} \cdot \rho \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.2  For <span class="enscript-variable-name">$iy$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$n.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}4.2.1  <span class="enscript-variable-name">$\hat W_{iy + ix} \leftarrow \hat W_{iy + ix} + \mu \cdot n_{iy}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.3  <span class="enscript-variable-name">$\hat W_{ix + 1} \leftarrow \hat W_{ix + 1} + \lfloor \hat W_{ix} / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
Propagate carries upwards. <span class="enscript-keyword">\\</span>
5.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$n.used$</span> to <span class="enscript-variable-name">$2n.used + 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$\hat W_{ix + 1} \leftarrow \hat W_{ix + 1} + \lfloor \hat W_{ix} / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
Shift right and reduce modulo <span class="enscript-variable-name">$\beta$</span> simultaneously. <span class="enscript-keyword">\\</span>
6.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$n.used + 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$x_{ix} \leftarrow \hat W_{ix + n.used} \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
Zero excess digits and fixup <span class="enscript-variable-name">$x$</span>. <span class="enscript-keyword">\\</span>
7.  if <span class="enscript-variable-name">$x.used &gt; n.used + 1$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$n.used + 1$</span> to <span class="enscript-variable-name">$x.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.1.1  <span class="enscript-variable-name">$x_{ix} \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$x.used \leftarrow n.used + 1$</span> <span class="enscript-keyword">\\</span>
9.  Clamp excessive digits of <span class="enscript-variable-name">$x$</span>. <span class="enscript-keyword">\\</span>
10.  If <span class="enscript-variable-name">$x \ge n$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}10.1  <span class="enscript-variable-name">$x \leftarrow x - n$</span> <span class="enscript-keyword">\\</span>
11.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm fast<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm fast<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce.}
This algorithm will compute the Montgomery reduction of <span class="enscript-variable-name">$x$</span> modulo <span class="enscript-variable-name">$n$</span> using the Comba technique.  It is on most computer platforms significantly
faster than algorithm mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce and algorithm mp<span class="enscript-keyword">\_</span>reduce (<span class="enscript-keyword">\textit</span>{Barrett reduction}).  The algorithm has the same restrictions
on the input as the baseline reduction algorithm.  An additional two restrictions are imposed on this algorithm.  The number of digits <span class="enscript-variable-name">$k$</span> in the 
the modulus <span class="enscript-variable-name">$n$</span> must not violate <span class="enscript-variable-name">$MP\_WARRAY &gt; 2k +1$</span> and <span class="enscript-variable-name">$n &lt; \delta$</span>.   When <span class="enscript-variable-name">$\beta = 2^{28}$</span> this algorithm can be used to reduce modulo
a modulus of at most <span class="enscript-variable-name">$3,556$</span> bits in length.  

As in the other Comba reduction algorithms there is a <span class="enscript-variable-name">$\hat W$</span> array which stores the columns of the product.  It is initially filled with the
contents of <span class="enscript-variable-name">$x$</span> with the excess digits zeroed.  The reduction loop is very similar the to the baseline loop at heart.  The multiplication on step
4.1 can be single precision only since <span class="enscript-variable-name">$ab \mbox{ (mod }\beta\mbox{)} \equiv (a \mbox{ mod }\beta)(b \mbox{ mod }\beta)$</span>.  Some multipliers such
as those on the ARM processors take a variable length time to complete depending on the number of bytes of result it must produce.  By performing
a single precision multiplication instead half the amount of time is spent.

Also note that digit <span class="enscript-variable-name">$\hat W_{ix}$</span> must have the carry from the <span class="enscript-variable-name">$ix - 1$</span>'th digit propagated upwards in order for this to work.  That is what step
4.3 will do.  In effect over the <span class="enscript-variable-name">$n.used$</span> iterations of the outer loop the <span class="enscript-variable-name">$n.used$</span>'th lower columns all have the their carries propagated forwards.  Note
how the upper bits of those same words are not reduced modulo <span class="enscript-variable-name">$\beta$</span>.  This is because those values will be discarded shortly and there is no
point.

Step 5 will propagate the remainder of the carries upwards.  On step 6 the columns are reduced modulo <span class="enscript-variable-name">$\beta$</span> and shifted simultaneously as they are
stored in the destination <span class="enscript-variable-name">$x$</span>.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>fast<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>reduce.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The <span class="enscript-variable-name">$\hat W$</span> array is first filled with digits of <span class="enscript-variable-name">$x$</span> on line 48 then the rest of the digits are zeroed on line 55.  Both loops share
the same alias variables to make the code easier to read.  

The value of <span class="enscript-variable-name">$\mu$</span> is calculated in an interesting fashion.  First the value <span class="enscript-variable-name">$\hat W_{ix}$</span> is reduced modulo <span class="enscript-variable-name">$\beta$</span> and cast to a mp<span class="enscript-keyword">\_</span>digit.  This
forces the compiler to use a single precision multiplication and prevents any concerns about loss of precision.   Line 110 fixes the carry 
for the next iteration of the loop by propagating the carry from <span class="enscript-variable-name">$\hat W_{ix}$</span> to <span class="enscript-variable-name">$\hat W_{ix+1}$</span>.

The for loop on line 109 propagates the rest of the carries upwards through the columns.  The for loop on line 126 reduces the columns
modulo <span class="enscript-variable-name">$\beta$</span> and shifts them <span class="enscript-variable-name">$k$</span> places at the same time.  The alias <span class="enscript-variable-name">$\_ \hat W$</span> actually refers to the array <span class="enscript-variable-name">$\hat W$</span> starting at the <span class="enscript-variable-name">$n.used$</span>'th
digit, that is <span class="enscript-variable-name">$\_ \hat W_{t} = \hat W_{n.used + t}$</span>.  

<span class="enscript-keyword">\subsection</span>{Montgomery Setup}
To calculate the variable <span class="enscript-variable-name">$\rho$</span> a relatively simple algorithm will be required.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>setup}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$n$</span> (<span class="enscript-variable-name">$n &gt; 1$</span> and <span class="enscript-variable-name">$(n, 2) = 1$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$\rho \equiv -1/n_0 \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$b \leftarrow n_0$</span> <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$b$</span> is even return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}) <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$x \leftarrow (((b + 2) \mbox{ AND } 4) &lt;&lt; 1) + b$</span> <span class="enscript-keyword">\\</span>
4.  for <span class="enscript-variable-name">$k$</span> from 0 to <span class="enscript-variable-name">$\lceil lg(lg(\beta)) \rceil - 2$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$x \leftarrow x \cdot (2 - bx)$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$\rho \leftarrow \beta - x \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
6.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>setup} 
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>setup.}
This algorithm will calculate the value of <span class="enscript-variable-name">$\rho$</span> required within the Montgomery reduction algorithms.  It uses a very interesting trick 
to calculate <span class="enscript-variable-name">$1/n_0$</span> when <span class="enscript-variable-name">$\beta$</span> is a power of two.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>setup.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This source code computes the value of <span class="enscript-variable-name">$\rho$</span> required to perform Montgomery reduction.  It has been modified to avoid performing excess
multiplications when <span class="enscript-variable-name">$\beta$</span> is not the default 28-bits.  

<span class="enscript-keyword">\section</span>{The Diminished Radix Algorithm}
The Diminished Radix method of modular reduction <span class="enscript-keyword">\cite</span>{DRMET} is a fairly clever technique which can be more efficient than either the Barrett
or Montgomery methods for certain forms of moduli.  The technique is based on the following simple congruence.

<span class="enscript-keyword">\begin</span>{equation}
(x <span class="enscript-keyword">\mbox</span>{ mod } n) + k <span class="enscript-keyword">\lfloor</span> x / n <span class="enscript-keyword">\rfloor</span> <span class="enscript-keyword">\equiv</span> x <span class="enscript-keyword">\mbox</span>{ (mod }(n - k)<span class="enscript-keyword">\mbox</span>{)}
<span class="enscript-keyword">\end</span>{equation}

This observation was used in the MMB <span class="enscript-keyword">\cite</span>{MMB} block cipher to create a diffusion primitive.  It used the fact that if <span class="enscript-variable-name">$n = 2^{31}$</span> and <span class="enscript-variable-name">$k=1$</span> that 
then a x86 multiplier could produce the 62-bit product and use  the ``shrd'' instruction to perform a double-precision right shift.  The proof
of the above equation is very simple.  First write <span class="enscript-variable-name">$x$</span> in the product form.

<span class="enscript-keyword">\begin</span>{equation}
x = qn + r
<span class="enscript-keyword">\end</span>{equation}

Now reduce both sides modulo <span class="enscript-variable-name">$(n - k)$</span>.

<span class="enscript-keyword">\begin</span>{equation}
x <span class="enscript-keyword">\equiv</span> qk + r  <span class="enscript-keyword">\mbox</span>{ (mod }(n-k)<span class="enscript-keyword">\mbox</span>{)}
<span class="enscript-keyword">\end</span>{equation}

The variable <span class="enscript-variable-name">$n$</span> reduces modulo <span class="enscript-variable-name">$n - k$</span> to <span class="enscript-variable-name">$k$</span>.  By putting <span class="enscript-variable-name">$q = \lfloor x/n \rfloor$</span> and <span class="enscript-variable-name">$r = x \mbox{ mod } n$</span> 
into the equation the original congruence is reproduced, thus concluding the proof.  The following algorithm is based on this observation.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Diminished Radix Reduction}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Integer <span class="enscript-variable-name">$x$</span>, <span class="enscript-variable-name">$n$</span>, <span class="enscript-variable-name">$k$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$x \mbox{ mod } (n - k)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$q \leftarrow \lfloor x / n \rfloor$</span> <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$q \leftarrow k \cdot q$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$x \leftarrow x \mbox{ (mod }n\mbox{)}$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$x \leftarrow x + q$</span> <span class="enscript-keyword">\\</span>
5.  If <span class="enscript-variable-name">$x \ge (n - k)$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$x \leftarrow x - (n - k)$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  Goto step 1. <span class="enscript-keyword">\\</span>
6.  Return <span class="enscript-variable-name">$x$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Diminished Radix Reduction}
<span class="enscript-keyword">\label</span>{fig:DR}
<span class="enscript-keyword">\end</span>{figure}

This algorithm will reduce <span class="enscript-variable-name">$x$</span> modulo <span class="enscript-variable-name">$n - k$</span> and return the residue.  If <span class="enscript-variable-name">$0 \le x &lt; (n - k)^2$</span> then the algorithm will loop almost always
once or twice and occasionally three times.  For simplicity sake the value of <span class="enscript-variable-name">$x$</span> is bounded by the following simple polynomial.

<span class="enscript-keyword">\begin</span>{equation} 
0 <span class="enscript-keyword">\le</span> x &lt; n^2 + k^2 - 2nk
<span class="enscript-keyword">\end</span>{equation}

The true bound is  <span class="enscript-variable-name">$0 \le x &lt; (n - k - 1)^2$</span> but this has quite a few more terms.  The value of <span class="enscript-variable-name">$q$</span> after step 1 is bounded by the following.

<span class="enscript-keyword">\begin</span>{equation}
q &lt; n - 2k - k^2/n
<span class="enscript-keyword">\end</span>{equation}

Since <span class="enscript-variable-name">$k^2$</span> is going to be considerably smaller than <span class="enscript-variable-name">$n$</span> that term will always be zero.  The value of <span class="enscript-variable-name">$x$</span> after step 3 is bounded trivially as
<span class="enscript-variable-name">$0 \le x &lt; n$</span>.  By step four the sum <span class="enscript-variable-name">$x + q$</span> is bounded by 

<span class="enscript-keyword">\begin</span>{equation}
0 <span class="enscript-keyword">\le</span> q + x &lt; (k + 1)n - 2k^2 - 1
<span class="enscript-keyword">\end</span>{equation}

With a second pass <span class="enscript-variable-name">$q$</span> will be loosely bounded by <span class="enscript-variable-name">$0 \le q &lt; k^2$</span> after step 2 while <span class="enscript-variable-name">$x$</span> will still be loosely bounded by <span class="enscript-variable-name">$0 \le x &lt; n$</span> after step 3.  After the second pass it is highly unlike that the
sum in step 4 will exceed <span class="enscript-variable-name">$n - k$</span>.  In practice fewer than three passes of the algorithm are required to reduce virtually every input in the 
range <span class="enscript-variable-name">$0 \le x &lt; (n - k - 1)^2$</span>.  

<span class="enscript-keyword">\begin</span>{figure}
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|l|}
<span class="enscript-keyword">\hline</span>
<span class="enscript-variable-name">$x = 123456789, n = 256, k = 3$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$q \leftarrow \lfloor x/n \rfloor = 482253$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$q \leftarrow q*k = 1446759$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x \mbox{ mod } n = 21$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x + q = 1446780$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x - (n - k) = 1446527$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> 
<span class="enscript-variable-name">$q \leftarrow \lfloor x/n \rfloor = 5650$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$q \leftarrow q*k = 16950$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x \mbox{ mod } n = 127$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x + q = 17077$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x - (n - k) = 16824$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> 
<span class="enscript-variable-name">$q \leftarrow \lfloor x/n \rfloor = 65$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$q \leftarrow q*k = 195$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x \mbox{ mod } n = 184$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x + q = 379$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$x \leftarrow x - (n - k) = 126$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Example Diminished Radix Reduction}
<span class="enscript-keyword">\label</span>{fig:EXDR}
<span class="enscript-keyword">\end</span>{figure}

Figure~<span class="enscript-keyword">\ref</span>{fig:EXDR} demonstrates the reduction of <span class="enscript-variable-name">$x = 123456789$</span> modulo <span class="enscript-variable-name">$n - k = 253$</span> when <span class="enscript-variable-name">$n = 256$</span> and <span class="enscript-variable-name">$k = 3$</span>.  Note that even while <span class="enscript-variable-name">$x$</span>
is considerably larger than <span class="enscript-variable-name">$(n - k - 1)^2 = 63504$</span> the algorithm still converges on the modular residue exceedingly fast.  In this case only
three passes were required to find the residue <span class="enscript-variable-name">$x \equiv 126$</span>.


<span class="enscript-keyword">\subsection</span>{Choice of Moduli}
On the surface this algorithm looks like a very expensive algorithm.  It requires a couple of subtractions followed by multiplication and other
modular reductions.  The usefulness of this algorithm becomes exceedingly clear when an appropriate modulus is chosen.

Division in general is a very expensive operation to perform.  The one exception is when the division is by a power of the radix of representation used.  
Division by ten for example is simple for pencil and paper mathematics since it amounts to shifting the decimal place to the right.  Similarly division 
by two (<span class="enscript-keyword">\textit</span>{or powers of two}) is very simple for binary computers to perform.  It would therefore seem logical to choose <span class="enscript-variable-name">$n$</span> of the form <span class="enscript-variable-name">$2^p$</span> 
which would imply that <span class="enscript-variable-name">$\lfloor x / n \rfloor$</span> is a simple shift of <span class="enscript-variable-name">$x$</span> right <span class="enscript-variable-name">$p$</span> bits.  

However, there is one operation related to division of power of twos that is even faster than this.  If <span class="enscript-variable-name">$n = \beta^p$</span> then the division may be 
performed by moving whole digits to the right <span class="enscript-variable-name">$p$</span> places.  In practice division by <span class="enscript-variable-name">$\beta^p$</span> is much faster than division by <span class="enscript-variable-name">$2^p$</span> for any <span class="enscript-variable-name">$p$</span>.  
Also with the choice of <span class="enscript-variable-name">$n = \beta^p$</span> reducing <span class="enscript-variable-name">$x$</span> modulo <span class="enscript-variable-name">$n$</span> merely requires zeroing the digits above the <span class="enscript-variable-name">$p-1$</span>'th digit of <span class="enscript-variable-name">$x$</span>.  

Throughout the next section the term ``restricted modulus'' will refer to a modulus of the form <span class="enscript-variable-name">$\beta^p - k$</span> whereas the term ``unrestricted
modulus'' will refer to a modulus of the form <span class="enscript-variable-name">$2^p - k$</span>.  The word ``restricted'' in this case refers to the fact that it is based on the 
<span class="enscript-variable-name">$2^p$</span> logic except <span class="enscript-variable-name">$p$</span> must be a multiple of <span class="enscript-variable-name">$lg(\beta)$</span>.  

<span class="enscript-keyword">\subsection</span>{Choice of <span class="enscript-variable-name">$k$</span>}
Now that division and reduction (<span class="enscript-keyword">\textit</span>{step 1 and 3 of figure~<span class="enscript-keyword">\ref</span>{fig:DR}}) have been optimized to simple digit operations the multiplication by <span class="enscript-variable-name">$k$</span>
in step 2 is the most expensive operation.  Fortunately the choice of <span class="enscript-variable-name">$k$</span> is not terribly limited.  For all intents and purposes it might
as well be a single digit.  The smaller the value of <span class="enscript-variable-name">$k$</span> is the faster the algorithm will be.  

<span class="enscript-keyword">\subsection</span>{Restricted Diminished Radix Reduction}
The restricted Diminished Radix algorithm can quickly reduce an input modulo a modulus of the form <span class="enscript-variable-name">$n = \beta^p - k$</span>.  This algorithm can reduce 
an input <span class="enscript-variable-name">$x$</span> within the range <span class="enscript-variable-name">$0 \le x &lt; n^2$</span> using only a couple passes of the algorithm demonstrated in figure~<span class="enscript-keyword">\ref</span>{fig:DR}.  The implementation
of this algorithm has been optimized to avoid additional overhead associated with a division by <span class="enscript-variable-name">$\beta^p$</span>, the multiplication by <span class="enscript-variable-name">$k$</span> or the addition 
of <span class="enscript-variable-name">$x$</span> and <span class="enscript-variable-name">$q$</span>.  The resulting algorithm is very efficient and can lead to substantial improvements over Barrett and Montgomery reduction when modular 
exponentiations are performed.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>reduce}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$x$</span>, <span class="enscript-variable-name">$n$</span> and a mp<span class="enscript-keyword">\_</span>digit <span class="enscript-variable-name">$k = \beta - n_0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{11.5mm}(<span class="enscript-variable-name">$0 \le x &lt; n^2$</span>, <span class="enscript-variable-name">$n &gt; 1$</span>, <span class="enscript-variable-name">$0 &lt; k &lt; \beta$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$x \mbox{ mod } n$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$m \leftarrow n.used$</span> <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$x.alloc &lt; 2m$</span> then grow <span class="enscript-variable-name">$x$</span> to <span class="enscript-variable-name">$2m$</span> digits. <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$\mu \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
4.  for <span class="enscript-variable-name">$i$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$m - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$\hat r \leftarrow k \cdot x_{m+i} + x_{i} + \mu$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.2  <span class="enscript-variable-name">$x_{i} \leftarrow \hat r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.3  <span class="enscript-variable-name">$\mu \leftarrow \lfloor \hat r / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$x_{m} \leftarrow \mu$</span> <span class="enscript-keyword">\\</span>
6.  for <span class="enscript-variable-name">$i$</span> from <span class="enscript-variable-name">$m + 1$</span> to <span class="enscript-variable-name">$x.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$x_{i} \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
7.  Clamp excess digits of <span class="enscript-variable-name">$x$</span>. <span class="enscript-keyword">\\</span>
8.  If <span class="enscript-variable-name">$x \ge n$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  <span class="enscript-variable-name">$x \leftarrow x - n$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.2  Goto step 3. <span class="enscript-keyword">\\</span>
9.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>reduce}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>reduce.}
This algorithm will perform the Dimished Radix reduction of <span class="enscript-variable-name">$x$</span> modulo <span class="enscript-variable-name">$n$</span>.  It has similar restrictions to that of the Barrett reduction
with the addition that <span class="enscript-variable-name">$n$</span> must be of the form <span class="enscript-variable-name">$n = \beta^m - k$</span> where <span class="enscript-variable-name">$0 &lt; k &lt;\beta$</span>.  

This algorithm essentially implements the pseudo-code in figure~<span class="enscript-keyword">\ref</span>{fig:DR} except with a slight optimization.  The division by <span class="enscript-variable-name">$\beta^m$</span>, multiplication by <span class="enscript-variable-name">$k$</span>
and addition of <span class="enscript-variable-name">$x \mbox{ mod }\beta^m$</span> are all performed simultaneously inside the loop on step 4.  The division by <span class="enscript-variable-name">$\beta^m$</span> is emulated by accessing
the term at the <span class="enscript-variable-name">$m+i$</span>'th position which is subsequently multiplied by <span class="enscript-variable-name">$k$</span> and added to the term at the <span class="enscript-variable-name">$i$</span>'th position.  After the loop the <span class="enscript-variable-name">$m$</span>'th
digit is set to the carry and the upper digits are zeroed.  Steps 5 and 6 emulate the reduction modulo <span class="enscript-variable-name">$\beta^m$</span> that should have happend to 
<span class="enscript-variable-name">$x$</span> before the addition of the multiple of the upper half.  

At step 8 if <span class="enscript-variable-name">$x$</span> is still larger than <span class="enscript-variable-name">$n$</span> another pass of the algorithm is required.  First <span class="enscript-variable-name">$n$</span> is subtracted from <span class="enscript-variable-name">$x$</span> and then the algorithm resumes
at step 3.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>reduce.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The first step is to grow <span class="enscript-variable-name">$x$</span> as required to <span class="enscript-variable-name">$2m$</span> digits since the reduction is performed in place on <span class="enscript-variable-name">$x$</span>.  The label on line 52 is where
the algorithm will resume if further reduction passes are required.  In theory it could be placed at the top of the function however, the size of
the modulus and question of whether <span class="enscript-variable-name">$x$</span> is large enough are invariant after the first pass meaning that it would be a waste of time.  

The aliases <span class="enscript-variable-name">$tmpx1$</span> and <span class="enscript-variable-name">$tmpx2$</span> refer to the digits of <span class="enscript-variable-name">$x$</span> where the latter is offset by <span class="enscript-variable-name">$m$</span> digits.  By reading digits from <span class="enscript-variable-name">$x$</span> offset by <span class="enscript-variable-name">$m$</span> digits
a division by <span class="enscript-variable-name">$\beta^m$</span> can be simulated virtually for free.  The loop on line 64 performs the bulk of the work (<span class="enscript-keyword">\textit</span>{corresponds to step 4 of algorithm 7.11})
in this algorithm.

By line 67 the pointer <span class="enscript-variable-name">$tmpx1$</span> points to the <span class="enscript-variable-name">$m$</span>'th digit of <span class="enscript-variable-name">$x$</span> which is where the final carry will be placed.  Similarly by line 74 the 
same pointer will point to the <span class="enscript-variable-name">$m+1$</span>'th digit where the zeroes will be placed.  

Since the algorithm is only valid if both <span class="enscript-variable-name">$x$</span> and <span class="enscript-variable-name">$n$</span> are greater than zero an unsigned comparison suffices to determine if another pass is required.  
With the same logic at line 81 the value of <span class="enscript-variable-name">$x$</span> is known to be greater than or equal to <span class="enscript-variable-name">$n$</span> meaning that an unsigned subtraction can be used
as well.  Since the destination of the subtraction is the larger of the inputs the call to algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub cannot fail and the return code
does not need to be checked.

<span class="enscript-keyword">\subsubsection</span>{Setup}
To setup the restricted Diminished Radix algorithm the value <span class="enscript-variable-name">$k = \beta - n_0$</span> is required.  This algorithm is not really complicated but provided for
completeness.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>setup}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$n$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$k = \beta - n_0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$k \leftarrow \beta - n_0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>setup}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>setup.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\subsubsection</span>{Modulus Detection}
Another algorithm which will be useful is the ability to detect a restricted Diminished Radix modulus.  An integer is said to be
of restricted Diminished Radix form if all of the digits are equal to <span class="enscript-variable-name">$\beta - 1$</span> except the trailing digit which may be any value.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>modulus}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$n$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$1$</span> if <span class="enscript-variable-name">$n$</span> is in D.R form, <span class="enscript-variable-name">$0$</span> otherwise <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
1.  If <span class="enscript-variable-name">$n.used &lt; 2$</span> then return(<span class="enscript-variable-name">$0$</span>). <span class="enscript-keyword">\\</span>
2.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$1$</span> to <span class="enscript-variable-name">$n.used - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  If <span class="enscript-variable-name">$n_{ix} \ne \beta - 1$</span> return(<span class="enscript-variable-name">$0$</span>). <span class="enscript-keyword">\\</span>
3.  Return(<span class="enscript-variable-name">$1$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>modulus}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>modulus.}
This algorithm determines if a value is in Diminished Radix form.  Step 1 rejects obvious cases where fewer than two digits are
in the mp<span class="enscript-keyword">\_</span>int.  Step 2 tests all but the first digit to see if they are equal to <span class="enscript-variable-name">$\beta - 1$</span>.  If the algorithm manages to get to
step 3 then <span class="enscript-variable-name">$n$</span> must be of Diminished Radix form.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>dr<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>modulus.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\subsection</span>{Unrestricted Diminished Radix Reduction}
The unrestricted Diminished Radix algorithm allows modular reductions to be performed when the modulus is of the form <span class="enscript-variable-name">$2^p - k$</span>.  This algorithm
is a straightforward adaptation of algorithm~<span class="enscript-keyword">\ref</span>{fig:DR}.

In general the restricted Diminished Radix reduction algorithm is much faster since it has considerably lower overhead.  However, this new
algorithm is much faster than either Montgomery or Barrett reduction when the moduli are of the appropriate form.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$n$</span>.  mp<span class="enscript-keyword">\_</span>digit <span class="enscript-variable-name">$k$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{11.5mm}(<span class="enscript-variable-name">$a \ge 0$</span>, <span class="enscript-variable-name">$n &gt; 1$</span>, <span class="enscript-variable-name">$0 &lt; k &lt; \beta$</span>, <span class="enscript-variable-name">$n + k$</span> is a power of two) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$a \mbox{ (mod }n\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
1.  <span class="enscript-variable-name">$p \leftarrow \lceil lg(n) \rceil$</span>  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>count<span class="enscript-keyword">\_</span>bits}) <span class="enscript-keyword">\\</span>
2.  While <span class="enscript-variable-name">$a \ge n$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$q \leftarrow \lfloor a / 2^p \rfloor$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2d}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  <span class="enscript-variable-name">$a \leftarrow a \mbox{ (mod }2^p\mbox{)}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>2d}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.3  <span class="enscript-variable-name">$q \leftarrow q \cdot k$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>d}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.4  <span class="enscript-variable-name">$a \leftarrow a - q$</span> (<span class="enscript-keyword">\textit</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.5  If <span class="enscript-variable-name">$a \ge n$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.5.1  <span class="enscript-variable-name">$a \leftarrow a - n$</span> <span class="enscript-keyword">\\</span>
3.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k.}
This algorithm quickly reduces an input <span class="enscript-variable-name">$a$</span> modulo an unrestricted Diminished Radix modulus <span class="enscript-variable-name">$n$</span>.  Division by <span class="enscript-variable-name">$2^p$</span> is emulated with a right
shift which makes the algorithm fairly inexpensive to use.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The algorithm mp<span class="enscript-keyword">\_</span>count<span class="enscript-keyword">\_</span>bits calculates the number of bits in an mp<span class="enscript-keyword">\_</span>int which is used to find the initial value of <span class="enscript-variable-name">$p$</span>.  The call to mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>2d
on line 31 calculates both the quotient <span class="enscript-variable-name">$q$</span> and the remainder <span class="enscript-variable-name">$a$</span> required.  By doing both in a single function call the code size
is kept fairly small.  The multiplication by <span class="enscript-variable-name">$k$</span> is only performed if <span class="enscript-variable-name">$k &gt; 1$</span>. This allows reductions modulo <span class="enscript-variable-name">$2^p - 1$</span> to be performed without
any multiplications.  

The unsigned s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add, mp<span class="enscript-keyword">\_</span>cmp<span class="enscript-keyword">\_</span>mag and s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>sub are used in place of their full sign counterparts since the inputs are only valid if they are 
positive.  By using the unsigned versions the overhead is kept to a minimum.  

<span class="enscript-keyword">\subsubsection</span>{Unrestricted Setup}
To setup this reduction algorithm the value of <span class="enscript-variable-name">$k = 2^p - n$</span> is required.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k<span class="enscript-keyword">\_</span>setup}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$n$</span>   <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$k = 2^p - n$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
1.  <span class="enscript-variable-name">$p \leftarrow \lceil lg(n) \rceil$</span>  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>count<span class="enscript-keyword">\_</span>bits}) <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$x \leftarrow 2^p$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>2expt}) <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$x \leftarrow x - n$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>sub}) <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$k \leftarrow x_0$</span> <span class="enscript-keyword">\\</span>
5.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k<span class="enscript-keyword">\_</span>setup}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k<span class="enscript-keyword">\_</span>setup.}
This algorithm computes the value of <span class="enscript-variable-name">$k$</span> required for the algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k.  By making a temporary variable <span class="enscript-variable-name">$x$</span> equal to <span class="enscript-variable-name">$2^p$</span> a subtraction
is sufficient to solve for <span class="enscript-variable-name">$k$</span>.  Alternatively if <span class="enscript-variable-name">$n$</span> has more than one digit the value of <span class="enscript-variable-name">$k$</span> is simply <span class="enscript-variable-name">$\beta - n_0$</span>.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k<span class="enscript-keyword">\_</span>setup.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\subsubsection</span>{Unrestricted Detection}
An integer <span class="enscript-variable-name">$n$</span> is a valid unrestricted Diminished Radix modulus if either of the following are true.

<span class="enscript-keyword">\begin</span>{enumerate}
<span class="enscript-keyword">\item</span>  The number has only one digit.
<span class="enscript-keyword">\item</span>  The number has more than one digit and every bit from the <span class="enscript-variable-name">$\beta$</span>'th to the most significant is one.
<span class="enscript-keyword">\end</span>{enumerate}

If either condition is true than there is a power of two <span class="enscript-variable-name">$2^p$</span> such that <span class="enscript-variable-name">$0 &lt; 2^p - n &lt; \beta$</span>.   If the input is only
one digit than it will always be of the correct form.  Otherwise all of the bits above the first digit must be one.  This arises from the fact
that there will be value of <span class="enscript-variable-name">$k$</span> that when added to the modulus causes a carry in the first digit which propagates all the way to the most
significant bit.  The resulting sum will be a power of two.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>2k}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$n$</span>   <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$1$</span> if of proper form, <span class="enscript-variable-name">$0$</span> otherwise <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
1.  If <span class="enscript-variable-name">$n.used = 0$</span> then return(<span class="enscript-variable-name">$0$</span>). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$n.used = 1$</span> then return(<span class="enscript-variable-name">$1$</span>). <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$p \leftarrow \lceil lg(n) \rceil$</span>  (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>count<span class="enscript-keyword">\_</span>bits}) <span class="enscript-keyword">\\</span>
4.  for <span class="enscript-variable-name">$x$</span> from <span class="enscript-variable-name">$lg(\beta)$</span> to <span class="enscript-variable-name">$p$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  If the (<span class="enscript-variable-name">$x \mbox{ mod }lg(\beta)$</span>)'th bit of the <span class="enscript-variable-name">$\lfloor x / lg(\beta) \rfloor$</span> of <span class="enscript-variable-name">$n$</span> is zero then return(<span class="enscript-variable-name">$0$</span>). <span class="enscript-keyword">\\</span>
5.  Return(<span class="enscript-variable-name">$1$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>2k}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>2k.}
This algorithm quickly determines if a modulus is of the form required for algorithm mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>2k to function properly.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>2k.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}



<span class="enscript-keyword">\section</span>{Algorithm Comparison}
So far three very different algorithms for modular reduction have been discussed.  Each of the algorithms have their own strengths and weaknesses
that makes having such a selection very useful.  The following table sumarizes the three algorithms along with comparisons of work factors.  Since
all three algorithms have the restriction that <span class="enscript-variable-name">$0 \le x &lt; n^2$</span> and <span class="enscript-variable-name">$n &gt; 1$</span> those limitations are not included in the table.  

<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|c|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Method} &amp; <span class="enscript-keyword">\textbf</span>{Work Required} &amp; <span class="enscript-keyword">\textbf</span>{Limitations} &amp; <span class="enscript-keyword">\textbf</span>{<span class="enscript-variable-name">$m = 8$</span>} &amp; <span class="enscript-keyword">\textbf</span>{<span class="enscript-variable-name">$m = 32$</span>} &amp; <span class="enscript-keyword">\textbf</span>{<span class="enscript-variable-name">$m = 64$</span>} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> Barrett    &amp; <span class="enscript-variable-name">$m^2 + 2m - 1$</span> &amp; None              &amp; <span class="enscript-variable-name">$79$</span> &amp; <span class="enscript-variable-name">$1087$</span> &amp; <span class="enscript-variable-name">$4223$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> Montgomery &amp; <span class="enscript-variable-name">$m^2 + m$</span>      &amp; <span class="enscript-variable-name">$n$</span> must be odd   &amp; <span class="enscript-variable-name">$72$</span> &amp; <span class="enscript-variable-name">$1056$</span> &amp; <span class="enscript-variable-name">$4160$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> D.R.       &amp; <span class="enscript-variable-name">$2m$</span>           &amp; <span class="enscript-variable-name">$n = \beta^m - k$</span> &amp; <span class="enscript-variable-name">$16$</span> &amp; <span class="enscript-variable-name">$64$</span>   &amp; <span class="enscript-variable-name">$128$</span>  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\end</span>{center}

In theory Montgomery and Barrett reductions would require roughly the same amount of time to complete.  However, in practice since Montgomery
reduction can be written as a single function with the Comba technique it is much faster.  Barrett reduction suffers from the overhead of
calling the half precision multipliers, addition and division by <span class="enscript-variable-name">$\beta$</span> algorithms.

For almost every cryptographic algorithm Montgomery reduction is the algorithm of choice.  The one set of algorithms where Diminished Radix reduction truly
shines are based on the discrete logarithm problem such as Diffie-Hellman <span class="enscript-keyword">\cite</span>{DH} and ElGamal <span class="enscript-keyword">\cite</span>{ELGAMAL}.  In these algorithms
primes of the form <span class="enscript-variable-name">$\beta^m - k$</span> can be found and shared amongst users.  These primes will allow the Diminished Radix algorithm to be used in
modular exponentiation to greatly speed up the operation.



<span class="enscript-keyword">\section</span>*{Exercises}
<span class="enscript-keyword">\begin</span>{tabular}{cl}
<span class="enscript-variable-name">$\left [ 3 \right ]$</span> &amp; Prove that the ``trick'' in algorithm mp<span class="enscript-keyword">\_</span>montgomery<span class="enscript-keyword">\_</span>setup actually <span class="enscript-keyword">\\</span>
                     &amp; calculates the correct value of <span class="enscript-variable-name">$\rho$</span>. <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 2 \right ]$</span> &amp; Devise an algorithm to reduce modulo <span class="enscript-variable-name">$n + k$</span> for small <span class="enscript-variable-name">$k$</span> quickly.  <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-variable-name">$\left [ 4 \right ]$</span> &amp; Prove that the pseudo-code algorithm ``Diminished Radix Reduction'' <span class="enscript-keyword">\\</span>
                     &amp; (<span class="enscript-keyword">\textit</span>{figure~<span class="enscript-keyword">\ref</span>{fig:DR}}) terminates.  Also prove the probability that it will <span class="enscript-keyword">\\</span>
                     &amp; terminate within <span class="enscript-variable-name">$1 \le k \le 10$</span> iterations. <span class="enscript-keyword">\\</span>
                     &amp; <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\end</span>{tabular}                     


<span class="enscript-keyword">\chapter</span>{Exponentiation}
Exponentiation is the operation of raising one variable to the power of another, for example, <span class="enscript-variable-name">$a^b$</span>.  A variant of exponentiation, computed
in a finite field or ring, is called modular exponentiation.  This latter style of operation is typically used in public key 
cryptosystems such as RSA and Diffie-Hellman.  The ability to quickly compute modular exponentiations is of great benefit to any
such cryptosystem and many methods have been sought to speed it up.

<span class="enscript-keyword">\section</span>{Exponentiation Basics}
A trivial algorithm would simply multiply <span class="enscript-variable-name">$a$</span> against itself <span class="enscript-variable-name">$b - 1$</span> times to compute the exponentiation desired.  However, as <span class="enscript-variable-name">$b$</span> grows in size
the number of multiplications becomes prohibitive.  Imagine what would happen if <span class="enscript-variable-name">$b$</span> <span class="enscript-variable-name">$\approx$</span> <span class="enscript-variable-name">$2^{1024}$</span> as is the case when computing an RSA signature
with a <span class="enscript-variable-name">$1024$</span>-bit key.  Such a calculation could never be completed as it would take simply far too long.

Fortunately there is a very simple algorithm based on the laws of exponents.  Recall that <span class="enscript-variable-name">$lg_a(a^b) = b$</span> and that <span class="enscript-variable-name">$lg_a(a^ba^c) = b + c$</span> which
are two trivial relationships between the base and the exponent.  Let <span class="enscript-variable-name">$b_i$</span> represent the <span class="enscript-variable-name">$i$</span>'th bit of <span class="enscript-variable-name">$b$</span> starting from the least 
significant bit.  If <span class="enscript-variable-name">$b$</span> is a <span class="enscript-variable-name">$k$</span>-bit integer than the following equation is true.

<span class="enscript-keyword">\begin</span>{equation}
a^b = <span class="enscript-keyword">\prod</span>_{i=0}^{k-1} a^{2^i <span class="enscript-keyword">\cdot</span> b_i}
<span class="enscript-keyword">\end</span>{equation}

By taking the base <span class="enscript-variable-name">$a$</span> logarithm of both sides of the equation the following equation is the result.

<span class="enscript-keyword">\begin</span>{equation}
b = <span class="enscript-keyword">\sum</span>_{i=0}^{k-1}2^i <span class="enscript-keyword">\cdot</span> b_i
<span class="enscript-keyword">\end</span>{equation}

The term <span class="enscript-variable-name">$a^{2^i}$</span> can be found from the <span class="enscript-variable-name">$i - 1$</span>'th term by squaring the term since <span class="enscript-variable-name">$\left ( a^{2^i} \right )^2$</span> is equal to
<span class="enscript-variable-name">$a^{2^{i+1}}$</span>.  This observation forms the basis of essentially all fast exponentiation algorithms.  It requires <span class="enscript-variable-name">$k$</span> squarings and on average
<span class="enscript-variable-name">$k \over 2$</span> multiplications to compute the result.  This is indeed quite an improvement over simply multiplying by <span class="enscript-variable-name">$a$</span> a total of <span class="enscript-variable-name">$b-1$</span> times.

While this current method is a considerable speed up there are further improvements to be made.  For example, the <span class="enscript-variable-name">$a^{2^i}$</span> term does not need to 
be computed in an auxilary variable.  Consider the following equivalent algorithm.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Left to Right Exponentiation}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Integer <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$k$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = a^b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$c \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
2.  for <span class="enscript-variable-name">$i$</span> from <span class="enscript-variable-name">$k - 1$</span> to <span class="enscript-variable-name">$0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$c \leftarrow c^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  <span class="enscript-variable-name">$c \leftarrow c \cdot a^{b_i}$</span> <span class="enscript-keyword">\\</span>
3.  Return <span class="enscript-variable-name">$c$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Left to Right Exponentiation}
<span class="enscript-keyword">\label</span>{fig:LTOR}
<span class="enscript-keyword">\end</span>{figure}

This algorithm starts from the most significant bit and works towards the least significant bit.  When the <span class="enscript-variable-name">$i$</span>'th bit of <span class="enscript-variable-name">$b$</span> is set <span class="enscript-variable-name">$a$</span> is
multiplied against the current product.  In each iteration the product is squared which doubles the exponent of the individual terms of the
product.  

For example, let <span class="enscript-variable-name">$b = 101100_2 \equiv 44_{10}$</span>.  The following chart demonstrates the actions of the algorithm.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Value of <span class="enscript-variable-name">$i$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Value of <span class="enscript-variable-name">$c$</span>} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> - &amp; <span class="enscript-variable-name">$1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$5$</span> &amp; <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$4$</span> &amp; <span class="enscript-variable-name">$a^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$3$</span> &amp; <span class="enscript-variable-name">$a^4 \cdot a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$2$</span> &amp; <span class="enscript-variable-name">$a^8 \cdot a^2 \cdot a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1$</span> &amp; <span class="enscript-variable-name">$a^{16} \cdot a^4 \cdot a^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$0$</span> &amp; <span class="enscript-variable-name">$a^{32} \cdot a^8 \cdot a^4$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Example of Left to Right Exponentiation}
<span class="enscript-keyword">\end</span>{figure}

When the product <span class="enscript-variable-name">$a^{32} \cdot a^8 \cdot a^4$</span> is simplified it is equal <span class="enscript-variable-name">$a^{44}$</span> which is the desired exponentiation.  This particular algorithm is 
called ``Left to Right'' because it reads the exponent in that order.  All of the exponentiation algorithms that will be presented are of this nature.  

<span class="enscript-keyword">\subsection</span>{Single Digit Exponentiation}
The first algorithm in the series of exponentiation algorithms will be an unbounded algorithm where the exponent is a single digit.  It is intended 
to be used when a small power of an input is required (<span class="enscript-keyword">\textit</span>{e.g. <span class="enscript-variable-name">$a^5$</span>}).  It is faster than simply multiplying <span class="enscript-variable-name">$b - 1$</span> times for all values of 
<span class="enscript-variable-name">$b$</span> that are greater than three.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>expt<span class="enscript-keyword">\_</span>d}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and mp<span class="enscript-keyword">\_</span>digit <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = a^b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$g \leftarrow a$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>init<span class="enscript-keyword">\_</span>copy}) <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$c \leftarrow 1$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>set}) <span class="enscript-keyword">\\</span>
3.  for <span class="enscript-variable-name">$x$</span> from 1 to <span class="enscript-variable-name">$lg(\beta)$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$c \leftarrow c^2$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>sqr}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.2  If <span class="enscript-variable-name">$b$</span> AND <span class="enscript-variable-name">$2^{lg(\beta) - 1} \ne 0$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}3.2.1  <span class="enscript-variable-name">$c \leftarrow c \cdot g$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mul}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.3  <span class="enscript-variable-name">$b \leftarrow b &lt;&lt; 1$</span> <span class="enscript-keyword">\\</span>
4.  Clear <span class="enscript-variable-name">$g$</span>. <span class="enscript-keyword">\\</span>
5.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>expt<span class="enscript-keyword">\_</span>d}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>expt<span class="enscript-keyword">\_</span>d.}
This algorithm computes the value of <span class="enscript-variable-name">$a$</span> raised to the power of a single digit <span class="enscript-variable-name">$b$</span>.  It uses the left to right exponentiation algorithm to
quickly compute the exponentiation.  It is loosely based on algorithm 14.79 of HAC <span class="enscript-keyword">\cite</span>[pp. 615]{HAC} with the difference that the 
exponent is a fixed width.  

A copy of <span class="enscript-variable-name">$a$</span> is made first to allow destination variable <span class="enscript-variable-name">$c$</span> be the same as the source variable <span class="enscript-variable-name">$a$</span>.  The result is set to the initial value of 
<span class="enscript-variable-name">$1$</span> in the subsequent step.

Inside the loop the exponent is read from the most significant bit first down to the least significant bit.  First <span class="enscript-variable-name">$c$</span> is invariably squared
on step 3.1.  In the following step if the most significant bit of <span class="enscript-variable-name">$b$</span> is one the copy of <span class="enscript-variable-name">$a$</span> is multiplied against <span class="enscript-variable-name">$c$</span>.  The value
of <span class="enscript-variable-name">$b$</span> is shifted left one bit to make the next bit down from the most signficant bit the new most significant bit.  In effect each
iteration of the loop moves the bits of the exponent <span class="enscript-variable-name">$b$</span> upwards to the most significant location.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>expt<span class="enscript-keyword">\_</span>d.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Line 29 sets the initial value of the result to <span class="enscript-variable-name">$1$</span>.  Next the loop on line 31 steps through each bit of the exponent starting from
the most significant down towards the least significant. The invariant squaring operation placed on line 33 is performed first.  After 
the squaring the result <span class="enscript-variable-name">$c$</span> is multiplied by the base <span class="enscript-variable-name">$g$</span> if and only if the most significant bit of the exponent is set.  The shift on line
47 moves all of the bits of the exponent upwards towards the most significant location.  

<span class="enscript-keyword">\section</span>{<span class="enscript-variable-name">$k$</span>-ary Exponentiation}
When calculating an exponentiation the most time consuming bottleneck is the multiplications which are in general a small factor
slower than squaring.  Recall from the previous algorithm that <span class="enscript-variable-name">$b_{i}$</span> refers to the <span class="enscript-variable-name">$i$</span>'th bit of the exponent <span class="enscript-variable-name">$b$</span>.  Suppose instead it referred to
the <span class="enscript-variable-name">$i$</span>'th <span class="enscript-variable-name">$k$</span>-bit digit of the exponent of <span class="enscript-variable-name">$b$</span>.  For <span class="enscript-variable-name">$k = 1$</span> the definitions are synonymous and for <span class="enscript-variable-name">$k &gt; 1$</span> algorithm~<span class="enscript-keyword">\ref</span>{fig:KARY}
computes the same exponentiation.  A group of <span class="enscript-variable-name">$k$</span> bits from the exponent is called a <span class="enscript-keyword">\textit</span>{window}.  That is it is a small window on only a
portion of the entire exponent.  Consider the following modification to the basic left to right exponentiation algorithm.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{<span class="enscript-variable-name">$k$</span>-ary Exponentiation}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Integer <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span>, <span class="enscript-variable-name">$k$</span> and <span class="enscript-variable-name">$t$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = a^b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$c \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
2.  for <span class="enscript-variable-name">$i$</span> from <span class="enscript-variable-name">$t - 1$</span> to <span class="enscript-variable-name">$0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$c \leftarrow c^{2^k} $</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  Extract the <span class="enscript-variable-name">$i$</span>'th <span class="enscript-variable-name">$k$</span>-bit word from <span class="enscript-variable-name">$b$</span> and store it in <span class="enscript-variable-name">$g$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.3  <span class="enscript-variable-name">$c \leftarrow c \cdot a^g$</span> <span class="enscript-keyword">\\</span>
3.  Return <span class="enscript-variable-name">$c$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{<span class="enscript-variable-name">$k$</span>-ary Exponentiation}
<span class="enscript-keyword">\label</span>{fig:KARY}
<span class="enscript-keyword">\end</span>{figure}

The squaring on step 2.1 can be calculated by squaring the value <span class="enscript-variable-name">$c$</span> successively <span class="enscript-variable-name">$k$</span> times.  If the values of <span class="enscript-variable-name">$a^g$</span> for <span class="enscript-variable-name">$0 &lt; g &lt; 2^k$</span> have been
precomputed this algorithm requires only <span class="enscript-variable-name">$t$</span> multiplications and <span class="enscript-variable-name">$tk$</span> squarings.  The table can be generated with <span class="enscript-variable-name">$2^{k - 1} - 1$</span> squarings and
<span class="enscript-variable-name">$2^{k - 1} + 1$</span> multiplications.  This algorithm assumes that the number of bits in the exponent is evenly divisible by <span class="enscript-variable-name">$k$</span>.  
However, when it is not the remaining <span class="enscript-variable-name">$0 &lt; x \le k - 1$</span> bits can be handled with algorithm~<span class="enscript-keyword">\ref</span>{fig:LTOR}.

Suppose <span class="enscript-variable-name">$k = 4$</span> and <span class="enscript-variable-name">$t = 100$</span>.  This modified algorithm will require <span class="enscript-variable-name">$109$</span> multiplications and <span class="enscript-variable-name">$408$</span> squarings to compute the exponentiation.  The
original algorithm would on average have required <span class="enscript-variable-name">$200$</span> multiplications and <span class="enscript-variable-name">$400$</span> squrings to compute the same value.  The total number of squarings
has increased slightly but the number of multiplications has nearly halved.

<span class="enscript-keyword">\subsection</span>{Optimal Values of <span class="enscript-variable-name">$k$</span>}
An optimal value of <span class="enscript-variable-name">$k$</span> will minimize <span class="enscript-variable-name">$2^{k} + \lceil n / k \rceil + n - 1$</span> for a fixed number of bits in the exponent <span class="enscript-variable-name">$n$</span>.  The simplest
approach is to brute force search amongst the values <span class="enscript-variable-name">$k = 2, 3, \ldots, 8$</span> for the lowest result.  Table~<span class="enscript-keyword">\ref</span>{fig:OPTK} lists optimal values of <span class="enscript-variable-name">$k$</span>
for various exponent sizes and compares the number of multiplication and squarings required against algorithm~<span class="enscript-keyword">\ref</span>{fig:LTOR}.  

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|c|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Exponent (bits)} &amp; <span class="enscript-keyword">\textbf</span>{Optimal <span class="enscript-variable-name">$k$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Work at <span class="enscript-variable-name">$k$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Work with ~<span class="enscript-keyword">\ref</span>{fig:LTOR}} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$16$</span> &amp; <span class="enscript-variable-name">$2$</span> &amp; <span class="enscript-variable-name">$27$</span> &amp; <span class="enscript-variable-name">$24$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$32$</span> &amp; <span class="enscript-variable-name">$3$</span> &amp; <span class="enscript-variable-name">$49$</span> &amp; <span class="enscript-variable-name">$48$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$64$</span> &amp; <span class="enscript-variable-name">$3$</span> &amp; <span class="enscript-variable-name">$92$</span> &amp; <span class="enscript-variable-name">$96$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$128$</span> &amp; <span class="enscript-variable-name">$4$</span> &amp; <span class="enscript-variable-name">$175$</span> &amp; <span class="enscript-variable-name">$192$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$256$</span> &amp; <span class="enscript-variable-name">$4$</span> &amp; <span class="enscript-variable-name">$335$</span> &amp; <span class="enscript-variable-name">$384$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$512$</span> &amp; <span class="enscript-variable-name">$5$</span> &amp; <span class="enscript-variable-name">$645$</span> &amp; <span class="enscript-variable-name">$768$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1024$</span> &amp; <span class="enscript-variable-name">$6$</span> &amp; <span class="enscript-variable-name">$1257$</span> &amp; <span class="enscript-variable-name">$1536$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$2048$</span> &amp; <span class="enscript-variable-name">$6$</span> &amp; <span class="enscript-variable-name">$2452$</span> &amp; <span class="enscript-variable-name">$3072$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$4096$</span> &amp; <span class="enscript-variable-name">$7$</span> &amp; <span class="enscript-variable-name">$4808$</span> &amp; <span class="enscript-variable-name">$6144$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Optimal Values of <span class="enscript-variable-name">$k$</span> for <span class="enscript-variable-name">$k$</span>-ary Exponentiation}
<span class="enscript-keyword">\label</span>{fig:OPTK}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\subsection</span>{Sliding-Window Exponentiation}
A simple modification to the previous algorithm is only generate the upper half of the table in the range <span class="enscript-variable-name">$2^{k-1} \le g &lt; 2^k$</span>.  Essentially
this is a table for all values of <span class="enscript-variable-name">$g$</span> where the most significant bit of <span class="enscript-variable-name">$g$</span> is a one.  However, in order for this to be allowed in the 
algorithm values of <span class="enscript-variable-name">$g$</span> in the range <span class="enscript-variable-name">$0 \le g &lt; 2^{k-1}$</span> must be avoided.  

Table~<span class="enscript-keyword">\ref</span>{fig:OPTK2} lists optimal values of <span class="enscript-variable-name">$k$</span> for various exponent sizes and compares the work required against algorithm~<span class="enscript-keyword">\ref</span>{fig:KARY}.  

<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|c|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Exponent (bits)} &amp; <span class="enscript-keyword">\textbf</span>{Optimal <span class="enscript-variable-name">$k$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Work at <span class="enscript-variable-name">$k$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Work with ~<span class="enscript-keyword">\ref</span>{fig:KARY}} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$16$</span> &amp; <span class="enscript-variable-name">$3$</span> &amp; <span class="enscript-variable-name">$24$</span> &amp; <span class="enscript-variable-name">$27$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$32$</span> &amp; <span class="enscript-variable-name">$3$</span> &amp; <span class="enscript-variable-name">$45$</span> &amp; <span class="enscript-variable-name">$49$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$64$</span> &amp; <span class="enscript-variable-name">$4$</span> &amp; <span class="enscript-variable-name">$87$</span> &amp; <span class="enscript-variable-name">$92$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$128$</span> &amp; <span class="enscript-variable-name">$4$</span> &amp; <span class="enscript-variable-name">$167$</span> &amp; <span class="enscript-variable-name">$175$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$256$</span> &amp; <span class="enscript-variable-name">$5$</span> &amp; <span class="enscript-variable-name">$322$</span> &amp; <span class="enscript-variable-name">$335$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$512$</span> &amp; <span class="enscript-variable-name">$6$</span> &amp; <span class="enscript-variable-name">$628$</span> &amp; <span class="enscript-variable-name">$645$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1024$</span> &amp; <span class="enscript-variable-name">$6$</span> &amp; <span class="enscript-variable-name">$1225$</span> &amp; <span class="enscript-variable-name">$1257$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$2048$</span> &amp; <span class="enscript-variable-name">$7$</span> &amp; <span class="enscript-variable-name">$2403$</span> &amp; <span class="enscript-variable-name">$2452$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$4096$</span> &amp; <span class="enscript-variable-name">$8$</span> &amp; <span class="enscript-variable-name">$4735$</span> &amp; <span class="enscript-variable-name">$4808$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Optimal Values of <span class="enscript-variable-name">$k$</span> for Sliding Window Exponentiation}
<span class="enscript-keyword">\label</span>{fig:OPTK2}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Sliding Window <span class="enscript-variable-name">$k$</span>-ary Exponentiation}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Integer <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span>, <span class="enscript-variable-name">$k$</span> and <span class="enscript-variable-name">$t$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = a^b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$c \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
2.  for <span class="enscript-variable-name">$i$</span> from <span class="enscript-variable-name">$t - 1$</span> to <span class="enscript-variable-name">$0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  If the <span class="enscript-variable-name">$i$</span>'th bit of <span class="enscript-variable-name">$b$</span> is a zero then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.1.1   <span class="enscript-variable-name">$c \leftarrow c^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  else do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.2.1  <span class="enscript-variable-name">$c \leftarrow c^{2^k}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.2.2  Extract the <span class="enscript-variable-name">$k$</span> bits from <span class="enscript-variable-name">$(b_{i}b_{i-1}\ldots b_{i-(k-1)})$</span> and store it in <span class="enscript-variable-name">$g$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.2.3  <span class="enscript-variable-name">$c \leftarrow c \cdot a^g$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}2.2.4  <span class="enscript-variable-name">$i \leftarrow i - k$</span> <span class="enscript-keyword">\\</span>
3.  Return <span class="enscript-variable-name">$c$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Sliding Window <span class="enscript-variable-name">$k$</span>-ary Exponentiation}
<span class="enscript-keyword">\end</span>{figure}

Similar to the previous algorithm this algorithm must have a special handler when fewer than <span class="enscript-variable-name">$k$</span> bits are left in the exponent.  While this
algorithm requires the same number of squarings it can potentially have fewer multiplications.  The pre-computed table <span class="enscript-variable-name">$a^g$</span> is also half
the size as the previous table.  

Consider the exponent <span class="enscript-variable-name">$b = 111101011001000_2 \equiv 31432_{10}$</span> with <span class="enscript-variable-name">$k = 3$</span> using both algorithms.  The first algorithm will divide the exponent up as 
the following five <span class="enscript-variable-name">$3$</span>-bit words <span class="enscript-variable-name">$b \equiv \left ( 111, 101, 011, 001, 000 \right )_{2}$</span>.  The second algorithm will break the 
exponent as <span class="enscript-variable-name">$b \equiv \left ( 111, 101, 0, 110, 0, 100, 0 \right )_{2}$</span>.  The single digit <span class="enscript-variable-name">$0$</span> in the second representation are where
a single squaring took place instead of a squaring and multiplication.  In total the first method requires <span class="enscript-variable-name">$10$</span> multiplications and <span class="enscript-variable-name">$18$</span> 
squarings.  The second method requires <span class="enscript-variable-name">$8$</span> multiplications and <span class="enscript-variable-name">$18$</span> squarings.  

In general the sliding window method is never slower than the generic <span class="enscript-variable-name">$k$</span>-ary method and often it is slightly faster.  

<span class="enscript-keyword">\section</span>{Modular Exponentiation}

Modular exponentiation is essentially computing the power of a base within a finite field or ring.  For example, computing 
<span class="enscript-variable-name">$d \equiv a^b \mbox{ (mod }c\mbox{)}$</span> is a modular exponentiation.  Instead of first computing <span class="enscript-variable-name">$a^b$</span> and then reducing it 
modulo <span class="enscript-variable-name">$c$</span> the intermediate result is reduced modulo <span class="enscript-variable-name">$c$</span> after every squaring or multiplication operation.  

This guarantees that any intermediate result is bounded by <span class="enscript-variable-name">$0 \le d \le c^2 - 2c + 1$</span> and can be reduced modulo <span class="enscript-variable-name">$c$</span> quickly using
one of the algorithms presented in chapter six.  

Before the actual modular exponentiation algorithm can be written a wrapper algorithm must be written first.  This algorithm
will allow the exponent <span class="enscript-variable-name">$b$</span> to be negative which is computed as <span class="enscript-variable-name">$c \equiv \left (1 / a \right )^{\vert b \vert} \mbox{(mod }d\mbox{)}$</span>. The
value of <span class="enscript-variable-name">$(1/a) \mbox{ mod }c$</span> is computed using the modular inverse (<span class="enscript-keyword">\textit</span>{see <span class="enscript-keyword">\ref</span>{sec;modinv}}).  If no inverse exists the algorithm
terminates with an error.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>exptmod}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$c$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$y \equiv g^x \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$c.sign = MP\_NEG$</span> return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$b.sign = MP\_NEG$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$g' \leftarrow g^{-1} \mbox{ (mod }c\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  <span class="enscript-variable-name">$x' \leftarrow \vert x \vert$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.3  Compute <span class="enscript-variable-name">$d \equiv g'^{x'} \mbox{ (mod }c\mbox{)}$</span> via recursion. <span class="enscript-keyword">\\</span>
3.  if <span class="enscript-variable-name">$p$</span> is odd <span class="enscript-keyword">\textbf</span>{OR} <span class="enscript-variable-name">$p$</span> is a D.R. modulus then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  Compute <span class="enscript-variable-name">$y \equiv g^{x} \mbox{ (mod }p\mbox{)}$</span> via algorithm mp<span class="enscript-keyword">\_</span>exptmod<span class="enscript-keyword">\_</span>fast. <span class="enscript-keyword">\\</span>
4.  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  Compute <span class="enscript-variable-name">$y \equiv g^{x} \mbox{ (mod }p\mbox{)}$</span> via algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>exptmod}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>exptmod.}
The first algorithm which actually performs modular exponentiation is algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod.  It is a sliding window <span class="enscript-variable-name">$k$</span>-ary algorithm 
which uses Barrett reduction to reduce the product modulo <span class="enscript-variable-name">$p$</span>.  The second algorithm mp<span class="enscript-keyword">\_</span>exptmod<span class="enscript-keyword">\_</span>fast performs the same operation 
except it uses either Montgomery or Diminished Radix reduction.  The two latter reduction algorithms are clumped in the same exponentiation
algorithm since their arguments are essentially the same (<span class="enscript-keyword">\textit</span>{two mp<span class="enscript-keyword">\_</span>ints and one mp<span class="enscript-keyword">\_</span>digit}).  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

In order to keep the algorithms in a known state the first step on line 29 is to reject any negative modulus as input.  If the exponent is
negative the algorithm tries to perform a modular exponentiation with the modular inverse of the base <span class="enscript-variable-name">$G$</span>.  The temporary variable <span class="enscript-variable-name">$tmpG$</span> is assigned
the modular inverse of <span class="enscript-variable-name">$G$</span> and <span class="enscript-variable-name">$tmpX$</span> is assigned the absolute value of <span class="enscript-variable-name">$X$</span>.  The algorithm will recuse with these new values with a positive
exponent.

If the exponent is positive the algorithm resumes the exponentiation.  Line 77 determines if the modulus is of the restricted Diminished Radix 
form.  If it is not line 70 attempts to determine if it is of a unrestricted Diminished Radix form.  The integer <span class="enscript-variable-name">$dr$</span> will take on one
of three values.

<span class="enscript-keyword">\begin</span>{enumerate}
<span class="enscript-keyword">\item</span> <span class="enscript-variable-name">$dr = 0$</span> means that the modulus is not of either restricted or unrestricted Diminished Radix form.
<span class="enscript-keyword">\item</span> <span class="enscript-variable-name">$dr = 1$</span> means that the modulus is of restricted Diminished Radix form.
<span class="enscript-keyword">\item</span> <span class="enscript-variable-name">$dr = 2$</span> means that the modulus is of unrestricted Diminished Radix form.
<span class="enscript-keyword">\end</span>{enumerate}

Line 69 determines if the fast modular exponentiation algorithm can be used.  It is allowed if <span class="enscript-variable-name">$dr \ne 0$</span> or if the modulus is odd.  Otherwise,
the slower s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod algorithm is used which uses Barrett reduction.  

<span class="enscript-keyword">\subsection</span>{Barrett Modular Exponentiation}

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$c$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$y \equiv g^x \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$k \leftarrow lg(x)$</span> <span class="enscript-keyword">\\</span>
2.  $winsize <span class="enscript-keyword">\leftarrow</span>  <span class="enscript-keyword">\left</span> <span class="enscript-keyword">\lbrace</span> <span class="enscript-keyword">\begin</span>{array}{ll}
                              2 &amp;  <span class="enscript-keyword">\mbox</span>{if }k <span class="enscript-keyword">\le</span> 7 <span class="enscript-keyword">\\</span>
                              3 &amp;  <span class="enscript-keyword">\mbox</span>{if }7 &lt; k <span class="enscript-keyword">\le</span> 36 <span class="enscript-keyword">\\</span>
                              4 &amp;  <span class="enscript-keyword">\mbox</span>{if }36 &lt; k <span class="enscript-keyword">\le</span> 140 <span class="enscript-keyword">\\</span>
                              5 &amp;  <span class="enscript-keyword">\mbox</span>{if }140 &lt; k <span class="enscript-keyword">\le</span> 450 <span class="enscript-keyword">\\</span>
                              6 &amp;  <span class="enscript-keyword">\mbox</span>{if }450 &lt; k <span class="enscript-keyword">\le</span> 1303 <span class="enscript-keyword">\\</span>
                              7 &amp;  <span class="enscript-keyword">\mbox</span>{if }1303 &lt; k <span class="enscript-keyword">\le</span> 3529 <span class="enscript-keyword">\\</span>
                              8 &amp;  <span class="enscript-keyword">\mbox</span>{if }3529 &lt; k <span class="enscript-keyword">\\</span>
                              <span class="enscript-keyword">\end</span>{array} <span class="enscript-keyword">\right</span> .$ <span class="enscript-keyword">\\</span>
3.  Initialize <span class="enscript-variable-name">$2^{winsize}$</span> mp<span class="enscript-keyword">\_</span>ints in an array named <span class="enscript-variable-name">$M$</span> and one mp<span class="enscript-keyword">\_</span>int named <span class="enscript-variable-name">$\mu$</span> <span class="enscript-keyword">\\</span>
4.  Calculate the <span class="enscript-variable-name">$\mu$</span> required for Barrett Reduction (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>reduce<span class="enscript-keyword">\_</span>setup}). <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$M_1 \leftarrow g \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Setup the table of small powers of <span class="enscript-variable-name">$g$</span>.  First find <span class="enscript-variable-name">$g^{2^{winsize}}$</span> and then all multiples of it. <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$k \leftarrow 2^{winsize - 1}$</span> <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$M_{k} \leftarrow M_1$</span> <span class="enscript-keyword">\\</span>
8.  for <span class="enscript-variable-name">$ix$</span> from 0 to <span class="enscript-variable-name">$winsize - 2$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  <span class="enscript-variable-name">$M_k \leftarrow \left ( M_k \right )^2$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>sqr})  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.2  <span class="enscript-variable-name">$M_k \leftarrow M_k \mbox{ (mod }p\mbox{)}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>reduce}) <span class="enscript-keyword">\\</span>
9.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$2^{winsize - 1} + 1$</span> to <span class="enscript-variable-name">$2^{winsize} - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.1  <span class="enscript-variable-name">$M_{ix} \leftarrow M_{ix - 1} \cdot M_{1}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>mul}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.2  <span class="enscript-variable-name">$M_{ix} \leftarrow M_{ix} \mbox{ (mod }p\mbox{)}$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>reduce}) <span class="enscript-keyword">\\</span>
10.  <span class="enscript-variable-name">$res \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Start Sliding Window. <span class="enscript-keyword">\\</span>
11.  <span class="enscript-variable-name">$mode \leftarrow 0, bitcnt \leftarrow 1, buf \leftarrow 0, digidx \leftarrow x.used - 1, bitcpy \leftarrow 0, bitbuf \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
12.  Loop <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.1  <span class="enscript-variable-name">$bitcnt \leftarrow bitcnt - 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.2  If <span class="enscript-variable-name">$bitcnt = 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.2.1  If <span class="enscript-variable-name">$digidx = -1$</span> goto step 13. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.2.2  <span class="enscript-variable-name">$buf \leftarrow x_{digidx}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.2.3  <span class="enscript-variable-name">$digidx \leftarrow digidx - 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.2.4  <span class="enscript-variable-name">$bitcnt \leftarrow lg(\beta)$</span> <span class="enscript-keyword">\\</span>
Continued on next page. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod} (<span class="enscript-keyword">\textit</span>{continued}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span> and <span class="enscript-variable-name">$c$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$y \equiv g^x \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.3  <span class="enscript-variable-name">$y \leftarrow (buf &gt;&gt; (lg(\beta) - 1))$</span> AND <span class="enscript-variable-name">$1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.4  <span class="enscript-variable-name">$buf \leftarrow buf &lt;&lt; 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.5  if <span class="enscript-variable-name">$mode = 0$</span> and <span class="enscript-variable-name">$y = 0$</span> then goto step 12. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.6  if <span class="enscript-variable-name">$mode = 1$</span> and <span class="enscript-variable-name">$y = 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.6.1  <span class="enscript-variable-name">$res \leftarrow res^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.6.2  <span class="enscript-variable-name">$res \leftarrow res \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.6.3  Goto step 12. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.7  <span class="enscript-variable-name">$bitcpy \leftarrow bitcpy + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.8  <span class="enscript-variable-name">$bitbuf \leftarrow bitbuf + (y &lt;&lt; (winsize - bitcpy))$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.9  <span class="enscript-variable-name">$mode \leftarrow 2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.10  If <span class="enscript-variable-name">$bitcpy = winsize$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}Window is full so perform the squarings and single multiplication. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.10.1  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$winsize -1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{9mm}12.10.1.1  <span class="enscript-variable-name">$res \leftarrow res^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{9mm}12.10.1.2  <span class="enscript-variable-name">$res \leftarrow res \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.10.2  <span class="enscript-variable-name">$res \leftarrow res \cdot M_{bitbuf}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.10.3  <span class="enscript-variable-name">$res \leftarrow res \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}Reset the window. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}12.10.4  <span class="enscript-variable-name">$bitcpy \leftarrow 0, bitbuf \leftarrow 0, mode \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
No more windows left.  Check for residual bits of exponent. <span class="enscript-keyword">\\</span>
13.  If <span class="enscript-variable-name">$mode = 2$</span> and <span class="enscript-variable-name">$bitcpy &gt; 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.1  for <span class="enscript-variable-name">$ix$</span> form <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$bitcpy - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.1.1  <span class="enscript-variable-name">$res \leftarrow res^2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.1.2  <span class="enscript-variable-name">$res \leftarrow res \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.1.3  <span class="enscript-variable-name">$bitbuf \leftarrow bitbuf &lt;&lt; 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.1.4  If <span class="enscript-variable-name">$bitbuf$</span> AND <span class="enscript-variable-name">$2^{winsize} \ne 0$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{9mm}13.1.4.1  <span class="enscript-variable-name">$res \leftarrow res \cdot M_{1}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{9mm}13.1.4.2  <span class="enscript-variable-name">$res \leftarrow res \mbox{ (mod }p\mbox{)}$</span> <span class="enscript-keyword">\\</span>
14.  <span class="enscript-variable-name">$y \leftarrow res$</span> <span class="enscript-keyword">\\</span>
15.  Clear <span class="enscript-variable-name">$res$</span>, <span class="enscript-variable-name">$mu$</span> and the <span class="enscript-variable-name">$M$</span> array. <span class="enscript-keyword">\\</span>
16.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod (continued)}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod.}
This algorithm computes the <span class="enscript-variable-name">$x$</span>'th power of <span class="enscript-variable-name">$g$</span> modulo <span class="enscript-variable-name">$p$</span> and stores the result in <span class="enscript-variable-name">$y$</span>.  It takes advantage of the Barrett reduction
algorithm to keep the product small throughout the algorithm.

The first two steps determine the optimal window size based on the number of bits in the exponent.  The larger the exponent the 
larger the window size becomes.  After a window size <span class="enscript-variable-name">$winsize$</span> has been chosen an array of <span class="enscript-variable-name">$2^{winsize}$</span> mp<span class="enscript-keyword">\_</span>int variables is allocated.  This
table will hold the values of <span class="enscript-variable-name">$g^x \mbox{ (mod }p\mbox{)}$</span> for <span class="enscript-variable-name">$2^{winsize - 1} \le x &lt; 2^{winsize}$</span>.  

After the table is allocated the first power of <span class="enscript-variable-name">$g$</span> is found.  Since <span class="enscript-variable-name">$g \ge p$</span> is allowed it must be first reduced modulo <span class="enscript-variable-name">$p$</span> to make
the rest of the algorithm more efficient.  The first element of the table at <span class="enscript-variable-name">$2^{winsize - 1}$</span> is found by squaring <span class="enscript-variable-name">$M_1$</span> successively <span class="enscript-variable-name">$winsize - 2$</span>
times.  The rest of the table elements are found by multiplying the previous element by <span class="enscript-variable-name">$M_1$</span> modulo <span class="enscript-variable-name">$p$</span>.

Now that the table is available the sliding window may begin.  The following list describes the functions of all the variables in the window.
<span class="enscript-keyword">\begin</span>{enumerate}
<span class="enscript-keyword">\item</span> The variable <span class="enscript-variable-name">$mode$</span> dictates how the bits of the exponent are interpreted.  
<span class="enscript-keyword">\begin</span>{enumerate}
   <span class="enscript-keyword">\item</span> When <span class="enscript-variable-name">$mode = 0$</span> the bits are ignored since no non-zero bit of the exponent has been seen yet.  For example, if the exponent were simply 
         <span class="enscript-variable-name">$1$</span> then there would be <span class="enscript-variable-name">$lg(\beta) - 1$</span> zero bits before the first non-zero bit.  In this case bits are ignored until a non-zero bit is found.  
   <span class="enscript-keyword">\item</span> When <span class="enscript-variable-name">$mode = 1$</span> a non-zero bit has been seen before and a new <span class="enscript-variable-name">$winsize$</span>-bit window has not been formed yet.  In this mode leading <span class="enscript-variable-name">$0$</span> bits 
         are read and a single squaring is performed.  If a non-zero bit is read a new window is created.  
   <span class="enscript-keyword">\item</span> When <span class="enscript-variable-name">$mode = 2$</span> the algorithm is in the middle of forming a window and new bits are appended to the window from the most significant bit
         downwards.
<span class="enscript-keyword">\end</span>{enumerate}
<span class="enscript-keyword">\item</span> The variable <span class="enscript-variable-name">$bitcnt$</span> indicates how many bits are left in the current digit of the exponent left to be read.  When it reaches zero a new digit
      is fetched from the exponent.
<span class="enscript-keyword">\item</span> The variable <span class="enscript-variable-name">$buf$</span> holds the currently read digit of the exponent. 
<span class="enscript-keyword">\item</span> The variable <span class="enscript-variable-name">$digidx$</span> is an index into the exponents digits.  It starts at the leading digit <span class="enscript-variable-name">$x.used - 1$</span> and moves towards the trailing digit.
<span class="enscript-keyword">\item</span> The variable <span class="enscript-variable-name">$bitcpy$</span> indicates how many bits are in the currently formed window.  When it reaches <span class="enscript-variable-name">$winsize$</span> the window is flushed and
      the appropriate operations performed.
<span class="enscript-keyword">\item</span> The variable <span class="enscript-variable-name">$bitbuf$</span> holds the current bits of the window being formed.  
<span class="enscript-keyword">\end</span>{enumerate}

All of step 12 is the window processing loop.  It will iterate while there are digits available form the exponent to read.  The first step
inside this loop is to extract a new digit if no more bits are available in the current digit.  If there are no bits left a new digit is
read and if there are no digits left than the loop terminates.  

After a digit is made available step 12.3 will extract the most significant bit of the current digit and move all other bits in the digit
upwards.  In effect the digit is read from most significant bit to least significant bit and since the digits are read from leading to 
trailing edges the entire exponent is read from most significant bit to least significant bit.

At step 12.5 if the <span class="enscript-variable-name">$mode$</span> and currently extracted bit <span class="enscript-variable-name">$y$</span> are both zero the bit is ignored and the next bit is read.  This prevents the 
algorithm from having to perform trivial squaring and reduction operations before the first non-zero bit is read.  Step 12.6 and 12.7-10 handle
the two cases of <span class="enscript-variable-name">$mode = 1$</span> and <span class="enscript-variable-name">$mode = 2$</span> respectively.  

<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\includegraphics</span>{pics/expt_state.ps}
<span class="enscript-keyword">\caption</span>{Sliding Window State Diagram}
<span class="enscript-keyword">\label</span>{pic:expt_state}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\end</span>{center}

By step 13 there are no more digits left in the exponent.  However, there may be partial bits in the window left.  If <span class="enscript-variable-name">$mode = 2$</span> then 
a Left-to-Right algorithm is used to process the remaining few bits.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>exptmod.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Lines 32 through 46 determine the optimal window size based on the length of the exponent in bits.  The window divisions are sorted
from smallest to greatest so that in each <span class="enscript-keyword">\textbf</span>{if} statement only one condition must be tested.  For example, by the <span class="enscript-keyword">\textbf</span>{if} statement 
on line 38 the value of <span class="enscript-variable-name">$x$</span> is already known to be greater than <span class="enscript-variable-name">$140$</span>.  

The conditional piece of code beginning on line 48 allows the window size to be restricted to five bits.  This logic is used to ensure
the table of precomputed powers of <span class="enscript-variable-name">$G$</span> remains relatively small.  

The for loop on line 61 initializes the <span class="enscript-variable-name">$M$</span> array while lines 72 and 77 through 86 initialize the reduction
function that will be used for this modulus.

-- More later.

<span class="enscript-keyword">\section</span>{Quick Power of Two}
Calculating <span class="enscript-variable-name">$b = 2^a$</span> can be performed much quicker than with any of the previous algorithms.  Recall that a logical shift left <span class="enscript-variable-name">$m &lt;&lt; k$</span> is
equivalent to <span class="enscript-variable-name">$m \cdot 2^k$</span>.  By this logic when <span class="enscript-variable-name">$m = 1$</span> a quick power of two can be achieved.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>2expt}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   integer <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$a \leftarrow 2^b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$a \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$a.alloc &lt; \lfloor b / lg(\beta) \rfloor + 1$</span> then grow <span class="enscript-variable-name">$a$</span> appropriately. <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$a.used \leftarrow \lfloor b / lg(\beta) \rfloor + 1$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$a_{\lfloor b / lg(\beta) \rfloor} \leftarrow 1 &lt;&lt; (b \mbox{ mod } lg(\beta))$</span> <span class="enscript-keyword">\\</span>
5.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>2expt}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>2expt.}

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>2expt.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\chapter</span>{Higher Level Algorithms}

This chapter discusses the various higher level algorithms that are required to complete a well rounded multiple precision integer package.  These
routines are less performance oriented than the algorithms of chapters five, six and seven but are no less important.  

The first section describes a method of integer division with remainder that is universally well known.  It provides the signed division logic
for the package.  The subsequent section discusses a set of algorithms which allow a single digit to be the 2nd operand for a variety of operations.  
These algorithms serve mostly to simplify other algorithms where small constants are required.  The last two sections discuss how to manipulate 
various representations of integers.  For example, converting from an mp<span class="enscript-keyword">\_</span>int to a string of character.

<span class="enscript-keyword">\section</span>{Integer Division with Remainder}
<span class="enscript-keyword">\label</span>{sec:division}

Integer division aside from modular exponentiation is the most intensive algorithm to compute.  Like addition, subtraction and multiplication
the basis of this algorithm is the long-hand division algorithm taught to school children.  Throughout this discussion several common variables
will be used.  Let <span class="enscript-variable-name">$x$</span> represent the divisor and <span class="enscript-variable-name">$y$</span> represent the dividend.  Let <span class="enscript-variable-name">$q$</span> represent the integer quotient <span class="enscript-variable-name">$\lfloor y / x \rfloor$</span> and 
let <span class="enscript-variable-name">$r$</span> represent the remainder <span class="enscript-variable-name">$r = y - x \lfloor y / x \rfloor$</span>.  The following simple algorithm will be used to start the discussion.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Radix-<span class="enscript-variable-name">$\beta$</span> Integer Division}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   integer <span class="enscript-variable-name">$x$</span> and <span class="enscript-variable-name">$y$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$q = \lfloor y/x\rfloor, r = y - xq$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$q \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$n \leftarrow \vert \vert y \vert \vert - \vert \vert x \vert \vert$</span> <span class="enscript-keyword">\\</span>
3.  for <span class="enscript-variable-name">$t$</span> from <span class="enscript-variable-name">$n$</span> down to <span class="enscript-variable-name">$0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  Maximize <span class="enscript-variable-name">$k$</span> such that <span class="enscript-variable-name">$kx\beta^t$</span> is less than or equal to <span class="enscript-variable-name">$y$</span> and <span class="enscript-variable-name">$(k + 1)x\beta^t$</span> is greater. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.2  <span class="enscript-variable-name">$q \leftarrow q + k\beta^t$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.3  <span class="enscript-variable-name">$y \leftarrow y - kx\beta^t$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$r \leftarrow y$</span> <span class="enscript-keyword">\\</span>
5.  Return(<span class="enscript-variable-name">$q, r$</span>) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Radix-<span class="enscript-variable-name">$\beta$</span> Integer Division}
<span class="enscript-keyword">\label</span>{fig:raddiv}
<span class="enscript-keyword">\end</span>{figure}

As children we are taught this very simple algorithm for the case of <span class="enscript-variable-name">$\beta = 10$</span>.  Almost instinctively several optimizations are taught for which
their reason of existing are never explained.  For this example let <span class="enscript-variable-name">$y = 5471$</span> represent the dividend and <span class="enscript-variable-name">$x = 23$</span> represent the divisor.

To find the first digit of the quotient the value of <span class="enscript-variable-name">$k$</span> must be maximized such that <span class="enscript-variable-name">$kx\beta^t$</span> is less than or equal to <span class="enscript-variable-name">$y$</span> and 
simultaneously <span class="enscript-variable-name">$(k + 1)x\beta^t$</span> is greater than <span class="enscript-variable-name">$y$</span>.  Implicitly <span class="enscript-variable-name">$k$</span> is the maximum value the <span class="enscript-variable-name">$t$</span>'th digit of the quotient may have.  The habitual method
used to find the maximum is to ``eyeball'' the two numbers, typically only the leading digits and quickly estimate a quotient.  By only using leading
digits a much simpler division may be used to form an educated guess at what the value must be.  In this case <span class="enscript-variable-name">$k = \lfloor 54/23\rfloor = 2$</span> quickly 
arises as a possible  solution.  Indeed <span class="enscript-variable-name">$2x\beta^2 = 4600$</span> is less than <span class="enscript-variable-name">$y = 5471$</span> and simultaneously <span class="enscript-variable-name">$(k + 1)x\beta^2 = 6900$</span> is larger than <span class="enscript-variable-name">$y$</span>.  
As a  result <span class="enscript-variable-name">$k\beta^2$</span> is added to the quotient which now equals <span class="enscript-variable-name">$q = 200$</span> and <span class="enscript-variable-name">$4600$</span> is subtracted from <span class="enscript-variable-name">$y$</span> to give a remainder of <span class="enscript-variable-name">$y = 841$</span>.

Again this process is repeated to produce the quotient digit <span class="enscript-variable-name">$k = 3$</span> which makes the quotient <span class="enscript-variable-name">$q = 200 + 3\beta = 230$</span> and the remainder 
<span class="enscript-variable-name">$y = 841 - 3x\beta = 181$</span>.  Finally the last iteration of the loop produces <span class="enscript-variable-name">$k = 7$</span> which leads to the quotient <span class="enscript-variable-name">$q = 230 + 7 = 237$</span> and the
remainder <span class="enscript-variable-name">$y = 181 - 7x = 20$</span>.  The final quotient and remainder found are <span class="enscript-variable-name">$q = 237$</span> and <span class="enscript-variable-name">$r = y = 20$</span> which are indeed correct since 
<span class="enscript-variable-name">$237 \cdot 23 + 20 = 5471$</span> is true.  

<span class="enscript-keyword">\subsection</span>{Quotient Estimation}
<span class="enscript-keyword">\label</span>{sec:divest}
As alluded to earlier the quotient digit <span class="enscript-variable-name">$k$</span> can be estimated from only the leading digits of both the divisor and dividend.  When <span class="enscript-variable-name">$p$</span> leading
digits are used from both the divisor and dividend to form an estimation the accuracy of the estimation rises as <span class="enscript-variable-name">$p$</span> grows.  Technically
speaking the estimation is based on assuming the lower <span class="enscript-variable-name">$\vert \vert y \vert \vert - p$</span> and <span class="enscript-variable-name">$\vert \vert x \vert \vert - p$</span> lower digits of the
dividend and divisor are zero.  

The value of the estimation may off by a few values in either direction and in general is fairly correct.  A simplification <span class="enscript-keyword">\cite</span>[pp. 271]{TAOCPV2}
of the estimation technique is to use <span class="enscript-variable-name">$t + 1$</span> digits of the dividend and <span class="enscript-variable-name">$t$</span> digits of the divisor, in particularly when <span class="enscript-variable-name">$t = 1$</span>.  The estimate 
using this technique is never too small.  For the following proof let <span class="enscript-variable-name">$t = \vert \vert y \vert \vert - 1$</span> and <span class="enscript-variable-name">$s = \vert \vert x \vert \vert - 1$</span> 
represent the most significant digits of the dividend and divisor respectively.

<span class="enscript-keyword">\textbf</span>{Proof.}<span class="enscript-keyword">\textit</span>{  The quotient <span class="enscript-variable-name">$\hat k = \lfloor (y_t\beta + y_{t-1}) / x_s \rfloor$</span> is greater than or equal to 
<span class="enscript-variable-name">$k = \lfloor y / (x \cdot \beta^{\vert \vert y \vert \vert - \vert \vert x \vert \vert - 1}) \rfloor$</span>. }
The first obvious case is when <span class="enscript-variable-name">$\hat k = \beta - 1$</span> in which case the proof is concluded since the real quotient cannot be larger.  For all other 
cases <span class="enscript-variable-name">$\hat k = \lfloor (y_t\beta + y_{t-1}) / x_s \rfloor$</span> and <span class="enscript-variable-name">$\hat k x_s \ge y_t\beta + y_{t-1} - x_s + 1$</span>.  The latter portion of the inequalility
<span class="enscript-variable-name">$-x_s + 1$</span> arises from the fact that a truncated integer division will give the same quotient for at most <span class="enscript-variable-name">$x_s - 1$</span> values.  Next a series of 
inequalities will prove the hypothesis.

<span class="enscript-keyword">\begin</span>{equation}
y - <span class="enscript-keyword">\hat</span> k x <span class="enscript-keyword">\le</span> y - <span class="enscript-keyword">\hat</span> k x_s<span class="enscript-keyword">\beta</span>^s
<span class="enscript-keyword">\end</span>{equation}

This is trivially true since <span class="enscript-variable-name">$x \ge x_s\beta^s$</span>.  Next we replace <span class="enscript-variable-name">$\hat kx_s\beta^s$</span> by the previous inequality for <span class="enscript-variable-name">$\hat kx_s$</span>.  

<span class="enscript-keyword">\begin</span>{equation}
y - <span class="enscript-keyword">\hat</span> k x <span class="enscript-keyword">\le</span> y_t<span class="enscript-keyword">\beta</span>^t + <span class="enscript-keyword">\ldots</span> + y_0 - (y_t<span class="enscript-keyword">\beta</span>^t + y_{t-1}<span class="enscript-keyword">\beta</span>^{t-1} - x_s<span class="enscript-keyword">\beta</span>^t + <span class="enscript-keyword">\beta</span>^s)
<span class="enscript-keyword">\end</span>{equation}

By simplifying the previous inequality the following inequality is formed.

<span class="enscript-keyword">\begin</span>{equation}
y - <span class="enscript-keyword">\hat</span> k x <span class="enscript-keyword">\le</span> y_{t-2}<span class="enscript-keyword">\beta</span>^{t-2} + <span class="enscript-keyword">\ldots</span> + y_0 + x_s<span class="enscript-keyword">\beta</span>^s - <span class="enscript-keyword">\beta</span>^s
<span class="enscript-keyword">\end</span>{equation}

Subsequently,

<span class="enscript-keyword">\begin</span>{equation}
y_{t-2}<span class="enscript-keyword">\beta</span>^{t-2} + <span class="enscript-keyword">\ldots</span> +  y_0  + x_s<span class="enscript-keyword">\beta</span>^s - <span class="enscript-keyword">\beta</span>^s &lt; x_s<span class="enscript-keyword">\beta</span>^s <span class="enscript-keyword">\le</span> x
<span class="enscript-keyword">\end</span>{equation}

Which proves that <span class="enscript-variable-name">$y - \hat kx \le x$</span> and by consequence <span class="enscript-variable-name">$\hat k \ge k$</span> which concludes the proof.  <span class="enscript-keyword">\textbf</span>{QED}


<span class="enscript-keyword">\subsection</span>{Normalized Integers}
For the purposes of division a normalized input is when the divisors leading digit <span class="enscript-variable-name">$x_n$</span> is greater than or equal to <span class="enscript-variable-name">$\beta / 2$</span>.  By multiplying both
<span class="enscript-variable-name">$x$</span> and <span class="enscript-variable-name">$y$</span> by <span class="enscript-variable-name">$j = \lfloor (\beta / 2) / x_n \rfloor$</span> the quotient remains unchanged and the remainder is simply <span class="enscript-variable-name">$j$</span> times the original
remainder.  The purpose of normalization is to ensure the leading digit of the divisor is sufficiently large such that the estimated quotient will
lie in the domain of a single digit.  Consider the maximum dividend <span class="enscript-variable-name">$(\beta - 1) \cdot \beta + (\beta - 1)$</span> and the minimum divisor <span class="enscript-variable-name">$\beta / 2$</span>.  

<span class="enscript-keyword">\begin</span>{equation} 
{{<span class="enscript-keyword">\beta</span>^2 - 1} <span class="enscript-keyword">\over</span> { <span class="enscript-keyword">\beta</span> / 2}} <span class="enscript-keyword">\le</span> 2<span class="enscript-keyword">\beta</span> - {2 <span class="enscript-keyword">\over</span> <span class="enscript-keyword">\beta</span>} 
<span class="enscript-keyword">\end</span>{equation}

At most the quotient approaches <span class="enscript-variable-name">$2\beta$</span>, however, in practice this will not occur since that would imply the previous quotient digit was too small.  

<span class="enscript-keyword">\subsection</span>{Radix-<span class="enscript-variable-name">$\beta$</span> Division with Remainder}
<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>div}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a, b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = \lfloor a/b \rfloor$</span>, <span class="enscript-variable-name">$d = a - bc$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b = 0$</span> return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$\vert a \vert &lt; \vert b \vert$</span> then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$d \leftarrow a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  <span class="enscript-variable-name">$c \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.3  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Setup the quotient to receive the digits. <span class="enscript-keyword">\\</span>
3.  Grow <span class="enscript-variable-name">$q$</span> to <span class="enscript-variable-name">$a.used + 2$</span> digits. <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$q \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$x \leftarrow \vert a \vert , y \leftarrow \vert b \vert$</span> <span class="enscript-keyword">\\</span>
6.  $sign <span class="enscript-keyword">\leftarrow</span>  <span class="enscript-keyword">\left</span> <span class="enscript-keyword">\lbrace</span> <span class="enscript-keyword">\begin</span>{array}{ll}
                              MP<span class="enscript-keyword">\_</span>ZPOS &amp;  <span class="enscript-keyword">\mbox</span>{if }a.sign = b.sign <span class="enscript-keyword">\\</span>
                              MP<span class="enscript-keyword">\_</span>NEG  &amp;  <span class="enscript-keyword">\mbox</span>{otherwise} <span class="enscript-keyword">\\</span>
                              <span class="enscript-keyword">\end</span>{array} <span class="enscript-keyword">\right</span> .$ <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Normalize the inputs such that the leading digit of <span class="enscript-variable-name">$y$</span> is greater than or equal to <span class="enscript-variable-name">$\beta / 2$</span>. <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$norm \leftarrow (lg(\beta) - 1) - (\lceil lg(y) \rceil \mbox{ (mod }lg(\beta)\mbox{)})$</span> <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$x \leftarrow x \cdot 2^{norm}, y \leftarrow y \cdot 2^{norm}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Find the leading digit of the quotient. <span class="enscript-keyword">\\</span>
9.  <span class="enscript-variable-name">$n \leftarrow x.used - 1, t \leftarrow y.used - 1$</span> <span class="enscript-keyword">\\</span>
10.  <span class="enscript-variable-name">$y \leftarrow y \cdot \beta^{n - t}$</span> <span class="enscript-keyword">\\</span>
11.  While (<span class="enscript-variable-name">$x \ge y$</span>) do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}11.1  <span class="enscript-variable-name">$q_{n - t} \leftarrow q_{n - t} + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}11.2  <span class="enscript-variable-name">$x \leftarrow x - y$</span> <span class="enscript-keyword">\\</span>
12.  <span class="enscript-variable-name">$y \leftarrow \lfloor y / \beta^{n-t} \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Continued on the next page. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>div}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>div} (continued). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a, b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = \lfloor a/b \rfloor$</span>, <span class="enscript-variable-name">$d = a - bc$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
Now find the remainder fo the digits. <span class="enscript-keyword">\\</span>
13.  for <span class="enscript-variable-name">$i$</span> from <span class="enscript-variable-name">$n$</span> down to <span class="enscript-variable-name">$(t + 1)$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.1  If <span class="enscript-variable-name">$i &gt; x.used$</span> then jump to the next iteration of this loop. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.2  If <span class="enscript-variable-name">$x_{i} = y_{t}$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.2.1  <span class="enscript-variable-name">$q_{i - t - 1} \leftarrow \beta - 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.3  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.3.1  <span class="enscript-variable-name">$\hat r \leftarrow x_{i} \cdot \beta + x_{i - 1}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.3.2  <span class="enscript-variable-name">$\hat r \leftarrow \lfloor \hat r / y_{t} \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.3.3  <span class="enscript-variable-name">$q_{i - t - 1} \leftarrow \hat r$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.4  <span class="enscript-variable-name">$q_{i - t - 1} \leftarrow q_{i - t - 1} + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Fixup quotient estimation. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.5  Loop <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.5.1  <span class="enscript-variable-name">$q_{i - t - 1} \leftarrow q_{i - t - 1} - 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.5.2  t<span class="enscript-variable-name">$1 \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.5.3  t<span class="enscript-variable-name">$1_0 \leftarrow y_{t - 1}, $</span> t<span class="enscript-variable-name">$1_1 \leftarrow y_t,$</span> t<span class="enscript-variable-name">$1.used \leftarrow 2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.5.4  <span class="enscript-variable-name">$t1 \leftarrow t1 \cdot q_{i - t - 1}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.5.5  t<span class="enscript-variable-name">$2_0 \leftarrow x_{i - 2}, $</span> t<span class="enscript-variable-name">$2_1 \leftarrow x_{i - 1}, $</span> t<span class="enscript-variable-name">$2_2 \leftarrow x_i, $</span> t<span class="enscript-variable-name">$2.used \leftarrow 3$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.5.6  If <span class="enscript-variable-name">$\vert t1 \vert &gt; \vert t2 \vert$</span> then goto step 13.5. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.6  t<span class="enscript-variable-name">$1 \leftarrow y \cdot q_{i - t - 1}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.7  t<span class="enscript-variable-name">$1 \leftarrow $</span> t<span class="enscript-variable-name">$1 \cdot \beta^{i - t - 1}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.8  <span class="enscript-variable-name">$x \leftarrow x - $</span> t<span class="enscript-variable-name">$1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.9  If <span class="enscript-variable-name">$x.sign = MP\_NEG$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.10  t<span class="enscript-variable-name">$1 \leftarrow y$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.11  t<span class="enscript-variable-name">$1 \leftarrow $</span> t<span class="enscript-variable-name">$1 \cdot \beta^{i - t - 1}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.12  <span class="enscript-variable-name">$x \leftarrow x + $</span> t<span class="enscript-variable-name">$1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}13.13  <span class="enscript-variable-name">$q_{i - t - 1} \leftarrow q_{i - t - 1} - 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\\</span>
Finalize the result. <span class="enscript-keyword">\\</span>
14.  Clamp excess digits of <span class="enscript-variable-name">$q$</span> <span class="enscript-keyword">\\</span>
15.  <span class="enscript-variable-name">$c \leftarrow q, c.sign \leftarrow sign$</span> <span class="enscript-keyword">\\</span>
16.  <span class="enscript-variable-name">$x.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
17.  <span class="enscript-variable-name">$d \leftarrow \lfloor x / 2^{norm} \rfloor$</span> <span class="enscript-keyword">\\</span>
18.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>div (continued)}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>div.}
This algorithm will calculate quotient and remainder from an integer division given a dividend and divisor.  The algorithm is a signed
division and will produce a fully qualified quotient and remainder.

First the divisor <span class="enscript-variable-name">$b$</span> must be non-zero which is enforced in step one.  If the divisor is larger than the dividend than the quotient is implicitly 
zero and the remainder is the dividend.  

After the first two trivial cases of inputs are handled the variable <span class="enscript-variable-name">$q$</span> is setup to receive the digits of the quotient.  Two unsigned copies of the
divisor <span class="enscript-variable-name">$y$</span> and dividend <span class="enscript-variable-name">$x$</span> are made as well.  The core of the division algorithm is an unsigned division and will only work if the values are
positive.  Now the two values <span class="enscript-variable-name">$x$</span> and <span class="enscript-variable-name">$y$</span> must be normalized such that the leading digit of <span class="enscript-variable-name">$y$</span> is greater than or equal to <span class="enscript-variable-name">$\beta / 2$</span>.  
This is performed by shifting both to the left by enough bits to get the desired normalization.  

At this point the division algorithm can begin producing digits of the quotient.  Recall that maximum value of the estimation used is 
<span class="enscript-variable-name">$2\beta - {2 \over \beta}$</span> which means that a digit of the quotient must be first produced by another means.  In this case <span class="enscript-variable-name">$y$</span> is shifted
to the left (<span class="enscript-keyword">\textit</span>{step ten}) so that it has the same number of digits as <span class="enscript-variable-name">$x$</span>.  The loop on step eleven will subtract multiples of the 
shifted copy of <span class="enscript-variable-name">$y$</span> until <span class="enscript-variable-name">$x$</span> is smaller.  Since the leading digit of <span class="enscript-variable-name">$y$</span> is greater than or equal to <span class="enscript-variable-name">$\beta/2$</span> this loop will iterate at most two
times to produce the desired leading digit of the quotient.  

Now the remainder of the digits can be produced.  The equation <span class="enscript-variable-name">$\hat q = \lfloor {{x_i \beta + x_{i-1}}\over y_t} \rfloor$</span> is used to fairly
accurately approximate the true quotient digit.  The estimation can in theory produce an estimation as high as <span class="enscript-variable-name">$2\beta - {2 \over \beta}$</span> but by
induction the upper quotient digit is correct (<span class="enscript-keyword">\textit</span>{as established on step eleven}) and the estimate must be less than <span class="enscript-variable-name">$\beta$</span>.  

Recall from section~<span class="enscript-keyword">\ref</span>{sec:divest} that the estimation is never too low but may be too high.  The next step of the estimation process is
to refine the estimation.  The loop on step 13.5 uses <span class="enscript-variable-name">$x_i\beta^2 + x_{i-1}\beta + x_{i-2}$</span> and <span class="enscript-variable-name">$q_{i - t - 1}(y_t\beta + y_{t-1})$</span> as a higher
order approximation to adjust the quotient digit.

After both phases of estimation the quotient digit may still be off by a value of one<span class="enscript-keyword">\footnote</span>{This is similar to the error introduced
by optimizing Barrett reduction.}.  Steps 13.6 and 13.7 subtract the multiple of the divisor from the dividend (<span class="enscript-keyword">\textit</span>{Similar to step 3.3 of
algorithm~<span class="enscript-keyword">\ref</span>{fig:raddiv}} and then subsequently add a multiple of the divisor if the quotient was too large.  

Now that the quotient has been determine finializing the result is a matter of clamping the quotient, fixing the sizes and de-normalizing the 
remainder.  An important aspect of this algorithm seemingly overlooked in other descriptions such as that of Algorithm 14.20 HAC <span class="enscript-keyword">\cite</span>[pp. 598]{HAC}
is that when the estimations are being made (<span class="enscript-keyword">\textit</span>{inside the loop on step 13.5}) that the digits <span class="enscript-variable-name">$y_{t-1}$</span>, <span class="enscript-variable-name">$x_{i-2}$</span> and <span class="enscript-variable-name">$x_{i-1}$</span> may lie 
outside their respective boundaries.  For example, if <span class="enscript-variable-name">$t = 0$</span> or <span class="enscript-variable-name">$i \le 1$</span> then the digits would be undefined.  In those cases the digits should
respectively be replaced with a zero.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>div.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The implementation of this algorithm differs slightly from the pseudo code presented previously.  In this algorithm either of the quotient <span class="enscript-variable-name">$c$</span> or
remainder <span class="enscript-variable-name">$d$</span> may be passed as a <span class="enscript-keyword">\textbf</span>{NULL} pointer which indicates their value is not desired.  For example, the C code to call the division
algorithm with only the quotient is 

<span class="enscript-keyword">\begin</span>{verbatim}
mp_div(&amp;a, &amp;b, &amp;c, NULL);  /* c = [a/b] */
<span class="enscript-keyword">\end</span>{verbatim}

Lines 109 and 113 handle the two trivial cases of inputs which are division by zero and dividend smaller than the divisor 
respectively.  After the two trivial cases all of the temporary variables are initialized.  Line 148 determines the sign of 
the quotient and line 148 ensures that both <span class="enscript-variable-name">$x$</span> and <span class="enscript-variable-name">$y$</span> are positive.  

The number of bits in the leading digit is calculated on line 151.  Implictly an mp<span class="enscript-keyword">\_</span>int with <span class="enscript-variable-name">$r$</span> digits will require <span class="enscript-variable-name">$lg(\beta)(r-1) + k$</span> bits
of precision which when reduced modulo <span class="enscript-variable-name">$lg(\beta)$</span> produces the value of <span class="enscript-variable-name">$k$</span>.  In this case <span class="enscript-variable-name">$k$</span> is the number of bits in the leading digit which is
exactly what is required.  For the algorithm to operate <span class="enscript-variable-name">$k$</span> must equal <span class="enscript-variable-name">$lg(\beta) - 1$</span> and when it does not the inputs must be normalized by shifting
them to the left by <span class="enscript-variable-name">$lg(\beta) - 1 - k$</span> bits.

Throughout the variables <span class="enscript-variable-name">$n$</span> and <span class="enscript-variable-name">$t$</span> will represent the highest digit of <span class="enscript-variable-name">$x$</span> and <span class="enscript-variable-name">$y$</span> respectively.  These are first used to produce the 
leading digit of the quotient.  The loop beginning on line 184 will produce the remainder of the quotient digits.

The conditional ``continue'' on line 187 is used to prevent the algorithm from reading past the leading edge of <span class="enscript-variable-name">$x$</span> which can occur when the
algorithm eliminates multiple non-zero digits in a single iteration.  This ensures that <span class="enscript-variable-name">$x_i$</span> is always non-zero since by definition the digits
above the <span class="enscript-variable-name">$i$</span>'th position <span class="enscript-variable-name">$x$</span> must be zero in order for the quotient to be precise<span class="enscript-keyword">\footnote</span>{Precise as far as integer division is concerned.}.  

Lines 214, 216 and 223 through 225 manually construct the high accuracy estimations by setting the digits of the two mp<span class="enscript-keyword">\_</span>int 
variables directly.  

<span class="enscript-keyword">\section</span>{Single Digit Helpers}

This section briefly describes a series of single digit helper algorithms which come in handy when working with small constants.  All of 
the helper functions assume the single digit input is positive and will treat them as such.

<span class="enscript-keyword">\subsection</span>{Single Digit Addition and Subtraction}

Both addition and subtraction are performed by ``cheating'' and using mp<span class="enscript-keyword">\_</span>set followed by the higher level addition or subtraction 
algorithms.   As a result these algorithms are subtantially simpler with a slight cost in performance.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>add<span class="enscript-keyword">\_</span>d}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and a mp<span class="enscript-keyword">\_</span>digit <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = a + b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$t \leftarrow b$</span> (<span class="enscript-keyword">\textit</span>{mp<span class="enscript-keyword">\_</span>set}) <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$c \leftarrow a + t$</span> <span class="enscript-keyword">\\</span>
3.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>add<span class="enscript-keyword">\_</span>d}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>add<span class="enscript-keyword">\_</span>d.}
This algorithm initiates a temporary mp<span class="enscript-keyword">\_</span>int with the value of the single digit and uses algorithm mp<span class="enscript-keyword">\_</span>add to add the two values together.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>add<span class="enscript-keyword">\_</span>d.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Clever use of the letter 't'.

<span class="enscript-keyword">\subsubsection</span>{Subtraction}
The single digit subtraction algorithm mp<span class="enscript-keyword">\_</span>sub<span class="enscript-keyword">\_</span>d is essentially the same except it uses mp<span class="enscript-keyword">\_</span>sub to subtract the digit from the mp<span class="enscript-keyword">\_</span>int.

<span class="enscript-keyword">\subsection</span>{Single Digit Multiplication}
Single digit multiplication arises enough in division and radix conversion that it ought to be implement as a special case of the baseline
multiplication algorithm.  Essentially this algorithm is a modified version of algorithm s<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>digs where one of the multiplicands
only has one digit.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>d}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and a mp<span class="enscript-keyword">\_</span>digit <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = ab$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$pa \leftarrow a.used$</span> <span class="enscript-keyword">\\</span>
2.  Grow <span class="enscript-variable-name">$c$</span> to at least <span class="enscript-variable-name">$pa + 1$</span> digits. <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$oldused \leftarrow c.used$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$c.used \leftarrow pa + 1$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$c.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$\mu \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
7.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$pa - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  <span class="enscript-variable-name">$\hat r \leftarrow \mu + a_{ix}b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.2  <span class="enscript-variable-name">$c_{ix} \leftarrow \hat r \mbox{ (mod }\beta\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.3  <span class="enscript-variable-name">$\mu \leftarrow \lfloor \hat r / \beta \rfloor$</span> <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$c_{pa} \leftarrow \mu$</span> <span class="enscript-keyword">\\</span>
9.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$pa + 1$</span> to <span class="enscript-variable-name">$oldused$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.1  <span class="enscript-variable-name">$c_{ix} \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
10.  Clamp excess digits of <span class="enscript-variable-name">$c$</span>. <span class="enscript-keyword">\\</span>
11.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>d}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>d.}
This algorithm quickly multiplies an mp<span class="enscript-keyword">\_</span>int by a small single digit value.  It is specially tailored to the job and has a minimal of overhead.  
Unlike the full multiplication algorithms this algorithm does not require any significnat temporary storage or memory allocations.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>mul<span class="enscript-keyword">\_</span>d.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

In this implementation the destination <span class="enscript-variable-name">$c$</span> may point to the same mp<span class="enscript-keyword">\_</span>int as the source <span class="enscript-variable-name">$a$</span> since the result is written after the digit is 
read from the source.  This function uses pointer aliases <span class="enscript-variable-name">$tmpa$</span> and <span class="enscript-variable-name">$tmpc$</span> for the digits of <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$c$</span> respectively.  

<span class="enscript-keyword">\subsection</span>{Single Digit Division}
Like the single digit multiplication algorithm, single digit division is also a fairly common algorithm used in radix conversion.  Since the
divisor is only a single digit a specialized variant of the division algorithm can be used to compute the quotient.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>d}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and a mp<span class="enscript-keyword">\_</span>digit <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = \lfloor a / b \rfloor, d = a - cb$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b = 0$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}).<span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$b = 3$</span> then use algorithm mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>3 instead. <span class="enscript-keyword">\\</span>
3.  Init <span class="enscript-variable-name">$q$</span> to <span class="enscript-variable-name">$a.used$</span> digits.  <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$q.used \leftarrow a.used$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$q.sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
6.  <span class="enscript-variable-name">$\hat w \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
7.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$a.used - 1$</span> down to <span class="enscript-variable-name">$0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  <span class="enscript-variable-name">$\hat w \leftarrow \hat w \beta + a_{ix}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.2  If <span class="enscript-variable-name">$\hat w \ge b$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.2.1  <span class="enscript-variable-name">$t \leftarrow \lfloor \hat w / b \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.2.2  <span class="enscript-variable-name">$\hat w \leftarrow \hat w \mbox{ (mod }b\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.3  else<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.3.1  <span class="enscript-variable-name">$t \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.4  <span class="enscript-variable-name">$q_{ix} \leftarrow t$</span> <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$d \leftarrow \hat w$</span> <span class="enscript-keyword">\\</span>
9.  Clamp excess digits of <span class="enscript-variable-name">$q$</span>. <span class="enscript-keyword">\\</span>
10.  <span class="enscript-variable-name">$c \leftarrow q$</span> <span class="enscript-keyword">\\</span>
11.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>d}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>d.}
This algorithm divides the mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> by the single mp<span class="enscript-keyword">\_</span>digit <span class="enscript-variable-name">$b$</span> using an optimized approach.  Essentially in every iteration of the
algorithm another digit of the dividend is reduced and another digit of quotient produced.  Provided <span class="enscript-variable-name">$b &lt; \beta$</span> the value of <span class="enscript-variable-name">$\hat w$</span>
after step 7.1 will be limited such that <span class="enscript-variable-name">$0 \le \lfloor \hat w / b \rfloor &lt; \beta$</span>.  

If the divisor <span class="enscript-variable-name">$b$</span> is equal to three a variant of this algorithm is used which is called mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>3.  It replaces the division by three with
a multiplication by <span class="enscript-variable-name">$\lfloor \beta / 3 \rfloor$</span> and the appropriate shift and residual fixup.  In essence it is much like the Barrett reduction
from chapter seven.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>div<span class="enscript-keyword">\_</span>d.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Like the implementation of algorithm mp<span class="enscript-keyword">\_</span>div this algorithm allows either of the quotient or remainder to be passed as a <span class="enscript-keyword">\textbf</span>{NULL} pointer to
indicate the respective value is not required.  This allows a trivial single digit modular reduction algorithm, mp<span class="enscript-keyword">\_</span>mod<span class="enscript-keyword">\_</span>d to be created.

The division and remainder on lines 44 and @45,<span class="enscript-comment">%@ can be replaced often by a single division on most processors.  For example, the 32-bit x86 based 
</span>processors can divide a 64-bit quantity by a 32-bit quantity and produce the quotient and remainder simultaneously.  Unfortunately the GCC 
compiler does not recognize that optimization and will actually produce two function calls to find the quotient and remainder respectively.  

<span class="enscript-keyword">\subsection</span>{Single Digit Root Extraction}

Finding the <span class="enscript-variable-name">$n$</span>'th root of an integer is fairly easy as far as numerical analysis is concerned.  Algorithms such as the Newton-Raphson approximation 
(<span class="enscript-keyword">\ref</span>{eqn:newton}) series will converge very quickly to a root for any continuous function <span class="enscript-variable-name">$f(x)$</span>.  

<span class="enscript-keyword">\begin</span>{equation}
x_{i+1} = x_i - {f(x_i) <span class="enscript-keyword">\over</span> f'(x_i)}
<span class="enscript-keyword">\label</span>{eqn:newton}
<span class="enscript-keyword">\end</span>{equation}

In this case the <span class="enscript-variable-name">$n$</span>'th root is desired and <span class="enscript-variable-name">$f(x) = x^n - a$</span> where <span class="enscript-variable-name">$a$</span> is the integer of which the root is desired.  The derivative of <span class="enscript-variable-name">$f(x)$</span> is 
simply <span class="enscript-variable-name">$f'(x) = nx^{n - 1}$</span>.  Of particular importance is that this algorithm will be used over the integers not over the a more continuous domain
such as the real numbers.  As a result the root found can be above the true root by few and must be manually adjusted.  Ideally at the end of the 
algorithm the <span class="enscript-variable-name">$n$</span>'th root <span class="enscript-variable-name">$b$</span> of an integer <span class="enscript-variable-name">$a$</span> is desired such that <span class="enscript-variable-name">$b^n \le a$</span>.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>n<span class="enscript-keyword">\_</span>root}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and a mp<span class="enscript-keyword">\_</span>digit <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c^b \le a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b$</span> is even and <span class="enscript-variable-name">$a.sign = MP\_NEG$</span> return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}). <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$sign \leftarrow a.sign$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$a.sign \leftarrow MP\_ZPOS$</span> <span class="enscript-keyword">\\</span>
4.  t<span class="enscript-variable-name">$2 \leftarrow 2$</span> <span class="enscript-keyword">\\</span>
5.  Loop <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  t<span class="enscript-variable-name">$1 \leftarrow $</span> t<span class="enscript-variable-name">$2$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  t<span class="enscript-variable-name">$3 \leftarrow $</span> t<span class="enscript-variable-name">$1^{b - 1}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  t<span class="enscript-variable-name">$2 \leftarrow $</span> t<span class="enscript-variable-name">$3 $</span> <span class="enscript-variable-name">$\cdot$</span> t<span class="enscript-variable-name">$1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.4  t<span class="enscript-variable-name">$2 \leftarrow $</span> t<span class="enscript-variable-name">$2 - a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.5  t<span class="enscript-variable-name">$3 \leftarrow $</span> t<span class="enscript-variable-name">$3 \cdot b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.6  t<span class="enscript-variable-name">$3 \leftarrow \lfloor $</span>t<span class="enscript-variable-name">$2 / $</span>t<span class="enscript-variable-name">$3 \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.7  t<span class="enscript-variable-name">$2 \leftarrow $</span> t<span class="enscript-variable-name">$1 - $</span> t<span class="enscript-variable-name">$3$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.8  If t<span class="enscript-variable-name">$1 \ne $</span> t<span class="enscript-variable-name">$2$</span> then goto step 5.  <span class="enscript-keyword">\\</span>
6.  Loop <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  t<span class="enscript-variable-name">$2 \leftarrow $</span> t<span class="enscript-variable-name">$1^b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  If t<span class="enscript-variable-name">$2 &gt; a$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.2.1  t<span class="enscript-variable-name">$1 \leftarrow $</span> t<span class="enscript-variable-name">$1 - 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.2.2  Goto step 6. <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$a.sign \leftarrow sign$</span> <span class="enscript-keyword">\\</span>
8.  <span class="enscript-variable-name">$c \leftarrow $</span> t<span class="enscript-variable-name">$1$</span> <span class="enscript-keyword">\\</span>
9.  <span class="enscript-variable-name">$c.sign \leftarrow sign$</span>  <span class="enscript-keyword">\\</span>
10.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}).  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>n<span class="enscript-keyword">\_</span>root}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>n<span class="enscript-keyword">\_</span>root.}
This algorithm finds the integer <span class="enscript-variable-name">$n$</span>'th root of an input using the Newton-Raphson approach.  It is partially optimized based on the observation
that the numerator of <span class="enscript-variable-name">${f(x) \over f'(x)}$</span> can be derived from a partial denominator.  That is at first the denominator is calculated by finding
<span class="enscript-variable-name">$x^{b - 1}$</span>.  This value can then be multiplied by <span class="enscript-variable-name">$x$</span> and have <span class="enscript-variable-name">$a$</span> subtracted from it to find the numerator.  This saves a total of <span class="enscript-variable-name">$b - 1$</span> 
multiplications by t<span class="enscript-variable-name">$1$</span> inside the loop.  

The initial value of the approximation is t<span class="enscript-variable-name">$2 = 2$</span> which allows the algorithm to start with very small values and quickly converge on the
root.  Ideally this algorithm is meant to find the <span class="enscript-variable-name">$n$</span>'th root of an input where <span class="enscript-variable-name">$n$</span> is bounded by <span class="enscript-variable-name">$2 \le n \le 5$</span>.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>n<span class="enscript-keyword">\_</span>root.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\section</span>{Random Number Generation}

Random numbers come up in a variety of activities from public key cryptography to simple simulations and various randomized algorithms.  Pollard-Rho 
factoring for example, can make use of random values as starting points to find factors of a composite integer.  In this case the algorithm presented
is solely for simulations and not intended for cryptographic use.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>rand}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   An integer <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  A pseudo-random number of <span class="enscript-variable-name">$b$</span> digits <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$a \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$b \le 0$</span> return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}) <span class="enscript-keyword">\\</span>
3.  Pick a non-zero random digit <span class="enscript-variable-name">$d$</span>. <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$a \leftarrow a + d$</span> <span class="enscript-keyword">\\</span>
5.  for <span class="enscript-variable-name">$ix$</span> from 1 to <span class="enscript-variable-name">$d - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$a \leftarrow a \cdot \beta$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  Pick a random digit <span class="enscript-variable-name">$d$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  <span class="enscript-variable-name">$a \leftarrow a + d$</span> <span class="enscript-keyword">\\</span>
6.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>rand}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>rand.}
This algorithm produces a pseudo-random integer of <span class="enscript-variable-name">$b$</span> digits.  By ensuring that the first digit is non-zero the algorithm also guarantees that the
final result has at least <span class="enscript-variable-name">$b$</span> digits.  It relies heavily on a third-part random number generator which should ideally generate uniformly all of
the integers from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$\beta - 1$</span>.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>rand.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\section</span>{Formatted Representations}
The ability to emit a radix-<span class="enscript-variable-name">$n$</span> textual representation of an integer is useful for interacting with human parties.  For example, the ability to
be given a string of characters such as ``114585'' and turn it into the radix-<span class="enscript-variable-name">$\beta$</span> equivalent would make it easier to enter numbers
into a program.

<span class="enscript-keyword">\subsection</span>{Reading Radix-n Input}
For the purposes of this text we will assume that a simple lower ASCII map (<span class="enscript-keyword">\ref</span>{fig:ASC}) is used for the values of from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$63$</span> to 
printable characters.  For example, when the character ``N'' is read it represents the integer <span class="enscript-variable-name">$23$</span>.  The first <span class="enscript-variable-name">$16$</span> characters of the
map are for the common representations up to hexadecimal.  After that they match the ``base64'' encoding scheme which are suitable chosen
such that they are printable.  While outputting as base64 may not be too helpful for human operators it does allow communication via non binary
mediums.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[here]
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{cc|cc|cc|cc}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Value} &amp; <span class="enscript-keyword">\textbf</span>{Char} &amp; <span class="enscript-keyword">\textbf</span>{Value} &amp; <span class="enscript-keyword">\textbf</span>{Char} &amp; <span class="enscript-keyword">\textbf</span>{Value} &amp; <span class="enscript-keyword">\textbf</span>{Char} &amp;  <span class="enscript-keyword">\textbf</span>{Value} &amp; <span class="enscript-keyword">\textbf</span>{Char} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> 
0 &amp; 0 &amp; 1 &amp; 1 &amp; 2 &amp; 2 &amp; 3 &amp; 3 <span class="enscript-keyword">\\</span>
4 &amp; 4 &amp; 5 &amp; 5 &amp; 6 &amp; 6 &amp; 7 &amp; 7 <span class="enscript-keyword">\\</span>
8 &amp; 8 &amp; 9 &amp; 9 &amp; 10 &amp; A &amp; 11 &amp; B <span class="enscript-keyword">\\</span>
12 &amp; C &amp; 13 &amp; D &amp; 14 &amp; E &amp; 15 &amp; F <span class="enscript-keyword">\\</span>
16 &amp; G &amp; 17 &amp; H &amp; 18 &amp; I &amp; 19 &amp; J <span class="enscript-keyword">\\</span>
20 &amp; K &amp; 21 &amp; L &amp; 22 &amp; M &amp; 23 &amp; N <span class="enscript-keyword">\\</span>
24 &amp; O &amp; 25 &amp; P &amp; 26 &amp; Q &amp; 27 &amp; R <span class="enscript-keyword">\\</span>
28 &amp; S &amp; 29 &amp; T &amp; 30 &amp; U &amp; 31 &amp; V <span class="enscript-keyword">\\</span>
32 &amp; W &amp; 33 &amp; X &amp; 34 &amp; Y &amp; 35 &amp; Z <span class="enscript-keyword">\\</span>
36 &amp; a &amp; 37 &amp; b &amp; 38 &amp; c &amp; 39 &amp; d <span class="enscript-keyword">\\</span>
40 &amp; e &amp; 41 &amp; f &amp; 42 &amp; g &amp; 43 &amp; h <span class="enscript-keyword">\\</span>
44 &amp; i &amp; 45 &amp; j &amp; 46 &amp; k &amp; 47 &amp; l <span class="enscript-keyword">\\</span>
48 &amp; m &amp; 49 &amp; n &amp; 50 &amp; o &amp; 51 &amp; p <span class="enscript-keyword">\\</span>
52 &amp; q &amp; 53 &amp; r &amp; 54 &amp; s &amp; 55 &amp; t <span class="enscript-keyword">\\</span>
56 &amp; u &amp; 57 &amp; v &amp; 58 &amp; w &amp; 59 &amp; x <span class="enscript-keyword">\\</span>
60 &amp; y &amp; 61 &amp; z &amp; 62 &amp; <span class="enscript-variable-name">$+$</span> &amp; 63 &amp; <span class="enscript-variable-name">$/$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Lower ASCII Map}
<span class="enscript-keyword">\label</span>{fig:ASC}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>read<span class="enscript-keyword">\_</span>radix}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   A string <span class="enscript-variable-name">$str$</span> of length <span class="enscript-variable-name">$sn$</span> and radix <span class="enscript-variable-name">$r$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The radix-<span class="enscript-variable-name">$\beta$</span> equivalent mp<span class="enscript-keyword">\_</span>int. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$r &lt; 2$</span> or <span class="enscript-variable-name">$r &gt; 64$</span> return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}). <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$ix \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
3.  If <span class="enscript-variable-name">$str_0 =$</span> ``-'' then do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$ix \leftarrow ix + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.2  <span class="enscript-variable-name">$sign \leftarrow MP\_NEG$</span> <span class="enscript-keyword">\\</span>
4.  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$sign \leftarrow MP\_ZPOS$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$a \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
6.  for <span class="enscript-variable-name">$iy$</span> from <span class="enscript-variable-name">$ix$</span> to <span class="enscript-variable-name">$sn - 1$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  Let <span class="enscript-variable-name">$y$</span> denote the position in the map of <span class="enscript-variable-name">$str_{iy}$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  If <span class="enscript-variable-name">$str_{iy}$</span> is not in the map or <span class="enscript-variable-name">$y \ge r$</span> then goto step 7. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.3  <span class="enscript-variable-name">$a \leftarrow a \cdot r$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.4  <span class="enscript-variable-name">$a \leftarrow a + y$</span> <span class="enscript-keyword">\\</span>
7.  If <span class="enscript-variable-name">$a \ne 0$</span> then <span class="enscript-variable-name">$a.sign \leftarrow sign$</span> <span class="enscript-keyword">\\</span>
8.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>read<span class="enscript-keyword">\_</span>radix}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>read<span class="enscript-keyword">\_</span>radix.}
This algorithm will read an ASCII string and produce the radix-<span class="enscript-variable-name">$\beta$</span> mp<span class="enscript-keyword">\_</span>int representation of the same integer.  A minus symbol ``-'' may precede the 
string  to indicate the value is negative, otherwise it is assumed to be positive.  The algorithm will read up to <span class="enscript-variable-name">$sn$</span> characters from the input
and will stop when it reads a character it cannot map the algorithm stops reading characters from the string.  This allows numbers to be embedded
as part of larger input without any significant problem.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>read<span class="enscript-keyword">\_</span>radix.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\subsection</span>{Generating Radix-<span class="enscript-variable-name">$n$</span> Output}
Generating radix-<span class="enscript-variable-name">$n$</span> output is fairly trivial with a division and remainder algorithm.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>toradix}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   A mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and an integer <span class="enscript-variable-name">$r$</span><span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The radix-<span class="enscript-variable-name">$r$</span> representation of <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$r &lt; 2$</span> or <span class="enscript-variable-name">$r &gt; 64$</span> return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$a = 0$</span> then <span class="enscript-variable-name">$str = $</span> ``<span class="enscript-variable-name">$0$</span>'' and return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}).  <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$t \leftarrow a$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$str \leftarrow$</span> ``'' <span class="enscript-keyword">\\</span>
5.  if <span class="enscript-variable-name">$t.sign = MP\_NEG$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$str \leftarrow str + $</span> ``-'' <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$t.sign = MP\_ZPOS$</span> <span class="enscript-keyword">\\</span>
6.  While (<span class="enscript-variable-name">$t \ne 0$</span>) do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$d \leftarrow t \mbox{ (mod }r\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  <span class="enscript-variable-name">$t \leftarrow \lfloor t / r \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.3  Look up <span class="enscript-variable-name">$d$</span> in the map and store the equivalent character in <span class="enscript-variable-name">$y$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.4  <span class="enscript-variable-name">$str \leftarrow str + y$</span> <span class="enscript-keyword">\\</span>
7.  If <span class="enscript-variable-name">$str_0 = $</span>``<span class="enscript-variable-name">$-$</span>'' then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  Reverse the digits <span class="enscript-variable-name">$str_1, str_2, \ldots str_n$</span>. <span class="enscript-keyword">\\</span>
8.  Otherwise <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  Reverse the digits <span class="enscript-variable-name">$str_0, str_1, \ldots str_n$</span>. <span class="enscript-keyword">\\</span>
9.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}).<span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>toradix}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>toradix.}
This algorithm computes the radix-<span class="enscript-variable-name">$r$</span> representation of an mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span>.  The ``digits'' of the representation are extracted by reducing 
successive powers of <span class="enscript-variable-name">$\lfloor a / r^k \rfloor$</span> the input modulo <span class="enscript-variable-name">$r$</span> until <span class="enscript-variable-name">$r^k &gt; a$</span>.  Note that instead of actually dividing by <span class="enscript-variable-name">$r^k$</span> in
each iteration the quotient <span class="enscript-variable-name">$\lfloor a / r \rfloor$</span> is saved for the next iteration.  As a result a series of trivial <span class="enscript-variable-name">$n \times 1$</span> divisions
are required instead of a series of <span class="enscript-variable-name">$n \times k$</span> divisions.  One design flaw of this approach is that the digits are produced in the reverse order 
(see~<span class="enscript-keyword">\ref</span>{fig:mpradix}).  To remedy this flaw the digits must be swapped or simply ``reversed''.

<span class="enscript-keyword">\begin</span>{figure}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{|c|c|c|}
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\textbf</span>{Value of <span class="enscript-variable-name">$a$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Value of <span class="enscript-variable-name">$d$</span>} &amp; <span class="enscript-keyword">\textbf</span>{Value of <span class="enscript-variable-name">$str$</span>} <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1234$</span> &amp; -- &amp; -- <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$123$</span>  &amp; <span class="enscript-variable-name">$4$</span> &amp; ``4'' <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$12$</span>   &amp; <span class="enscript-variable-name">$3$</span> &amp; ``43'' <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$1$</span>    &amp; <span class="enscript-variable-name">$2$</span> &amp; ``432'' <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-variable-name">$0$</span>    &amp; <span class="enscript-variable-name">$1$</span> &amp; ``4321'' <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\caption</span>{Example of Algorithm mp<span class="enscript-keyword">\_</span>toradix.}
<span class="enscript-keyword">\label</span>{fig:mpradix}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>toradix.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\chapter</span>{Number Theoretic Algorithms}
This chapter discusses several fundamental number theoretic algorithms such as the greatest common divisor, least common multiple and Jacobi 
symbol computation.  These algorithms arise as essential components in several key cryptographic algorithms such as the RSA public key algorithm and
various Sieve based factoring algorithms.

<span class="enscript-keyword">\section</span>{Greatest Common Divisor}
The greatest common divisor of two integers <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>, often denoted as <span class="enscript-variable-name">$(a, b)$</span> is the largest integer <span class="enscript-variable-name">$k$</span> that is a proper divisor of
both <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>.  That is, <span class="enscript-variable-name">$k$</span> is the largest integer such that <span class="enscript-variable-name">$0 \equiv a \mbox{ (mod }k\mbox{)}$</span> and <span class="enscript-variable-name">$0 \equiv b \mbox{ (mod }k\mbox{)}$</span> occur
simultaneously.

The most common approach (cite) is to reduce one input modulo another.  That is if <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> are divisible by some integer <span class="enscript-variable-name">$k$</span> and if <span class="enscript-variable-name">$qa + r = b$</span> then
<span class="enscript-variable-name">$r$</span> is also divisible by <span class="enscript-variable-name">$k$</span>.  The reduction pattern follows <span class="enscript-variable-name">$\left &lt; a , b \right &gt; \rightarrow \left &lt; b, a \mbox{ mod } b \right &gt;$</span>.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Greatest Common Divisor (I)}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two positive integers <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> greater than zero. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The greatest common divisor <span class="enscript-variable-name">$(a, b)$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  While (<span class="enscript-variable-name">$b &gt; 0$</span>) do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$r \leftarrow a \mbox{ (mod }b\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  <span class="enscript-variable-name">$a \leftarrow b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.3  <span class="enscript-variable-name">$b \leftarrow r$</span> <span class="enscript-keyword">\\</span>
2.  Return(<span class="enscript-variable-name">$a$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Greatest Common Divisor (I)}
<span class="enscript-keyword">\label</span>{fig:gcd1}
<span class="enscript-keyword">\end</span>{figure}

This algorithm will quickly converge on the greatest common divisor since the residue <span class="enscript-variable-name">$r$</span> tends diminish rapidly.  However, divisions are
relatively expensive operations to perform and should ideally be avoided.  There is another approach based on a similar relationship of 
greatest common divisors.  The faster approach is based on the observation that if <span class="enscript-variable-name">$k$</span> divides both <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> it will also divide <span class="enscript-variable-name">$a - b$</span>.  
In particular, we would like <span class="enscript-variable-name">$a - b$</span> to decrease in magnitude which implies that <span class="enscript-variable-name">$b \ge a$</span>.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Greatest Common Divisor (II)}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two positive integers <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> greater than zero. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The greatest common divisor <span class="enscript-variable-name">$(a, b)$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  While (<span class="enscript-variable-name">$b &gt; 0$</span>) do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  Swap <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> such that <span class="enscript-variable-name">$a$</span> is the smallest of the two. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  <span class="enscript-variable-name">$b \leftarrow b - a$</span> <span class="enscript-keyword">\\</span>
2.  Return(<span class="enscript-variable-name">$a$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Greatest Common Divisor (II)}
<span class="enscript-keyword">\label</span>{fig:gcd2}
<span class="enscript-keyword">\end</span>{figure}

<span class="enscript-keyword">\textbf</span>{Proof} <span class="enscript-keyword">\textit</span>{Algorithm~<span class="enscript-keyword">\ref</span>{fig:gcd2} will return the greatest common divisor of <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>.}
The algorithm in figure~<span class="enscript-keyword">\ref</span>{fig:gcd2} will eventually terminate since <span class="enscript-variable-name">$b \ge a$</span> the subtraction in step 1.2 will be a value less than <span class="enscript-variable-name">$b$</span>.  In other
words in every iteration that tuple <span class="enscript-variable-name">$\left &lt; a, b \right &gt;$</span> decrease in magnitude until eventually <span class="enscript-variable-name">$a = b$</span>.  Since both <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> are always 
divisible by the greatest common divisor (<span class="enscript-keyword">\textit</span>{until the last iteration}) and in the last iteration of the algorithm <span class="enscript-variable-name">$b = 0$</span>, therefore, in the 
second to last iteration of the algorithm <span class="enscript-variable-name">$b = a$</span> and clearly <span class="enscript-variable-name">$(a, a) = a$</span> which concludes the proof.  <span class="enscript-keyword">\textbf</span>{QED}.

As a matter of practicality algorithm <span class="enscript-keyword">\ref</span>{fig:gcd1} decreases far too slowly to be useful.  Specially if <span class="enscript-variable-name">$b$</span> is much larger than <span class="enscript-variable-name">$a$</span> such that 
<span class="enscript-variable-name">$b - a$</span> is still very much larger than <span class="enscript-variable-name">$a$</span>.  A simple addition to the algorithm is to divide <span class="enscript-variable-name">$b - a$</span> by a power of some integer <span class="enscript-variable-name">$p$</span> which does
not divide the greatest common divisor but will divide <span class="enscript-variable-name">$b - a$</span>.  In this case <span class="enscript-variable-name">${b - a} \over p$</span> is also an integer and still divisible by
the greatest common divisor.

However, instead of factoring <span class="enscript-variable-name">$b - a$</span> to find a suitable value of <span class="enscript-variable-name">$p$</span> the powers of <span class="enscript-variable-name">$p$</span> can be removed from <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> that are in common first.  
Then inside the loop whenever <span class="enscript-variable-name">$b - a$</span> is divisible by some power of <span class="enscript-variable-name">$p$</span> it can be safely removed.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{Greatest Common Divisor (III)}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   Two positive integers <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> greater than zero. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The greatest common divisor <span class="enscript-variable-name">$(a, b)$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$k \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
2.  While <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> are both divisible by <span class="enscript-variable-name">$p$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$a \leftarrow \lfloor a / p \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  <span class="enscript-variable-name">$b \leftarrow \lfloor b / p \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.3  <span class="enscript-variable-name">$k \leftarrow k + 1$</span> <span class="enscript-keyword">\\</span>
3.  While <span class="enscript-variable-name">$a$</span> is divisible by <span class="enscript-variable-name">$p$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$a \leftarrow \lfloor a / p \rfloor$</span> <span class="enscript-keyword">\\</span>
4.  While <span class="enscript-variable-name">$b$</span> is divisible by <span class="enscript-variable-name">$p$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$b \leftarrow \lfloor b / p \rfloor$</span> <span class="enscript-keyword">\\</span>
5.  While (<span class="enscript-variable-name">$b &gt; 0$</span>) do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  Swap <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> such that <span class="enscript-variable-name">$a$</span> is the smallest of the two. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$b \leftarrow b - a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  While <span class="enscript-variable-name">$b$</span> is divisible by <span class="enscript-variable-name">$p$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}5.3.1  <span class="enscript-variable-name">$b \leftarrow \lfloor b / p \rfloor$</span> <span class="enscript-keyword">\\</span>
6.  Return(<span class="enscript-variable-name">$a \cdot p^k$</span>). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm Greatest Common Divisor (III)}
<span class="enscript-keyword">\label</span>{fig:gcd3}
<span class="enscript-keyword">\end</span>{figure}

This algorithm is based on the first except it removes powers of <span class="enscript-variable-name">$p$</span> first and inside the main loop to ensure the tuple <span class="enscript-variable-name">$\left &lt; a, b \right &gt;$</span> 
decreases more rapidly.  The first loop on step two removes powers of <span class="enscript-variable-name">$p$</span> that are in common.  A count, <span class="enscript-variable-name">$k$</span>, is kept which will present a common
divisor of <span class="enscript-variable-name">$p^k$</span>.  After step two the remaining common divisor of <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> cannot be divisible by <span class="enscript-variable-name">$p$</span>.  This means that <span class="enscript-variable-name">$p$</span> can be safely 
divided out of the difference <span class="enscript-variable-name">$b - a$</span> so long as the division leaves no remainder.  

In particular the value of <span class="enscript-variable-name">$p$</span> should be chosen such that the division on step 5.3.1 occur often.  It also helps that division by <span class="enscript-variable-name">$p$</span> be easy
to compute.  The ideal choice of <span class="enscript-variable-name">$p$</span> is two since division by two amounts to a right logical shift.  Another important observation is that by
step five both <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> are odd.  Therefore, the diffrence <span class="enscript-variable-name">$b - a$</span> must be even which means that each iteration removes one bit from the 
largest of the pair.

<span class="enscript-keyword">\subsection</span>{Complete Greatest Common Divisor}
The algorithms presented so far cannot handle inputs which are zero or negative.  The following algorithm can handle all input cases properly
and will produce the greatest common divisor.

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>gcd}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The greatest common divisor <span class="enscript-variable-name">$c = (a, b)$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$a = 0$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$c \leftarrow \vert b \vert $</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$b = 0$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$c \leftarrow \vert a \vert $</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$u \leftarrow \vert a \vert, v \leftarrow \vert b \vert$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$k \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
5.  While <span class="enscript-variable-name">$u.used &gt; 0$</span> and <span class="enscript-variable-name">$v.used &gt; 0$</span> and <span class="enscript-variable-name">$u_0 \equiv v_0 \equiv 0 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$k \leftarrow k + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$u \leftarrow \lfloor u / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.3  <span class="enscript-variable-name">$v \leftarrow \lfloor v / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
6.  While <span class="enscript-variable-name">$u.used &gt; 0$</span> and <span class="enscript-variable-name">$u_0 \equiv 0 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$u \leftarrow \lfloor u / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
7.  While <span class="enscript-variable-name">$v.used &gt; 0$</span> and <span class="enscript-variable-name">$v_0 \equiv 0 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  <span class="enscript-variable-name">$v \leftarrow \lfloor v / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
8.  While <span class="enscript-variable-name">$v.used &gt; 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  If <span class="enscript-variable-name">$\vert u \vert &gt; \vert v \vert$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}8.1.1  Swap <span class="enscript-variable-name">$u$</span> and <span class="enscript-variable-name">$v$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.2  <span class="enscript-variable-name">$v \leftarrow \vert v \vert - \vert u \vert$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.3  While <span class="enscript-variable-name">$v.used &gt; 0$</span> and <span class="enscript-variable-name">$v_0 \equiv 0 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}8.3.1  <span class="enscript-variable-name">$v \leftarrow \lfloor v / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
9.  <span class="enscript-variable-name">$c \leftarrow u \cdot 2^k$</span> <span class="enscript-keyword">\\</span>
10.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>gcd}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>gcd.}
This algorithm will produce the greatest common divisor of two mp<span class="enscript-keyword">\_</span>ints <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>.  The algorithm was originally based on Algorithm B of
Knuth <span class="enscript-keyword">\cite</span>[pp. 338]{TAOCPV2} but has been modified to be simpler to explain.  In theory it achieves the same asymptotic working time as
Algorithm B and in practice this appears to be true.  

The first two steps handle the cases where either one of or both inputs are zero.  If either input is zero the greatest common divisor is the 
largest input or zero if they are both zero.  If the inputs are not trivial than <span class="enscript-variable-name">$u$</span> and <span class="enscript-variable-name">$v$</span> are assigned the absolute values of 
<span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> respectively and the algorithm will proceed to reduce the pair.

Step five will divide out any common factors of two and keep track of the count in the variable <span class="enscript-variable-name">$k$</span>.  After this step, two is no longer a
factor of the remaining greatest common divisor between <span class="enscript-variable-name">$u$</span> and <span class="enscript-variable-name">$v$</span> and can be safely evenly divided out of either whenever they are even.  Step 
six and seven ensure that the <span class="enscript-variable-name">$u$</span> and <span class="enscript-variable-name">$v$</span> respectively have no more factors of two.  At most only one of the while--loops will iterate since 
they cannot both be even.

By step eight both of <span class="enscript-variable-name">$u$</span> and <span class="enscript-variable-name">$v$</span> are odd which is required for the inner logic.  First the pair are swapped such that <span class="enscript-variable-name">$v$</span> is equal to
or greater than <span class="enscript-variable-name">$u$</span>.  This ensures that the subtraction on step 8.2 will always produce a positive and even result.  Step 8.3 removes any
factors of two from the difference <span class="enscript-variable-name">$u$</span> to ensure that in the next iteration of the loop both are once again odd.

After <span class="enscript-variable-name">$v = 0$</span> occurs the variable <span class="enscript-variable-name">$u$</span> has the greatest common divisor of the pair <span class="enscript-variable-name">$\left &lt; u, v \right &gt;$</span> just after step six.  The result
must be adjusted by multiplying by the common factors of two (<span class="enscript-variable-name">$2^k$</span>) removed earlier.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>gcd.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

This function makes use of the macros mp<span class="enscript-keyword">\_</span>iszero and mp<span class="enscript-keyword">\_</span>iseven.  The former evaluates to <span class="enscript-variable-name">$1$</span> if the input mp<span class="enscript-keyword">\_</span>int is equivalent to the 
integer zero otherwise it evaluates to <span class="enscript-variable-name">$0$</span>.  The latter evaluates to <span class="enscript-variable-name">$1$</span> if the input mp<span class="enscript-keyword">\_</span>int represents a non-zero even integer otherwise
it evaluates to <span class="enscript-variable-name">$0$</span>.  Note that just because mp<span class="enscript-keyword">\_</span>iseven may evaluate to <span class="enscript-variable-name">$0$</span> does not mean the input is odd, it could also be zero.  The three 
trivial cases of inputs are handled on lines 24 through 30.  After those lines the inputs are assumed to be non-zero.

Lines 32 and 37 make local copies <span class="enscript-variable-name">$u$</span> and <span class="enscript-variable-name">$v$</span> of the inputs <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> respectively.  At this point the common factors of two 
must be divided out of the two inputs.  The block starting at line 44 removes common factors of two by first counting the number of trailing
zero bits in both.  The local integer <span class="enscript-variable-name">$k$</span> is used to keep track of how many factors of <span class="enscript-variable-name">$2$</span> are pulled out of both values.  It is assumed that 
the number of factors will not exceed the maximum value of a C ``int'' data type<span class="enscript-keyword">\footnote</span>{Strictly speaking no array in C may have more than 
entries than are accessible by an ``int'' so this is not a limitation.}.  

At this point there are no more common factors of two in the two values.  The divisions by a power of two on lines 62 and 68 remove 
any independent factors of two such that both <span class="enscript-variable-name">$u$</span> and <span class="enscript-variable-name">$v$</span> are guaranteed to be an odd integer before hitting the main body of the algorithm.  The while loop
on line 73 performs the reduction of the pair until <span class="enscript-variable-name">$v$</span> is equal to zero.  The unsigned comparison and subtraction algorithms are used in
place of the full signed routines since both values are guaranteed to be positive and the result of the subtraction is guaranteed to be non-negative.

<span class="enscript-keyword">\section</span>{Least Common Multiple}
The least common multiple of a pair of integers is their product divided by their greatest common divisor.  For two integers <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> the
least common multiple is normally denoted as <span class="enscript-variable-name">$[ a, b ]$</span> and numerically equivalent to <span class="enscript-variable-name">${ab} \over {(a, b)}$</span>.  For example, if <span class="enscript-variable-name">$a = 2 \cdot 2 \cdot 3 = 12$</span>
and <span class="enscript-variable-name">$b = 2 \cdot 3 \cdot 3 \cdot 7 = 126$</span> the least common multiple is <span class="enscript-variable-name">${126 \over {(12, 126)}} = {126 \over 6} = 21$</span>.

The least common multiple arises often in coding theory as well as number theory.  If two functions have periods of <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> respectively they will
collide, that is be in synchronous states, after only <span class="enscript-variable-name">$[ a, b ]$</span> iterations.  This is why, for example, random number generators based on 
Linear Feedback Shift Registers (LFSR) tend to use registers with periods which are co-prime (<span class="enscript-keyword">\textit</span>{e.g. the greatest common divisor is one.}).  
Similarly in number theory if a composite <span class="enscript-variable-name">$n$</span> has two prime factors <span class="enscript-variable-name">$p$</span> and <span class="enscript-variable-name">$q$</span> then maximal order of any unit of <span class="enscript-variable-name">$\Z/n\Z$</span> will be <span class="enscript-variable-name">$[ p - 1, q - 1] $</span>.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>lcm}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The least common multiple <span class="enscript-variable-name">$c = [a, b]$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$c \leftarrow (a, b)$</span> <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$t \leftarrow a \cdot b$</span> <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$c \leftarrow \lfloor t / c \rfloor$</span> <span class="enscript-keyword">\\</span>
4.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>lcm}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>lcm.}
This algorithm computes the least common multiple of two mp<span class="enscript-keyword">\_</span>int inputs <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>.  It computes the least common multiple directly by
dividing the product of the two inputs by their greatest common divisor.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>lcm.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\section</span>{Jacobi Symbol Computation}
To explain the Jacobi Symbol we shall first discuss the Legendre function<span class="enscript-keyword">\footnote</span>{Arrg.  What is the name of this?} off which the Jacobi symbol is 
defined.  The Legendre function computes whether or not an integer <span class="enscript-variable-name">$a$</span> is a quadratic residue modulo an odd prime <span class="enscript-variable-name">$p$</span>.  Numerically it is
equivalent to equation <span class="enscript-keyword">\ref</span>{eqn:legendre}.

<span class="enscript-keyword">\textit</span>{-- Tom, don't be an ass, cite your source here...!}

<span class="enscript-keyword">\begin</span>{equation}
a^{(p-1)/2} <span class="enscript-keyword">\equiv</span> <span class="enscript-keyword">\begin</span>{array}{rl}
                              -1 &amp;  <span class="enscript-keyword">\mbox</span>{if }a<span class="enscript-keyword">\mbox</span>{ is a quadratic non-residue.} <span class="enscript-keyword">\\</span>
                              0  &amp;  <span class="enscript-keyword">\mbox</span>{if }a<span class="enscript-keyword">\mbox</span>{ divides }p<span class="enscript-keyword">\mbox</span>{.} <span class="enscript-keyword">\\</span>
                              1  &amp;  <span class="enscript-keyword">\mbox</span>{if }a<span class="enscript-keyword">\mbox</span>{ is a quadratic residue}. 
                              <span class="enscript-keyword">\end</span>{array} <span class="enscript-keyword">\mbox</span>{ (mod }p<span class="enscript-keyword">\mbox</span>{)}
<span class="enscript-keyword">\label</span>{eqn:legendre}                              
<span class="enscript-keyword">\end</span>{equation}

<span class="enscript-keyword">\textbf</span>{Proof.} <span class="enscript-keyword">\textit</span>{Equation <span class="enscript-keyword">\ref</span>{eqn:legendre} correctly identifies the residue status of an integer <span class="enscript-variable-name">$a$</span> modulo a prime <span class="enscript-variable-name">$p$</span>.}
An integer <span class="enscript-variable-name">$a$</span> is a quadratic residue if the following equation has a solution.

<span class="enscript-keyword">\begin</span>{equation}
x^2 <span class="enscript-keyword">\equiv</span> a <span class="enscript-keyword">\mbox</span>{ (mod }p<span class="enscript-keyword">\mbox</span>{)}
<span class="enscript-keyword">\label</span>{eqn:root}
<span class="enscript-keyword">\end</span>{equation}

Consider the following equation.

<span class="enscript-keyword">\begin</span>{equation}
0 <span class="enscript-keyword">\equiv</span> x^{p-1} - 1 <span class="enscript-keyword">\equiv</span> <span class="enscript-keyword">\left</span> <span class="enscript-keyword">\lbrace</span> <span class="enscript-keyword">\left</span> (x^2 <span class="enscript-keyword">\right</span> )^{(p-1)/2} - a^{(p-1)/2} <span class="enscript-keyword">\right</span> <span class="enscript-keyword">\rbrace</span> + <span class="enscript-keyword">\left</span> ( a^{(p-1)/2} - 1 <span class="enscript-keyword">\right</span> ) <span class="enscript-keyword">\mbox</span>{ (mod }p<span class="enscript-keyword">\mbox</span>{)}
<span class="enscript-keyword">\label</span>{eqn:rooti}
<span class="enscript-keyword">\end</span>{equation}

Whether equation <span class="enscript-keyword">\ref</span>{eqn:root} has a solution or not equation <span class="enscript-keyword">\ref</span>{eqn:rooti} is always true.  If <span class="enscript-variable-name">$a^{(p-1)/2} - 1 \equiv 0 \mbox{ (mod }p\mbox{)}$</span>
then the quantity in the braces must be zero.  By reduction,

<span class="enscript-keyword">\begin</span>{eqnarray}
<span class="enscript-keyword">\left</span> (x^2 <span class="enscript-keyword">\right</span> )^{(p-1)/2} - a^{(p-1)/2} <span class="enscript-keyword">\equiv</span> 0  <span class="enscript-keyword">\nonumber</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\left</span> (x^2 <span class="enscript-keyword">\right</span> )^{(p-1)/2} <span class="enscript-keyword">\equiv</span> a^{(p-1)/2} <span class="enscript-keyword">\nonumber</span> <span class="enscript-keyword">\\</span>
x^2 <span class="enscript-keyword">\equiv</span> a <span class="enscript-keyword">\mbox</span>{ (mod }p<span class="enscript-keyword">\mbox</span>{)} 
<span class="enscript-keyword">\end</span>{eqnarray}

As a result there must be a solution to the quadratic equation and in turn <span class="enscript-variable-name">$a$</span> must be a quadratic residue.  If <span class="enscript-variable-name">$a$</span> does not divide <span class="enscript-variable-name">$p$</span> and <span class="enscript-variable-name">$a$</span>
is not a quadratic residue then the only other value <span class="enscript-variable-name">$a^{(p-1)/2}$</span> may be congruent to is <span class="enscript-variable-name">$-1$</span> since
<span class="enscript-keyword">\begin</span>{equation}
0 <span class="enscript-keyword">\equiv</span> a^{p - 1} - 1 <span class="enscript-keyword">\equiv</span> (a^{(p-1)/2} + 1)(a^{(p-1)/2} - 1) <span class="enscript-keyword">\mbox</span>{ (mod }p<span class="enscript-keyword">\mbox</span>{)}
<span class="enscript-keyword">\end</span>{equation}
One of the terms on the right hand side must be zero.  <span class="enscript-keyword">\textbf</span>{QED}

<span class="enscript-keyword">\subsection</span>{Jacobi Symbol}
The Jacobi symbol is a generalization of the Legendre function for any odd non prime moduli <span class="enscript-variable-name">$p$</span> greater than 2.  If <span class="enscript-variable-name">$p = \prod_{i=0}^n p_i$</span> then
the Jacobi symbol <span class="enscript-variable-name">$\left ( { a \over p } \right )$</span> is equal to the following equation.

<span class="enscript-keyword">\begin</span>{equation}
<span class="enscript-keyword">\left</span> ( { a <span class="enscript-keyword">\over</span> p } <span class="enscript-keyword">\right</span> ) = <span class="enscript-keyword">\left</span> ( { a <span class="enscript-keyword">\over</span> p_0} <span class="enscript-keyword">\right</span> ) <span class="enscript-keyword">\left</span> ( { a <span class="enscript-keyword">\over</span> p_1} <span class="enscript-keyword">\right</span> ) <span class="enscript-keyword">\ldots</span> <span class="enscript-keyword">\left</span> ( { a <span class="enscript-keyword">\over</span> p_n} <span class="enscript-keyword">\right</span> )
<span class="enscript-keyword">\end</span>{equation}

By inspection if <span class="enscript-variable-name">$p$</span> is prime the Jacobi symbol is equivalent to the Legendre function.  The following facts<span class="enscript-keyword">\footnote</span>{See HAC <span class="enscript-keyword">\cite</span>[pp. 72-74]{HAC} for
further details.} will be used to derive an efficient Jacobi symbol algorithm.  Where <span class="enscript-variable-name">$p$</span> is an odd integer greater than two and <span class="enscript-variable-name">$a, b \in \Z$</span> the
following are true.  

<span class="enscript-keyword">\begin</span>{enumerate}
<span class="enscript-keyword">\item</span> <span class="enscript-variable-name">$\left ( { a \over p} \right )$</span> equals <span class="enscript-variable-name">$-1$</span>, <span class="enscript-variable-name">$0$</span> or <span class="enscript-variable-name">$1$</span>. 
<span class="enscript-keyword">\item</span> <span class="enscript-variable-name">$\left ( { ab \over p} \right ) = \left ( { a \over p} \right )\left ( { b \over p} \right )$</span>.
<span class="enscript-keyword">\item</span> If <span class="enscript-variable-name">$a \equiv b$</span> then <span class="enscript-variable-name">$\left ( { a \over p} \right ) = \left ( { b \over p} \right )$</span>.
<span class="enscript-keyword">\item</span> <span class="enscript-variable-name">$\left ( { 2 \over p} \right )$</span> equals <span class="enscript-variable-name">$1$</span> if <span class="enscript-variable-name">$p \equiv 1$</span> or <span class="enscript-variable-name">$7 \mbox{ (mod }8\mbox{)}$</span>.  Otherwise, it equals <span class="enscript-variable-name">$-1$</span>.
<span class="enscript-keyword">\item</span> <span class="enscript-variable-name">$\left ( { a \over p} \right ) \equiv \left ( { p \over a} \right ) \cdot (-1)^{(p-1)(a-1)/4}$</span>.  More specifically 
<span class="enscript-variable-name">$\left ( { a \over p} \right ) = \left ( { p \over a} \right )$</span> if <span class="enscript-variable-name">$p \equiv a \equiv 1 \mbox{ (mod }4\mbox{)}$</span>.  
<span class="enscript-keyword">\end</span>{enumerate}

Using these facts if <span class="enscript-variable-name">$a = 2^k \cdot a'$</span> then

<span class="enscript-keyword">\begin</span>{eqnarray}
<span class="enscript-keyword">\left</span> ( { a <span class="enscript-keyword">\over</span> p } <span class="enscript-keyword">\right</span> ) = <span class="enscript-keyword">\left</span> ( {{2^k} <span class="enscript-keyword">\over</span> p } <span class="enscript-keyword">\right</span> ) <span class="enscript-keyword">\left</span> ( {a' <span class="enscript-keyword">\over</span> p} <span class="enscript-keyword">\right</span> ) <span class="enscript-keyword">\nonumber</span> <span class="enscript-keyword">\\</span>
                               = <span class="enscript-keyword">\left</span> ( {2 <span class="enscript-keyword">\over</span> p } <span class="enscript-keyword">\right</span> )^k <span class="enscript-keyword">\left</span> ( {a' <span class="enscript-keyword">\over</span> p} <span class="enscript-keyword">\right</span> ) 
<span class="enscript-keyword">\label</span>{eqn:jacobi}
<span class="enscript-keyword">\end</span>{eqnarray}

By fact five, 

<span class="enscript-keyword">\begin</span>{equation}
<span class="enscript-keyword">\left</span> ( { a <span class="enscript-keyword">\over</span> p } <span class="enscript-keyword">\right</span> ) = <span class="enscript-keyword">\left</span> ( { p <span class="enscript-keyword">\over</span> a } <span class="enscript-keyword">\right</span> ) <span class="enscript-keyword">\cdot</span> (-1)^{(p-1)(a-1)/4} 
<span class="enscript-keyword">\end</span>{equation}

Subsequently by fact three since <span class="enscript-variable-name">$p \equiv (p \mbox{ mod }a) \mbox{ (mod }a\mbox{)}$</span> then 

<span class="enscript-keyword">\begin</span>{equation}
<span class="enscript-keyword">\left</span> ( { a <span class="enscript-keyword">\over</span> p } <span class="enscript-keyword">\right</span> ) = <span class="enscript-keyword">\left</span> ( { {p <span class="enscript-keyword">\mbox</span>{ mod } a} <span class="enscript-keyword">\over</span> a } <span class="enscript-keyword">\right</span> ) <span class="enscript-keyword">\cdot</span> (-1)^{(p-1)(a-1)/4} 
<span class="enscript-keyword">\end</span>{equation}

By putting both observations into equation <span class="enscript-keyword">\ref</span>{eqn:jacobi} the following simplified equation is formed.

<span class="enscript-keyword">\begin</span>{equation}
<span class="enscript-keyword">\left</span> ( { a <span class="enscript-keyword">\over</span> p } <span class="enscript-keyword">\right</span> ) = <span class="enscript-keyword">\left</span> ( {2 <span class="enscript-keyword">\over</span> p } <span class="enscript-keyword">\right</span> )^k <span class="enscript-keyword">\left</span> ( {{p<span class="enscript-keyword">\mbox</span>{ mod }a'} <span class="enscript-keyword">\over</span> a'} <span class="enscript-keyword">\right</span> )  <span class="enscript-keyword">\cdot</span> (-1)^{(p-1)(a'-1)/4} 
<span class="enscript-keyword">\end</span>{equation}

The value of <span class="enscript-variable-name">$\left ( {{p \mbox{ mod }a'} \over a'} \right )$</span> can be found by using the same equation recursively.  The value of 
<span class="enscript-variable-name">$\left ( {2 \over p } \right )^k$</span> equals <span class="enscript-variable-name">$1$</span> if <span class="enscript-variable-name">$k$</span> is even otherwise it equals <span class="enscript-variable-name">$\left ( {2 \over p } \right )$</span>.  Using this approach the 
factors of <span class="enscript-variable-name">$p$</span> do not have to be known.  Furthermore, if <span class="enscript-variable-name">$(a, p) = 1$</span> then the algorithm will terminate when the recursion requests the 
Jacobi symbol computation of <span class="enscript-variable-name">$\left ( {1 \over a'} \right )$</span> which is simply <span class="enscript-variable-name">$1$</span>.  

<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>jacobi}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$p$</span>, <span class="enscript-variable-name">$a \ge 0$</span>, <span class="enscript-variable-name">$p \ge 3$</span>, <span class="enscript-variable-name">$p \equiv 1 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The Jacobi symbol <span class="enscript-variable-name">$c = \left ( {a \over p } \right )$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$a = 0$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$c \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$a = 1$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$c \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.2  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$a' \leftarrow a$</span> <span class="enscript-keyword">\\</span>
4.  <span class="enscript-variable-name">$k \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
5.  While <span class="enscript-variable-name">$a'.used &gt; 0$</span> and <span class="enscript-variable-name">$a'_0 \equiv 0 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.1  <span class="enscript-variable-name">$k \leftarrow k + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}5.2  <span class="enscript-variable-name">$a' \leftarrow \lfloor a' / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
6.  If <span class="enscript-variable-name">$k \equiv 0 \mbox{ (mod }2\mbox{)}$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$s \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
7.  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  <span class="enscript-variable-name">$r \leftarrow p_0 \mbox{ (mod }8\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.2  If <span class="enscript-variable-name">$r = 1$</span> or <span class="enscript-variable-name">$r = 7$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.2.1  <span class="enscript-variable-name">$s \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.3  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.3.1  <span class="enscript-variable-name">$s \leftarrow -1$</span> <span class="enscript-keyword">\\</span>
8.  If <span class="enscript-variable-name">$p_0 \equiv a'_0 \equiv 3 \mbox{ (mod }4\mbox{)}$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  <span class="enscript-variable-name">$s \leftarrow -s$</span> <span class="enscript-keyword">\\</span>
9.  If <span class="enscript-variable-name">$a' \ne 1$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.1  <span class="enscript-variable-name">$p' \leftarrow p \mbox{ (mod }a'\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.2  <span class="enscript-variable-name">$s \leftarrow s \cdot \mbox{mp\_jacobi}(p', a')$</span> <span class="enscript-keyword">\\</span>
10.  <span class="enscript-variable-name">$c \leftarrow s$</span> <span class="enscript-keyword">\\</span>
11.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>jacobi}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>jacobi.}
This algorithm computes the Jacobi symbol for an arbitrary positive integer <span class="enscript-variable-name">$a$</span> with respect to an odd integer <span class="enscript-variable-name">$p$</span> greater than three.  The algorithm
is based on algorithm 2.149 of HAC <span class="enscript-keyword">\cite</span>[pp. 73]{HAC}.  

Step numbers one and two handle the trivial cases of <span class="enscript-variable-name">$a = 0$</span> and <span class="enscript-variable-name">$a = 1$</span> respectively.  Step five determines the number of two factors in the
input <span class="enscript-variable-name">$a$</span>.  If <span class="enscript-variable-name">$k$</span> is even than the term <span class="enscript-variable-name">$\left ( { 2 \over p } \right )^k$</span> must always evaluate to one.  If <span class="enscript-variable-name">$k$</span> is odd than the term evaluates to one 
if <span class="enscript-variable-name">$p_0$</span> is congruent to one or seven modulo eight, otherwise it evaluates to <span class="enscript-variable-name">$-1$</span>. After the the <span class="enscript-variable-name">$\left ( { 2 \over p } \right )^k$</span> term is handled 
the <span class="enscript-variable-name">$(-1)^{(p-1)(a'-1)/4}$</span> is computed and multiplied against the current product <span class="enscript-variable-name">$s$</span>.  The latter term evaluates to one if both <span class="enscript-variable-name">$p$</span> and <span class="enscript-variable-name">$a'$</span> 
are congruent to one modulo four, otherwise it evaluates to negative one.

By step nine if <span class="enscript-variable-name">$a'$</span> does not equal one a recursion is required.  Step 9.1 computes <span class="enscript-variable-name">$p' \equiv p \mbox{ (mod }a'\mbox{)}$</span> and will recurse to compute
<span class="enscript-variable-name">$\left ( {p' \over a'} \right )$</span> which is multiplied against the current Jacobi product.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>jacobi.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

As a matter of practicality the variable <span class="enscript-variable-name">$a'$</span> as per the pseudo-code is reprensented by the variable <span class="enscript-variable-name">$a1$</span> since the <span class="enscript-variable-name">$'$</span> symbol is not valid for a C 
variable name character. 

The two simple cases of <span class="enscript-variable-name">$a = 0$</span> and <span class="enscript-variable-name">$a = 1$</span> are handled at the very beginning to simplify the algorithm.  If the input is non-trivial the algorithm
has to proceed compute the Jacobi.  The variable <span class="enscript-variable-name">$s$</span> is used to hold the current Jacobi product.  Note that <span class="enscript-variable-name">$s$</span> is merely a C ``int'' data type since
the values it may obtain are merely <span class="enscript-variable-name">$-1$</span>, <span class="enscript-variable-name">$0$</span> and <span class="enscript-variable-name">$1$</span>.  

After a local copy of <span class="enscript-variable-name">$a$</span> is made all of the factors of two are divided out and the total stored in <span class="enscript-variable-name">$k$</span>.  Technically only the least significant
bit of <span class="enscript-variable-name">$k$</span> is required, however, it makes the algorithm simpler to follow to perform an addition. In practice an exclusive-or and addition have the same 
processor requirements and neither is faster than the other.

Line 58 through 71 determines the value of <span class="enscript-variable-name">$\left ( { 2 \over p } \right )^k$</span>.  If the least significant bit of <span class="enscript-variable-name">$k$</span> is zero than
<span class="enscript-variable-name">$k$</span> is even and the value is one.  Otherwise, the value of <span class="enscript-variable-name">$s$</span> depends on which residue class <span class="enscript-variable-name">$p$</span> belongs to modulo eight.  The value of
<span class="enscript-variable-name">$(-1)^{(p-1)(a'-1)/4}$</span> is compute and multiplied against <span class="enscript-variable-name">$s$</span> on lines 71 through 74.  

Finally, if <span class="enscript-variable-name">$a1$</span> does not equal one the algorithm must recurse and compute <span class="enscript-variable-name">$\left ( {p' \over a'} \right )$</span>.  

<span class="enscript-keyword">\textit</span>{-- Comment about default <span class="enscript-variable-name">$s$</span> and such...}

<span class="enscript-keyword">\section</span>{Modular Inverse}
<span class="enscript-keyword">\label</span>{sec:modinv}
The modular inverse of a number actually refers to the modular multiplicative inverse.  Essentially for any integer <span class="enscript-variable-name">$a$</span> such that <span class="enscript-variable-name">$(a, p) = 1$</span> there
exist another integer <span class="enscript-variable-name">$b$</span> such that <span class="enscript-variable-name">$ab \equiv 1 \mbox{ (mod }p\mbox{)}$</span>.  The integer <span class="enscript-variable-name">$b$</span> is called the multiplicative inverse of <span class="enscript-variable-name">$a$</span> which is
denoted as <span class="enscript-variable-name">$b = a^{-1}$</span>.  Technically speaking modular inversion is a well defined operation for any finite ring or field not just for rings and 
fields of integers.  However, the former will be the matter of discussion.

The simplest approach is to compute the algebraic inverse of the input.  That is to compute <span class="enscript-variable-name">$b \equiv a^{\Phi(p) - 1}$</span>.  If <span class="enscript-variable-name">$\Phi(p)$</span> is the 
order of the multiplicative subgroup modulo <span class="enscript-variable-name">$p$</span> then <span class="enscript-variable-name">$b$</span> must be the multiplicative inverse of <span class="enscript-variable-name">$a$</span>.  The proof of which is trivial.

<span class="enscript-keyword">\begin</span>{equation}
ab <span class="enscript-keyword">\equiv</span> a <span class="enscript-keyword">\left</span> (a^{<span class="enscript-keyword">\Phi</span>(p) - 1} <span class="enscript-keyword">\right</span> ) <span class="enscript-keyword">\equiv</span> a^{<span class="enscript-keyword">\Phi</span>(p)} <span class="enscript-keyword">\equiv</span> a^0 <span class="enscript-keyword">\equiv</span> 1 <span class="enscript-keyword">\mbox</span>{ (mod }p<span class="enscript-keyword">\mbox</span>{)}
<span class="enscript-keyword">\end</span>{equation}

However, as simple as this approach may be it has two serious flaws.  It requires that the value of <span class="enscript-variable-name">$\Phi(p)$</span> be known which if <span class="enscript-variable-name">$p$</span> is composite 
requires all of the prime factors.  This approach also is very slow as the size of <span class="enscript-variable-name">$p$</span> grows.  

A simpler approach is based on the observation that solving for the multiplicative inverse is equivalent to solving the linear 
Diophantine<span class="enscript-keyword">\footnote</span>{See LeVeque <span class="enscript-keyword">\cite</span>[pp. 40-43]{LeVeque} for more information.} equation.

<span class="enscript-keyword">\begin</span>{equation}
ab + pq = 1
<span class="enscript-keyword">\end</span>{equation}

Where <span class="enscript-variable-name">$a$</span>, <span class="enscript-variable-name">$b$</span>, <span class="enscript-variable-name">$p$</span> and <span class="enscript-variable-name">$q$</span> are all integers.  If such a pair of integers <span class="enscript-variable-name">$ \left &lt; b, q \right &gt;$</span> exist than <span class="enscript-variable-name">$b$</span> is the multiplicative inverse of 
<span class="enscript-variable-name">$a$</span> modulo <span class="enscript-variable-name">$p$</span>.  The extended Euclidean algorithm (Knuth <span class="enscript-keyword">\cite</span>[pp. 342]{TAOCPV2}) can be used to solve such equations provided <span class="enscript-variable-name">$(a, p) = 1$</span>.  
However, instead of using that algorithm directly a variant known as the binary Extended Euclidean algorithm will be used in its place.  The
binary approach is very similar to the binary greatest common divisor algorithm except it will produce a full solution to the Diophantine 
equation.  

<span class="enscript-keyword">\subsection</span>{General Case}
<span class="enscript-keyword">\newpage</span><span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>invmod}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>, <span class="enscript-variable-name">$(a, b) = 1$</span>, <span class="enscript-variable-name">$p \ge 2$</span>, <span class="enscript-variable-name">$0 &lt; a &lt; p$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  The modular inverse <span class="enscript-variable-name">$c \equiv a^{-1} \mbox{ (mod }b\mbox{)}$</span>. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  If <span class="enscript-variable-name">$b \le 0$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}). <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$b_0 \equiv 1 \mbox{ (mod }2\mbox{)}$</span> then use algorithm fast<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>invmod. <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$x \leftarrow \vert a \vert, y \leftarrow b$</span> <span class="enscript-keyword">\\</span>
4.  If <span class="enscript-variable-name">$x_0 \equiv y_0  \equiv 0 \mbox{ (mod }2\mbox{)}$</span> then return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}). <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$B \leftarrow 0, C \leftarrow 0, A \leftarrow 1, D \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
6.  While <span class="enscript-variable-name">$u.used &gt; 0$</span> and <span class="enscript-variable-name">$u_0 \equiv 0 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$u \leftarrow \lfloor u / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  If (<span class="enscript-variable-name">$A.used &gt; 0$</span> and <span class="enscript-variable-name">$A_0 \equiv 1 \mbox{ (mod }2\mbox{)}$</span>) or (<span class="enscript-variable-name">$B.used &gt; 0$</span> and <span class="enscript-variable-name">$B_0 \equiv 1 \mbox{ (mod }2\mbox{)}$</span>) then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.2.1  <span class="enscript-variable-name">$A \leftarrow A + y$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.2.2  <span class="enscript-variable-name">$B \leftarrow B - x$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.3  <span class="enscript-variable-name">$A \leftarrow \lfloor A / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.4  <span class="enscript-variable-name">$B \leftarrow \lfloor B / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
7.  While <span class="enscript-variable-name">$v.used &gt; 0$</span> and <span class="enscript-variable-name">$v_0 \equiv 0 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.1  <span class="enscript-variable-name">$v \leftarrow \lfloor v / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.2  If (<span class="enscript-variable-name">$C.used &gt; 0$</span> and <span class="enscript-variable-name">$C_0 \equiv 1 \mbox{ (mod }2\mbox{)}$</span>) or (<span class="enscript-variable-name">$D.used &gt; 0$</span> and <span class="enscript-variable-name">$D_0 \equiv 1 \mbox{ (mod }2\mbox{)}$</span>) then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.2.1  <span class="enscript-variable-name">$C \leftarrow C + y$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}7.2.2  <span class="enscript-variable-name">$D \leftarrow D - x$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.3  <span class="enscript-variable-name">$C \leftarrow \lfloor C / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}7.4  <span class="enscript-variable-name">$D \leftarrow \lfloor D / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
8.  If <span class="enscript-variable-name">$u \ge v$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.1  <span class="enscript-variable-name">$u \leftarrow u - v$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.2  <span class="enscript-variable-name">$A \leftarrow A - C$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}8.3  <span class="enscript-variable-name">$B \leftarrow B - D$</span> <span class="enscript-keyword">\\</span>
9.  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.1  <span class="enscript-variable-name">$v \leftarrow v - u$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.2  <span class="enscript-variable-name">$C \leftarrow C - A$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}9.3  <span class="enscript-variable-name">$D \leftarrow D - B$</span> <span class="enscript-keyword">\\</span>
10.  If <span class="enscript-variable-name">$u \ne 0$</span> goto step 6. <span class="enscript-keyword">\\</span>
11.  If <span class="enscript-variable-name">$v \ne 1$</span> return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>VAL}). <span class="enscript-keyword">\\</span>
12.  While <span class="enscript-variable-name">$C \le 0$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}12.1  <span class="enscript-variable-name">$C \leftarrow C + b$</span> <span class="enscript-keyword">\\</span>
13.  While <span class="enscript-variable-name">$C \ge b$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}13.1  <span class="enscript-variable-name">$C \leftarrow C - b$</span> <span class="enscript-keyword">\\</span>
14.  <span class="enscript-variable-name">$c \leftarrow C$</span> <span class="enscript-keyword">\\</span>
15.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>invmod.}
This algorithm computes the modular multiplicative inverse of an integer <span class="enscript-variable-name">$a$</span> modulo an integer <span class="enscript-variable-name">$b$</span>.  This algorithm is a variation of the 
extended binary Euclidean algorithm from HAC <span class="enscript-keyword">\cite</span>[pp. 608]{HAC}.  It has been modified to only compute the modular inverse and not a complete
Diophantine solution.  

If <span class="enscript-variable-name">$b \le 0$</span> than the modulus is invalid and MP<span class="enscript-keyword">\_</span>VAL is returned.  Similarly if both <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> are even then there cannot be a multiplicative
inverse for <span class="enscript-variable-name">$a$</span> and the error is reported.  

The astute reader will observe that steps seven through nine are very similar to the binary greatest common divisor algorithm mp<span class="enscript-keyword">\_</span>gcd.  In this case
the other variables to the Diophantine equation are solved.  The algorithm terminates when <span class="enscript-variable-name">$u = 0$</span> in which case the solution is

<span class="enscript-keyword">\begin</span>{equation}
Ca + Db = v
<span class="enscript-keyword">\end</span>{equation}

If <span class="enscript-variable-name">$v$</span>, the greatest common divisor of <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span> is not equal to one then the algorithm will report an error as no inverse exists.  Otherwise, <span class="enscript-variable-name">$C$</span>
is the modular inverse of <span class="enscript-variable-name">$a$</span>.  The actual value of <span class="enscript-variable-name">$C$</span> is congruent to, but not necessarily equal to, the ideal modular inverse which should lie 
within <span class="enscript-variable-name">$1 \le a^{-1} &lt; b$</span>.  Step numbers twelve and thirteen adjust the inverse until it is in range.  If the original input <span class="enscript-variable-name">$a$</span> is within <span class="enscript-variable-name">$0 &lt; a &lt; p$</span> 
then only a couple of additions or subtractions will be required to adjust the inverse.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>invmod.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\subsubsection</span>{Odd Moduli}

When the modulus <span class="enscript-variable-name">$b$</span> is odd the variables <span class="enscript-variable-name">$A$</span> and <span class="enscript-variable-name">$C$</span> are fixed and are not required to compute the inverse.  In particular by attempting to solve
the Diophantine <span class="enscript-variable-name">$Cb + Da = 1$</span> only <span class="enscript-variable-name">$B$</span> and <span class="enscript-variable-name">$D$</span> are required to find the inverse of <span class="enscript-variable-name">$a$</span>.  

The algorithm fast<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>invmod is a direct adaptation of algorithm mp<span class="enscript-keyword">\_</span>invmod with all all steps involving either <span class="enscript-variable-name">$A$</span> or <span class="enscript-variable-name">$C$</span> removed.  This 
optimization will halve the time required to compute the modular inverse.

<span class="enscript-keyword">\section</span>{Primality Tests}

A non-zero integer <span class="enscript-variable-name">$a$</span> is said to be prime if it is not divisible by any other integer excluding one and itself.  For example, <span class="enscript-variable-name">$a = 7$</span> is prime 
since the integers <span class="enscript-variable-name">$2 \ldots 6$</span> do not evenly divide <span class="enscript-variable-name">$a$</span>.  By contrast, <span class="enscript-variable-name">$a = 6$</span> is not prime since <span class="enscript-variable-name">$a = 6 = 2 \cdot 3$</span>. 

Prime numbers arise in cryptography considerably as they allow finite fields to be formed.  The ability to determine whether an integer is prime or
not quickly has been a viable subject in cryptography and number theory for considerable time.  The algorithms that will be presented are all
probablistic algorithms in that when they report an integer is composite it must be composite.  However, when the algorithms report an integer is
prime the algorithm may be incorrect.  

As will be discussed it is possible to limit the probability of error so well that for practical purposes the probablity of error might as 
well be zero.  For the purposes of these discussions let <span class="enscript-variable-name">$n$</span> represent the candidate integer of which the primality is in question.

<span class="enscript-keyword">\subsection</span>{Trial Division}

Trial division means to attempt to evenly divide a candidate integer by small prime integers.  If the candidate can be evenly divided it obviously
cannot be prime.  By dividing by all primes <span class="enscript-variable-name">$1 &lt; p \le \sqrt{n}$</span> this test can actually prove whether an integer is prime.  However, such a test
would require a prohibitive amount of time as <span class="enscript-variable-name">$n$</span> grows.

Instead of dividing by every prime, a smaller, more mangeable set of primes may be used instead.  By performing trial division with only a subset
of the primes less than <span class="enscript-variable-name">$\sqrt{n} + 1$</span> the algorithm cannot prove if a candidate is prime.  However, often it can prove a candidate is not prime.

The benefit of this test is that trial division by small values is fairly efficient.  Specially compared to the other algorithms that will be
discussed shortly.  The probability that this approach correctly identifies a composite candidate when tested with all primes upto <span class="enscript-variable-name">$q$</span> is given by
<span class="enscript-variable-name">$1 - {1.12 \over ln(q)}$</span>.  The graph (<span class="enscript-keyword">\ref</span>{pic:primality}, will be added later) demonstrates the probability of success for the range 
<span class="enscript-variable-name">$3 \le q \le 100$</span>.  

At approximately <span class="enscript-variable-name">$q = 30$</span> the gain of performing further tests diminishes fairly quickly.  At <span class="enscript-variable-name">$q = 90$</span> further testing is generally not going to 
be of any practical use.  In the case of LibTomMath the default limit <span class="enscript-variable-name">$q = 256$</span> was chosen since it is not too high and will eliminate 
approximately <span class="enscript-variable-name">$80\%$</span> of all candidate integers.  The constant <span class="enscript-keyword">\textbf</span>{PRIME<span class="enscript-keyword">\_</span>SIZE} is equal to the number of primes in the test base.  The 
array <span class="enscript-keyword">\_</span><span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>tab is an array of the first <span class="enscript-keyword">\textbf</span>{PRIME<span class="enscript-keyword">\_</span>SIZE} prime numbers.  

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>divisible}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = 1$</span> if <span class="enscript-variable-name">$n$</span> is divisible by a small prime, otherwise <span class="enscript-variable-name">$c = 0$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  for <span class="enscript-variable-name">$ix$</span> from <span class="enscript-variable-name">$0$</span> to <span class="enscript-variable-name">$PRIME\_SIZE$</span> do <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.1  <span class="enscript-variable-name">$d \leftarrow n \mbox{ (mod }\_\_prime\_tab_{ix}\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}1.2  If <span class="enscript-variable-name">$d = 0$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}1.2.1  <span class="enscript-variable-name">$c \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}1.2.2  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$c \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
3.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>divisible}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>divisible.}
This algorithm attempts to determine if a candidate integer <span class="enscript-variable-name">$n$</span> is composite by performing trial divisions.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>is<span class="enscript-keyword">\_</span>divisible.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

The algorithm defaults to a return of <span class="enscript-variable-name">$0$</span> in case an error occurs.  The values in the prime table are all specified to be in the range of a 
mp<span class="enscript-keyword">\_</span>digit.  The table <span class="enscript-keyword">\_</span><span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>tab is defined in the following file.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>tab.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

Note that there are two possible tables.  When an mp<span class="enscript-keyword">\_</span>digit is 7-bits long only the primes upto <span class="enscript-variable-name">$127$</span> may be included, otherwise the primes
upto <span class="enscript-variable-name">$1619$</span> are used.  Note that the value of <span class="enscript-keyword">\textbf</span>{PRIME<span class="enscript-keyword">\_</span>SIZE} is a constant dependent on the size of a mp<span class="enscript-keyword">\_</span>digit. 

<span class="enscript-keyword">\subsection</span>{The Fermat Test}
The Fermat test is probably one the oldest tests to have a non-trivial probability of success.  It is based on the fact that if <span class="enscript-variable-name">$n$</span> is in 
fact prime then <span class="enscript-variable-name">$a^{n} \equiv a \mbox{ (mod }n\mbox{)}$</span> for all <span class="enscript-variable-name">$0 &lt; a &lt; n$</span>.  The reason being that if <span class="enscript-variable-name">$n$</span> is prime than the order of
the multiplicative sub group is <span class="enscript-variable-name">$n - 1$</span>.  Any base <span class="enscript-variable-name">$a$</span> must have an order which divides <span class="enscript-variable-name">$n - 1$</span> and as such <span class="enscript-variable-name">$a^n$</span> is equivalent to 
<span class="enscript-variable-name">$a^1 = a$</span>.  

If <span class="enscript-variable-name">$n$</span> is composite then any given base <span class="enscript-variable-name">$a$</span> does not have to have a period which divides <span class="enscript-variable-name">$n - 1$</span>.  In which case 
it is possible that <span class="enscript-variable-name">$a^n \nequiv a \mbox{ (mod }n\mbox{)}$</span>.  However, this test is not absolute as it is possible that the order
of a base will divide <span class="enscript-variable-name">$n - 1$</span> which would then be reported as prime.  Such a base yields what is known as a Fermat pseudo-prime.  Several 
integers known as Carmichael numbers will be a pseudo-prime to all valid bases.  Fortunately such numbers are extremely rare as <span class="enscript-variable-name">$n$</span> grows
in size.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>fermat}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>, <span class="enscript-variable-name">$a \ge 2$</span>, <span class="enscript-variable-name">$0 &lt; b &lt; a$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = 1$</span> if <span class="enscript-variable-name">$b^a \equiv b \mbox{ (mod }a\mbox{)}$</span>, otherwise <span class="enscript-variable-name">$c = 0$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span> <span class="enscript-keyword">\\</span>
1.  <span class="enscript-variable-name">$t \leftarrow b^a \mbox{ (mod }a\mbox{)}$</span> <span class="enscript-keyword">\\</span>
2.  If <span class="enscript-variable-name">$t = b$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}2.1  <span class="enscript-variable-name">$c = 1$</span> <span class="enscript-keyword">\\</span>
3.  else <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}3.1  <span class="enscript-variable-name">$c = 0$</span> <span class="enscript-keyword">\\</span>
4.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>fermat}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>fermat.}
This algorithm determines whether an mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> is a Fermat prime to the base <span class="enscript-variable-name">$b$</span> or not.  It uses a single modular exponentiation to
determine the result.  

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>fermat.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}

<span class="enscript-keyword">\subsection</span>{The Miller-Rabin Test}
The Miller-Rabin (citation) test is another primality test which has tighter error bounds than the Fermat test specifically with sequentially chosen 
candidate  integers.  The algorithm is based on the observation that if <span class="enscript-variable-name">$n - 1 = 2^kr$</span> and if <span class="enscript-variable-name">$b^r \nequiv \pm 1$</span> then after upto <span class="enscript-variable-name">$k - 1$</span> squarings the 
value must be equal to <span class="enscript-variable-name">$-1$</span>.  The squarings are stopped as soon as <span class="enscript-variable-name">$-1$</span> is observed.  If the value of <span class="enscript-variable-name">$1$</span> is observed first it means that
some value not congruent to <span class="enscript-variable-name">$\pm 1$</span> when squared equals one which cannot occur if <span class="enscript-variable-name">$n$</span> is prime.

<span class="enscript-keyword">\begin</span>{figure}[!here]
<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\begin</span>{center}
<span class="enscript-keyword">\begin</span>{tabular}{l}
<span class="enscript-keyword">\hline</span> Algorithm <span class="enscript-keyword">\textbf</span>{mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>miller<span class="enscript-keyword">\_</span>rabin}. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Input}.   mp<span class="enscript-keyword">\_</span>int <span class="enscript-variable-name">$a$</span> and <span class="enscript-variable-name">$b$</span>, <span class="enscript-variable-name">$a \ge 2$</span>, <span class="enscript-variable-name">$0 &lt; b &lt; a$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\textbf</span>{Output}.  <span class="enscript-variable-name">$c = 1$</span> if <span class="enscript-variable-name">$a$</span> is a Miller-Rabin prime to the base <span class="enscript-variable-name">$a$</span>, otherwise <span class="enscript-variable-name">$c = 0$</span>.  <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
1.  <span class="enscript-variable-name">$a' \leftarrow a - 1$</span> <span class="enscript-keyword">\\</span>
2.  <span class="enscript-variable-name">$r  \leftarrow n1$</span>    <span class="enscript-keyword">\\</span>
3.  <span class="enscript-variable-name">$c \leftarrow 0, s  \leftarrow 0$</span> <span class="enscript-keyword">\\</span>
4.  While <span class="enscript-variable-name">$r.used &gt; 0$</span> and <span class="enscript-variable-name">$r_0 \equiv 0 \mbox{ (mod }2\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.1  <span class="enscript-variable-name">$s \leftarrow s + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}4.2  <span class="enscript-variable-name">$r \leftarrow \lfloor r / 2 \rfloor$</span> <span class="enscript-keyword">\\</span>
5.  <span class="enscript-variable-name">$y \leftarrow b^r \mbox{ (mod }a\mbox{)}$</span> <span class="enscript-keyword">\\</span>
6.  If <span class="enscript-variable-name">$y \nequiv \pm 1$</span> then <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.1  <span class="enscript-variable-name">$j \leftarrow 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.2  While <span class="enscript-variable-name">$j \le (s - 1)$</span> and <span class="enscript-variable-name">$y \nequiv a'$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.2.1  <span class="enscript-variable-name">$y \leftarrow y^2 \mbox{ (mod }a\mbox{)}$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.2.2  If <span class="enscript-variable-name">$y = 1$</span> then goto step 8. <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{6mm}6.2.3  <span class="enscript-variable-name">$j \leftarrow j + 1$</span> <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hspace</span>{3mm}6.3  If <span class="enscript-variable-name">$y \nequiv a'$</span> goto step 8. <span class="enscript-keyword">\\</span>
7.  <span class="enscript-variable-name">$c \leftarrow 1$</span><span class="enscript-keyword">\\</span>
8.  Return(<span class="enscript-keyword">\textit</span>{MP<span class="enscript-keyword">\_</span>OKAY}). <span class="enscript-keyword">\\</span>
<span class="enscript-keyword">\hline</span>
<span class="enscript-keyword">\end</span>{tabular}
<span class="enscript-keyword">\end</span>{center}
<span class="enscript-keyword">\end</span>{small}
<span class="enscript-keyword">\caption</span>{Algorithm mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>miller<span class="enscript-keyword">\_</span>rabin}
<span class="enscript-keyword">\end</span>{figure}
<span class="enscript-keyword">\textbf</span>{Algorithm mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>miller<span class="enscript-keyword">\_</span>rabin.}
This algorithm performs one trial round of the Miller-Rabin algorithm to the base <span class="enscript-variable-name">$b$</span>.  It will set <span class="enscript-variable-name">$c = 1$</span> if the algorithm cannot determine
if <span class="enscript-variable-name">$b$</span> is composite or <span class="enscript-variable-name">$c = 0$</span> if <span class="enscript-variable-name">$b$</span> is provably composite.  The values of <span class="enscript-variable-name">$s$</span> and <span class="enscript-variable-name">$r$</span> are computed such that <span class="enscript-variable-name">$a' = a - 1 = 2^sr$</span>.  

If the value <span class="enscript-variable-name">$y \equiv b^r$</span> is congruent to <span class="enscript-variable-name">$\pm 1$</span> then the algorithm cannot prove if <span class="enscript-variable-name">$a$</span> is composite or not.  Otherwise, the algorithm will
square <span class="enscript-variable-name">$y$</span> upto <span class="enscript-variable-name">$s - 1$</span> times stopping only when <span class="enscript-variable-name">$y \equiv -1$</span>.  If <span class="enscript-variable-name">$y^2 \equiv 1$</span> and <span class="enscript-variable-name">$y \nequiv \pm 1$</span> then the algorithm can report that <span class="enscript-variable-name">$a$</span>
is provably composite.  If the algorithm performs <span class="enscript-variable-name">$s - 1$</span> squarings and <span class="enscript-variable-name">$y \nequiv -1$</span> then <span class="enscript-variable-name">$a$</span> is provably composite.  If <span class="enscript-variable-name">$a$</span> is not provably 
composite then it is <span class="enscript-keyword">\textit</span>{probably} prime.

<span class="enscript-keyword">\vspace</span>{+3mm}<span class="enscript-keyword">\begin</span>{small}
<span class="enscript-keyword">\hspace</span>{-5.1mm}{<span class="enscript-keyword">\bf</span> File}: bn<span class="enscript-keyword">\_</span>mp<span class="enscript-keyword">\_</span>prime<span class="enscript-keyword">\_</span>miller<span class="enscript-keyword">\_</span>rabin.c
<span class="enscript-keyword">\vspace</span>{-3mm}
<span class="enscript-keyword">\begin</span>{alltt}
<span class="enscript-keyword">\end</span>{alltt}
<span class="enscript-keyword">\end</span>{small}




<span class="enscript-keyword">\backmatter</span>
<span class="enscript-keyword">\appendix</span>
<span class="enscript-keyword">\begin</span>{thebibliography}{ABCDEF}
<span class="enscript-keyword">\bibitem</span>[1]{TAOCPV2}
Donald Knuth, <span class="enscript-keyword">\textit</span>{The Art of Computer Programming}, Third Edition, Volume Two, Seminumerical Algorithms, Addison-Wesley, 1998

<span class="enscript-keyword">\bibitem</span>[2]{HAC}
A. Menezes, P. van Oorschot, S. Vanstone, <span class="enscript-keyword">\textit</span>{Handbook of Applied Cryptography}, CRC Press, 1996

<span class="enscript-keyword">\bibitem</span>[3]{ROSE}
Michael Rosing, <span class="enscript-keyword">\textit</span>{Implementing Elliptic Curve Cryptography}, Manning Publications, 1999

<span class="enscript-keyword">\bibitem</span>[4]{COMBA}
Paul G. Comba, <span class="enscript-keyword">\textit</span>{Exponentiation Cryptosystems on the IBM PC}. IBM Systems Journal 29(4): 526-538 (1990)

<span class="enscript-keyword">\bibitem</span>[5]{KARA}
A. Karatsuba, Doklay Akad. Nauk SSSR 145 (1962), pp.293-294

<span class="enscript-keyword">\bibitem</span>[6]{KARAP}
Andre Weimerskirch and Christof Paar, <span class="enscript-keyword">\textit</span>{Generalizations of the Karatsuba Algorithm for Polynomial Multiplication}, Submitted to Design, Codes and Cryptography, March 2002

<span class="enscript-keyword">\bibitem</span>[7]{BARRETT}
Paul Barrett, <span class="enscript-keyword">\textit</span>{Implementing the Rivest Shamir and Adleman Public Key Encryption Algorithm on a Standard Digital Signal Processor}, Advances in Cryptology, Crypto '86, Springer-Verlag.

<span class="enscript-keyword">\bibitem</span>[8]{MONT}
P.L.Montgomery. <span class="enscript-keyword">\textit</span>{Modular multiplication without trial division}. Mathematics of Computation, 44(170):519-521, April 1985.

<span class="enscript-keyword">\bibitem</span>[9]{DRMET}
Chae Hoon Lim and Pil Joong Lee, <span class="enscript-keyword">\textit</span>{Generating Efficient Primes for Discrete Log Cryptosystems}, POSTECH Information Research Laboratories

<span class="enscript-keyword">\bibitem</span>[10]{MMB}
J. Daemen and R. Govaerts and J. Vandewalle, <span class="enscript-keyword">\textit</span>{Block ciphers based on Modular Arithmetic}, State and {P}rogress in the {R}esearch of {C}ryptography, 1993, pp. 80-89

<span class="enscript-keyword">\bibitem</span>[11]{RSAREF}
R.L. Rivest, A. Shamir, L. Adleman, <span class="enscript-keyword">\textit</span>{A Method for Obtaining Digital Signatures and Public-Key Cryptosystems}

<span class="enscript-keyword">\bibitem</span>[12]{DHREF}
Whitfield Diffie, Martin E. Hellman, <span class="enscript-keyword">\textit</span>{New Directions in Cryptography}, IEEE Transactions on Information Theory, 1976

<span class="enscript-keyword">\bibitem</span>[13]{IEEE}
IEEE Standard for Binary Floating-Point Arithmetic (ANSI/IEEE Std 754-1985)

<span class="enscript-keyword">\bibitem</span>[14]{GMP}
GNU Multiple Precision (GMP), <span class="enscript-keyword">\url</span>{<a href="http://www.swox.com/gmp/">http://www.swox.com/gmp/</a>}

<span class="enscript-keyword">\bibitem</span>[15]{MPI}
Multiple Precision Integer Library (MPI), Michael Fromberger, <span class="enscript-keyword">\url</span>{<a href="http://thayer.dartmouth.edu/~sting/mpi/">http://thayer.dartmouth.edu/~sting/mpi/</a>}

<span class="enscript-keyword">\bibitem</span>[16]{OPENSSL}
OpenSSL Cryptographic Toolkit, <span class="enscript-keyword">\url</span>{<a href="http://openssl.org">http://openssl.org</a>}

<span class="enscript-keyword">\bibitem</span>[17]{LIP}
Large Integer Package, <span class="enscript-keyword">\url</span>{<a href="http://home.hetnet.nl/~ecstr/LIP.zip">http://home.hetnet.nl/~ecstr/LIP.zip</a>}

<span class="enscript-keyword">\bibitem</span>[18]{ISOC}
JTC1/SC22/WG14, ISO/IEC 9899:1999, ``A draft rationale for the C99 standard.''

<span class="enscript-keyword">\bibitem</span>[19]{JAVA}
The Sun Java Website, <span class="enscript-keyword">\url</span>{<a href="http://java.sun.com/">http://java.sun.com/</a>}

<span class="enscript-keyword">\end</span>{thebibliography}

<span class="enscript-keyword">\input</span>{tommath.ind}

<span class="enscript-keyword">\end</span>{document}
</pre>
<hr />
</body></html>