Quantum Programming in QCL PDF
Quantum Programming in QCL PDF
Bernhard Omer
20th January 2000
E-mail: [email protected]
Homepage: http://tph.tuwien.ac.at/~oemer
Contents
2 Quantum Computers 22
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.1.1 The Church-Turing Thesis . . . . . . . . . . . . . . . . 22
2.1.2 Computing Machines . . . . . . . . . . . . . . . . . . . 23
2.1.3 Computation as a Physical Process . . . . . . . . . . . 24
2.2 Components of a Quantum Computer . . . . . . . . . . . . . . 25
2.2.1 Quantum Memory . . . . . . . . . . . . . . . . . . . . 25
2.2.2 Processing Units . . . . . . . . . . . . . . . . . . . . . 29
2.2.3 Input and Output . . . . . . . . . . . . . . . . . . . . . 34
2.3 Models of Quantum Computation . . . . . . . . . . . . . . . . 36
2.3.1 The Mathematical Model of QC . . . . . . . . . . . . . 36
2.3.2 Quantum Turing Machines . . . . . . . . . . . . . . . . 37
2.3.3 Quantum Circuits . . . . . . . . . . . . . . . . . . . . . 37
2.3.4 Quantum Programming Languages . . . . . . . . . . . 38
1
CONTENTS 2
3 Quantum Programming 41
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.1.1 Computers and Programming . . . . . . . . . . . . . . 41
3.1.2 Complexity Requirements . . . . . . . . . . . . . . . . 42
3.1.3 Hybrid Architecture . . . . . . . . . . . . . . . . . . . 42
3.2 QCL as a Classical Language . . . . . . . . . . . . . . . . . . 43
3.2.1 Structure of a QCL Program . . . . . . . . . . . . . . . 44
3.2.2 Data Types and Variables . . . . . . . . . . . . . . . . 44
3.2.3 Expressions . . . . . . . . . . . . . . . . . . . . . . . . 46
3.2.4 Simple Statements . . . . . . . . . . . . . . . . . . . . 47
3.2.5 Flow Control . . . . . . . . . . . . . . . . . . . . . . . 49
3.2.6 Classical Subroutines . . . . . . . . . . . . . . . . . . . 50
3.3 Quantum States and Variables . . . . . . . . . . . . . . . . . . 51
3.3.1 Quantum Memory Management . . . . . . . . . . . . . 51
3.3.2 Quantum Variables . . . . . . . . . . . . . . . . . . . . 54
3.3.3 Quantum Expressions . . . . . . . . . . . . . . . . . . 57
3.4 Quantum Operations . . . . . . . . . . . . . . . . . . . . . . . 58
3.4.1 Non-unitary Operations . . . . . . . . . . . . . . . . . 58
3.4.2 Subroutines . . . . . . . . . . . . . . . . . . . . . . . . 59
3.4.3 General Operators . . . . . . . . . . . . . . . . . . . . 60
3.4.4 Unitary Gates . . . . . . . . . . . . . . . . . . . . . . . 62
3.4.5 Pseudo-classic Operators . . . . . . . . . . . . . . . . . 64
3.4.6 Quantum Functions . . . . . . . . . . . . . . . . . . . . 65
3.4.7 Pseudo-classic Gates . . . . . . . . . . . . . . . . . . . 67
3.5 Programming Techniques . . . . . . . . . . . . . . . . . . . . . 69
3.5.1 Design of Quantum Algorithms . . . . . . . . . . . . . 69
3.5.2 Dealing with Reversibility . . . . . . . . . . . . . . . . 73
4 Quantum Algorithms 76
4.1 Grovers Database Search . . . . . . . . . . . . . . . . . . . . 76
4.1.1 Formulating a Query . . . . . . . . . . . . . . . . . . . 76
4.1.2 The Algorithm . . . . . . . . . . . . . . . . . . . . . . 77
4.1.3 Implementation . . . . . . . . . . . . . . . . . . . . . . 79
4.2 Shors Algorithm for Quantum Factorization . . . . . . . . . . 81
4.2.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.2.2 The Algorithm . . . . . . . . . . . . . . . . . . . . . . 82
4.2.3 Quantum Fourier Transform . . . . . . . . . . . . . . . 85
4.2.4 Modular Arithmetic . . . . . . . . . . . . . . . . . . . 86
4.2.5 Implementation . . . . . . . . . . . . . . . . . . . . . . 88
CONTENTS 3
A QCL Syntax 96
A.1 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
A.2 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
A.3 Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
4
CHAPTER 1. QUANTUM PHYSICS IN A NUTSHELL 5
h = 2h = 6.626075 1034 Js
eU = C P
E = e(U + P ) = h = h
a2
l = 364.56 nm (1.1)
a2 4
CHAPTER 1. QUANTUM PHYSICS IN A NUTSHELL 6
This can be generalized to the Rydberg equation, which also accounts for the
non-visible parts of the spectrum
1 1 1
= RH 2
2 (1.2)
l k a
This suggests, that the electron in the Hydrogen atom is confined to certain
energy levels, which is in contradiction with classical mechanics.
The Bohr-Sommerfeld model accounted for this by introducing a quantum
condition: While the electrons are still assumed to circulate the nucleus on
their classical orbits, their angular momentum has to be a multiple of h. This
restriction could be justified by attributing wave properties to the electron
and demanding that their corresponding wave functions form a standing
wave; however this kind of hybrid theory remained unsatisfactory.
A complete solution for the problem came in 1923 from Heisenberg who
used a matrices-based formalism. In 1925, Schrodinger published an alter-
native solution using complex wave functions. It took two years until Dirac
showed that both formalisms were in fact equivalent.
Any momentary state of the system can be used as an initial value for the
above equation to determine its temporal behavior.
Figure 1.1: A ball trapped between two mirrors as classical and as quantum
particle
In analogy to equation 1.2.2.1, the expectation value hOi and the uncer-
CHAPTER 1. QUANTUM PHYSICS IN A NUTSHELL 10
If we split off the time dependent part, using the ansatz (~r, t) = (~r)(t)
from 1.2.2.2 and the separation parameter E, we get
E (t) = ih (t) and H (~r) = E (~r) (1.12)
t
The time part is solved by = eit with = E/h. E is the energy of the
state, since
Z Z
3
hHi = (~r) (H (~r)) d ~r = E (~r) (~r) d3~r = E (1.13)
spectrum and the possible eigenvalues En (also called energy terms) can be
enumerated. The solution for the lowest eigenvalue E0 is called the ground-
state 0 of the system.
Since for most physical applications, only the value of the energy terms is
of importance, it is hardly ever necessary to actually compute the eigenstates.
It has been the discovery of discrete energy states, which gave quantum
physics its name, as any state change from eigenstate n to m involves the
exchange of an energy quantum E = Em En .
1 (x) 1 (x)
2 (x) 2 (x)
3 (x) 3 (x)
Figure 1.2: The first three eigenstates for an electron in a potential well
CHAPTER 1. QUANTUM PHYSICS IN A NUTSHELL 13
The scalar product hi|ji of the eigenfunctions i and j from the on dimen-
sional capacitor example (1.2.3.3) gives
Z
2Z l
hi|ji = i (x)j (x)dx = sin( ix) sin( jx)dx (1.27)
I l 0 l l
The substitution = l x leads to
2Z
hi|ji = sin(i) sin(j)d = ij (1.28)
0
So the eigenfunctions of the Hamilton operator H are orthonormal according
to the scalar product (1.26) and therefor form the base of the orthonormal
vector space H consisting of all possible linear combinations of {1 , 2 , . . .}.
This space is the Hilbert space for this particular problem and it can be shown
that the eigenvalues of any operator describing a physical observable form
an orthogonal base.9
1.3.1.2 Completeness
Since the Schrodinger Equation is a linear differential equation, any linear
combination of solutions is also a solution and thus a valid physical state.
To calculate the expectation value hHi of the energy for a given state (x, t)
we have to solve the integral
Z
hHi = h|H|i = (x, t)H(x, t)dx (1.29)
9
As physical observables are real values, their corresponding operators O have to be
self-adjoint i.e. O = O
CHAPTER 1. QUANTUM PHYSICS IN A NUTSHELL 15
Since H |ii = Ei |ii and hi|ji = ij , hHi can be expressed as a weighted sum
of eigenvalues: X
hHi = |ci |2 Ei (1.31)
i
Using the eigenfunctions for the one-dimensional capacitor (1.2.3.3) the com-
plex amplitudes ci for an arbitrary continuous function f (x) over [0, l] are
given by s
2 Zl
ci = hi|f i = sin( ix)f (x)dx (1.32)
l 0 l
This describes a standard sine-Fourier Transform. The original function can
be reconstructed by a composition of eigenfunctions n (x) with the Fourier
components ci
s
X
2 X
f (x) = ci i (x) = ci sin( ix) (1.33)
i l i=1 l
1.3.1.3 Definitions
A Hilbert space H is a linear vector space over the scalar body C. Let
|f i, |gi, |hi H and , C, then the following operations are defined [23]:
1.3.2 Operators
1.3.2.1 Operators as Matrices
As we have shown in 1.3.1.2, all valid states can be expressed as a sum of
eigenfunctions, i.e.
X
(~r, t) = ci i (~r, t) (1.44)
i=0
1.3.2.3 Measurement
In classical physics, the observables of a system such as particle location, mo-
mentum, Energy, etc. where thought to be well defined entities which change
their values over time according to certain dynamic laws and which could
technical difficulties aside in principle be observed without disturbing the
system itself. It is a fundamental finding of quantum physics that this is not
the case.
we will always get the same energy as in the first measurement as the wave
function has collapsed to either 1 or 2 .
(
|1 i with probability |c1 |2
|i (1.53)
|2 i with probability |c2 |2
The fact that hHi is only a statistical value, brings up the question when
it is reasonable to speak about the energy of a state (or any other observable,
for the matter) or, with other words, whether a physical quality of a system
exists for itself or is invariably tied to the process of measuring.
The Copenhagen interpretation of quantum physics argues that an observ-
able O only exists if the system in question happens to be in an eigenstate
of the according operator O [22].
HU (t) |0 i = ih U (t) |0 i and U (0)|i = |i (1.58)
t
We get the operator equation HU = ih t U with the solution
hi Ht
X 1 (i)n tn
U (t) = e = n Hn (1.59)
n=0 n! h
Operators U with U = U (1) are called unitary. Since the temporal evolution
of a quantum system is described by a unitary operator and U (t) = U (t)
it follows that the temporal behavior of a quantum system is reversible, as
long a no measurement is performed.10
Unitary operators can also be used to describe abstract operations like
rotations
without the need to specify how this transformations are actually performed
or having to deal with time-dependent Hamilton operators.
Mathematically, unitary operations can be described as base-transform-
ations between 2 orthonormal bases (just like rotations in R3 ). Let A and B
be Hermitian operators with the orthonormal eigenfunctions n and n and
P P
|i = i ci |i i = i ci |i i, then the Fourier coefficients ci are given by
c0 c0
X
c1 = U c1 with U = |i ihi |j ihj | (1.65)
..
.. i,j
. .
The spins also form a finite Hilbert space HS = C2 with the orthonormal
base {| i, | i}. If we combine HS with the solution space HR for the spinless
problem (equation 1.22), we get a combined Hilbert space H = HR HB
with the base-vectors
Such states are called product states. Unitary transformations and measure-
ments applied to only one subsystem dont affect the other as
X
U A |i = (U I)| A i| B i = Uik ak jl bl |i, ji = U | A i | B i (1.70)
i,j,k,l
2 2
2 X X
pA
i = h A
i |h B
| |i =
b
a b
j k l hi, j|k, li
= a
i b
j j = |ai |
b 2
j,k,l j
(1.71)
1.3.3.3 Entanglement
If |i is not a product state, then operations on one subsystem can affect
the other. Consider two electrons with the common spin state
1
|i = (| i + | i) (1.72)
2
If we measure the spin of the first electron, we get either | i or | i with the
equal probability p = 1/2 which the resulting post-measurement states | i
or | i. Consequently, if we measure the spin of the second electron, we will
always find it to be anti-parallel to the first.
Two systems whose common wave-function |i is not a product state are
entangled.
11
We assume here that the eigenvalue EiA isnt degenerated, otherwise the solution is
analog to equation 1.50.
Chapter 2
Quantum Computers
2.1 Introduction
2.1.1 The Church-Turing Thesis
The basic idea of modern computing science is the view of computation as
a mechanical, rather than a purely mental process. A method, or procedure
M for achieving some desired result is called effective or mechanical just in
case [17]
2. M will, if carried out without error, always produce the desired result
in a finite number of steps;
22
CHAPTER 2. QUANTUM COMPUTERS 23
Alan Turing and Alonzo Church both formalized the above definition by
introducing the concept of computability by Turing machine and the math-
ematically equivalent concept of recursive functions with the following con-
clusions:
The states s0 and sn are called the input- and the output-state. The
machine M = (S, m, , ) thus implements the function
2.1.3.1 Indeterminism
As we have showed in 1.3.2.3, the measurement of an observable O with the
according operator O is only deterministic, if a system is in an eigenstate of
O. To account for the stochastic nature of quantum measurement, we have
to replace the labeling function m by a probabilistic operator M : H
which randomly chooses a string s according to some probability distribution
P
: s [0, 1] with s (s) = 1.
The value of a qubit is the observable N with the Hermitian operator N |ii =
i |ii over the Hilbert space H = C2 , or in matrix representation
!
0 0
N= (2.3)
0 1
thus, hN i gives the probability to find the system in state |1i if a measurement
is performed on the qubit.
|i = |00i + |10i + |01i + |11i with ||2 + ||2 + ||2 + ||2 = 1 (2.5)
CHAPTER 2. QUANTUM COMPUTERS 26
While we still can define distinct observables N (1) and N (2) for the value of
each qubit with the operators N (1) |iji = i |iji and N (2) |iji = j |iji, their
expectation values
3
Unless the machine state happens to be a product state, that is (see 1.3.3.2).
CHAPTER 2. QUANTUM COMPUTERS 27
2.2.1.4 Subsystems
As we have shown above, the memory of an n-qubit quantum computer is
a combined system of n identical qubit-subsystems. Since the partition into
subsystems is merely methodical, we can consider the first m qubits (m < n)
as a single subsystem and write as
m 1 2nm 1
2X X n
|i = cij |i, ji with |i H = C2 (2.15)
i=0 j=0
As the base vectors |i, ji are product states |i, ji = |ii|ji, the Hilbert space
H can be written as a combination of
m nm
H = H0 H00 with H0 = C2 and H00 = C2 (2.16)
Let U 0 and U 00 be unitary operators over H0 and H00 , then the commutator
[U 0 , U 00 ] = 0 as
X
[U 0 , U 00 ] |i = cij [U 0 |ii(U 00 |ji) U 00 (U 0 |ii)|ji] = 0 (2.17)
i,j
Since the transformed base vectors (k) are identical for all permutations (k) s
and h0(k) |(k) i = j 0 j , it follows that the back-transformation U 0 I U is
independent from the chosen permutation (k) s .
CHAPTER 2. QUANTUM COMPUTERS 29
The mathematical explanation of this feature lies in the fact that the
requirement hi|U U |ji = ij is weaker than the pseudo-classical (see
2.2.2.4) condition
(k) (k)
s |d0 , d1 . . . dn1 i = |ds0 , ds1 . . . dsm1 i| i (2.31)
Deutsch [6] has shown that the set {U 2(, , , ), XOR} is in fact uni-
versal for unitary transformation. Furthermore, since {U 2( 0 , 0 , 0 , 0 )n } is
dense in {U 2(, , , )} for almost any6 set of parameters, {U 2, XOR} is
universal for most U 2 in the sense that any unitary transformation U can be
approximated to arbitrary precision.
Deutsch also proposed a 3-qubit gate D() which is universal, while only
requiring one parameter:
(
i cos |i, j, ki + sin |i, j, 1 ki for i = j = 1
D() : |i, j, ki (2.36)
|i, j, ki otherwise
If the matrix elements uij are of the form uij = ij with some permutation
, then their effect on pure states (base-vectors) can be described in terms
of classical reversible boolean logic.
For = /2 the universal Deutsch gate D() (2.36) degenerates into the
pseudo-classic operator
T = D( ) = |i, j, (i j) kihi, j, k| with i, j, k B (2.38)
2
T is the 3-bit controlled-not or Toffoli gate, which is a universal gate for
reversible boolean logic.
Let f : Z2n Z2n be a bijective function, then the corresponding pseudo-
classic operator F is given as
n 1
2X n 1
2X
1
F = |f (i)ihi| and F =F = |iihf (i)| (2.39)
i=0 i=0
6
basically, it is just required that the quotients between 0 , 0 , 0 , 0 and are irrational.
CHAPTER 2. QUANTUM COMPUTERS 33
2.2.3.3 Initialization
To set a quantum computer to a desired initial state |0 i = |s0 i correspond-
ing to the boolean input string s0 , it suffices to provide means to initially
cool all qubits to |0i and then apply any unitary transformation U which
matches the condition U |0i = |s0 i.
2.2.3.4 Measurement
As has been described in 1.3.2.3, it is impossible to observe a quantum state
without, at the same time, forcing the system to adopt a state 0 which
is an eigenstate of the Hermitian operator O corresponding to the observed
quantity O. The transition probability is thereby given as
2
p0 = |h 0 |i| (2.44)
the probabilities to measure i and the assorted post measurement states are
consequently
pi = |ci |2 and |i0 i = |ii (2.46)
The probability pi to measure the number i in the first register and the
according post measurement state |i0 i are given by
m 1
2X m 1
1 2X
pi = ci,j ci,j , and |i0 i = ci,j |i, ji (2.48)
j=0 pi j=0
Only n-to-n networks are allowed i.e. the total number of inputs has
to match the total number of outputs.
START
reset
classical control structure machine state
quantum operations
unitary
transformation
evaluate measure
measurement machine state
solution
no found?
yes
STOP
Quantum Programming
This chapter discusses the programming of quantum computers and the design
of quantum algorithms in the experimental quantum programming language
QCL.
3.1 Introduction
3.1.1 Computers and Programming
As has been illustrated in 2.1.2, a computer is basically a device which
3. provides means to initialize and measure the machine state while in-
terpreting S as discrete symbolic computational states s
41
CHAPTER 3. QUANTUM PROGRAMMING 42
Since the Toffoli gate is universal for reversible boolean logic, any bijective
boolean function g can directly be implemented on a quantum computer.
A general boolean function f over Bn , can be implemented by using a
pseudo-classical operator F
a classical computer can simulate any unitary operator with arbitrary preci-
sion by encoding the complex amplitudes as fixed point binary numbers. In
the general case, however, this will require an exponential overhead in time
as well as in space complexity.
Due to the stochastic nature of quantum measurements, the emulating
computer will also need a source of true randomness (like e.g. the probabilis-
tic Turing machine).
QCL program
binary quantum
program state machine state
terms of classical computer science, you can describe this setting as a uni-
versal computer with a quantum oracle. Figure 3.1 illustrates this hybrid
architecture.
From the perspective of the user, quantum programs behave exactly like
any other classical program, in the sense that it takes classical input such as
startup parameters or interactive data, and produces classical output. The
state of the controlling computer (i.e. program counter, variable values, but
also the mapping of quantum registers) is also strictly classical and referred
to as program state.
The actual program , i.e. the sequence of quantum instructions con-
sisting of elementary gates, measurement- and initialization-instructions is
passed over a well defined interface to the quantum computer, while the
returned output of is restricted to binary measurements values. The quan-
tum computer doesnt require any control logic, its computational state can
therefor be fully described by the common quantum state of its qubits,
also referred to as machine state.
3.2.1.1 Statements
Statements range from simple commands, over procedure-calls to complex
control-structures and are executed when they are encountered.
qcl> if random()>=0.5 { print "red"; } else { print "black"; }
: red
3.2.1.2 Definitions
Definitions are not executed but bind a value (variable- or constant-definition)
or a block of code (routine-definition) to a symbol (identifier).
qcl> int counter=5;
qcl> int fac(int n) { if n<=0 {return 1;} else {return n*fac(n-1);} }
Consequently, each symbol has an associated type, which can either be a data
type or a routine type and defines whether the symbol is accessed by reference
or call.
3.2.1.3 Expressions
Many statements and routines take arguments of certain data types. These
expressions can be composed of literals, variable references and sub-expressions
combined by operators and function calls.
qcl> print "5 out of 10:",fac(10)/fac(5)^2,"combinations."
: 5 out of 10: 252 combinations.
3.2.2.1 Constants
Frequently used values can be defined as symbolic constants. The syntax of
a constant declaration is
3.2.2.2 Variables
The definition of variables in QCL is analogous to C:
If no initial value is given, the new variable is initialized with zero, false or
"", respectively. The value of a variable can be changed by an assignment,
user input (see 3.2.4.3) and quantum measurement (see 3.4.1):
qcl> complex z; // declare complex variable z
qcl> print z; // z was initialized with 0
: (0.000000,0.000000)
qcl> z=(0,1); // setting z to i
qcl> print z;
: (0.000000,1.000000)
qcl> z=exp(z*pi); // assignment to z may contain z
qcl> print z;
: (-1.000000,0.000000)
qcl> input z; // ask for user input
? complex z [(Re,Im)] ? (0.8,0.6)
qcl> print z;
: (0.800000,0.600000)
CHAPTER 3. QUANTUM PROGRAMMING 46
3.2.3 Expressions
3.2.3.1 Operators
Table 3.2 shows all QCL operators ordered from high to low precedence.1
All binary operators are left associative, thus a b c = (a b) c. Explicit
grouping can be achieved by using parentheses.
3.2.3.2 Functions
QCL expressions may also contain calls to built-in or user defined functions.
Table 3.3 shown all built-in unary arithmetic functions.
Trigonometric Funct. Hyperbolic Funct.
sin(x) sine of x sinh(x) hyperbolic sine of x
cos(x) cosine of x cosh(x) hyperbolic cosine of x
tan(x) tangent of x tanh(x) hyperbolic tangent of x
cot(x) cotangent of x coth(x) hyperbolic cotangent of x
Complex Funct. Exponential an related Funct.
Re(z) real part of z exp(x) e raised to the power of x
Im(z) imaginary part of z log(x) natural logarithm of x
abs(z) magnitude of z log(x,n) base-n logarithm of x
conj(z) conjugate of z sqrt(x) square root of x
In addition to the above, QCL also contains n-ary functions such as min-
imum or gcd, conversion functions and the the pseudo function random()
(table 3.4). As the latter is no function in the mathematical sense, it may
not be used within the definition of user-functions and quantum operators.
Funct. Description
ceil(x) nearest integer to x (rounded upwards)
floor(x) nearest integer to x (rounded downward)
max(x,...) maximum
min(x,...) minimum
gcd(n,...) greatest common divisor
lcm(n,...) least common multiple
random() random value from [0, 1)
3.2.4.2 Call
The call of a procedure has the syntax
stmt identifier ( [ expr { , expr }] ) ;
As with assignments, no typecasting is performed for classical argument
types.
Due to the potential side-effects on the program state, procedure-call may
not occur within the definition of functions or operators.
3.2.4.3 Input
The input command prompts for user input and assigns the value to the
variable identifier . Optionally a prompt string expr can be given instead of
the standard prompt which indicates the type and the name of the variable.
qcl> real n;
qcl> input "Enter Number of iterations:",n;
? Enter Number of iterations: 1000
3.2.4.4 Output
The print command takes a comma separated list of expressions and prints
them to the console. Each output is prepended by a colon and terminated
with newline.
CHAPTER 3. QUANTUM PROGRAMMING 49
stmt for identifier = expr from to expr to [ step expr step ] block
3.2.6.2 Procedures
Procedures are the most general routine type and used to implement the
classical control structures of quantum algorithms which generally involve
evaluation loops, the choice of applied operators, the interpretation of mea-
surements and classical probabilistic elements.
With the exception of routine declarations, procedures allow the same
operations as are available in global scope (e.g. at the shell prompt) allowing
arbitrary changes to both the program and the machine state. Operations
exclusive to procedures are
Procedures can take any number of classical or quantum arguments and may
call all types of subroutines.
(see 3.3.1.6). These commands, however dont interfere with the program
state.
At startup or after the reset command, the whole machine state is empty,
thus |i = |0i.
The machine state of an n-qubit quantum computer with m allocated
qubits therefor is a product state of the form
As has been pointed out in 1.3.3.2, two quantum systems whose common
wave function is a product state are physically independent. This esp. means
that neither measurements nor unitary transformations on the allocated bits
s will affect s being in substate |0i.
The concept of the quantum heap allows two important abstractions:
2
Since the operators Ni for the value of the qubits commute (i.e
n [Ni , nj ] = 0), the
number of physically different measurement operations is merely m as the additional
bit-permutations are in fact classical operations.
CHAPTER 3. QUANTUM PROGRAMMING 53
Since allocated and unallocated qubits are in a product state, the defi-
nition of quantum algorithms is independent from the total number of
qubits.
During the application of F , the register s is filled with the temporary junk
bits j(i). To reclaim s, QCL allocates an auxiliary register t and translates
F into an operator F 0 which is defined as
The application of F 0 restores the scratch register s and the auxiliary register
a to |0i while preserving the function value in the target register t:
|i, 0, 0, 0i |i, 0, j(i), f (i)i |i, f (i), j(i), f (i)i |i, f (i), 0, 0i (3.9)
3.3.1.6 Simulation
The interpreter qcl can simulate quantum computers with arbitrary numbers
of qubits. According to the hybrid architecture as introduced in 3.1.3, the
numerical simulations are handled by a library (libqc) to separate the clas-
sical program state from the quantum machine state. QCL provides special
commands for inspecting the simulated machine state.
The dump command prints the current machine state in Braket notation.
When a quantum expression is given, it prints the probability spectrum in-
stead.
qcl> qureg q[2];
qcl> Mix(q);
qcl> dump;
: STATE: 2 / 4 qubits allocated, 2 / 4 qubits free
0.5 |0000> + 0.5 |0010> + 0.5 |0001> + 0.5 |0011>
qcl> dump q[0];
: SPECTRUM q[0]: |...0>
0.5 |0> + 0.5 |1>
The current machine-state can be loaded and saved with the load and save
command.
The quantum expression expr is bound to the register identifier of the quan-
tum type type which can be qureg or quconst.
qcl> qureg q[8];
qcl> qureg oddbits=q[1]&q[3]&q[5]&q[7];
qcl> qureg lowbits=q[0:3];
qcl> list q,oddbits,lowbits;
: global symbol q = |........76543210>:
qureg q[8];
: global symbol oddbits = |........3.2.1.0.>:
qureg oddbits;
: global symbol lowbits = |............3210>:
qureg lowbits;
3.3.3.1 Subregisters
Subregisters can be addressed with the subscript operator [. . .]. Depending
on the syntax (see table 3.5), single qubits are specified by their zero-based
offset and substrings are specified by the offset of the first qubit and either
the offset of the last qubit (syntax [:]) or the total length of the subregister
(syntax [\]).
qcl> qureg q[8];
qcl> print q[3],q[3:4],q[3\4];
: |....0...> |...10...> |.3210...>
Indices can be arbitrary expressions of type int. Invalid subscripts trigger
an error.
qcl> int i=255;
qcl> print q[floor(log(i,2))];
: |0.......>
qcl> print q[floor(log(i,2))\2];
! range error: invalid quantum subregister
The measure command measures the quantum register expr and assigns the
measured bit-string to the int variable identifier . If no variable is given,
the value is discarded.
The outcome of the measurement is determined by a random number
generator, which by default is initialized with the current system time.
For reproducible behavior of the simulation, a seed value can be given with
the option --seed.
Since reset and measure operations are irreversible, they must not occur
within operator definitions.
3.4.2 Subroutines
3.4.2.1 Hierarchy of Subroutines
Besides the classical subroutine type procedure and function, QCL pro-
vides two quantum routine types for general unitary operators (operator)
and pseudo-classic operators (qufunct). QCL allows to invert operators and
can perform scratch-space management for quantum functions, thus allowed
side effects on the classical program state as well as on the quantum machine
state have to be strictly specified.
The 4 QCL routine types form a call hierarchy, which means that a routine
may invoke only subroutines of the same or a lower level (see table 3.6).
The mathematical semantic of QCL operators and functions requires that
every call is reproducible. This means, that not only the program state must
not be changed by these routines, but also that their execution may in no way
depend on the global program state which includes global variables, options
and the state of the internal random number generator.
External operators have no body since they are not executed within QCL,
but merely serve as a hook for a binary function which implements the de-
sired operation directly by using the numeric QC-library and is linked to the
interpreter.
Section 3.4.4 and 3.4.7 describe the elementary unitary and pseudo classic
gates which are provided by the integrated simulator of qcl.
Matrix operators are checked for unitarity before they are applied:
qcl> const i=(0,1);
qcl> qureg q[1];
qcl> Matrix2x2(i*cos(pi/6),i*sin(pi/6),(0,0),(1,0),q);
! external error: matrix operator is not unitary
CHAPTER 3. QUANTUM PROGRAMMING 63
The vectors B 0 = {i Bn | |i0 i = H |ii} form the Hadamard base or dual base
or parity base to B = {i Bn | |ii}.
The Hadamard Transformation is self adjoint (i.e. H = H), which, for
unitary operators, implies that H 2 = I.
Since B 0 only contains uniform superpositions that just differ by the signs
of the base-vectors, the external implementation of H is called Mix.
extern operator Mix(qureg q);
Since both, explicit scratch parameters of type quscratch and local registers
of type qureg, have to be uncomputed manually, they are especially useful
for quantum functions U : |x, 0, 0i |x, f (s(x), x), 0i of the form
Base permutations are checked for unitarity before they are applied (i.e. it
is verified that the given integer sequence is in fact a permutation)
qcl> qureg q[3];
qcl> Perm8(0,0,1,2,3,4,5,6,q);
! external error: no permutation
CHAPTER 3. QUANTUM PROGRAMMING 68
3.4.7.2 Fanout
The Fanout operation is a quantum function (see 2.2.2.5) and stands for a
class of transformations with the characteristic Fanout : |x, 0i |x, xi
The external fanout operator of QCL is defined as
QCL also provides the special syntax a->b and a<-b as abbreviations for
Fanout(a,b) and !Fanout(a,b).
3.4.7.3 Swap
The Swap operator exchanges the qubits of two equal sized registers (Swap :
|x, yi |y, xi). A one to one qubit Swap operator has the transformation
matrix
1 0 0 0
0 0 1 0
Swap = (3.34)
0 1 0 0
0 0 0 1
extern qufunct Swap(qureg a,qureg b);
The QCL versions of Not and CNot also work on target registers, in which
case C[[e]] is applied to all qubits:
qcl> qureg q[4]; qureg p[4];
qcl> Not(q);
[8/8] 1 |00001111>
qcl> CNot(p,q);
[8/8] 1 |11111111>
3.5.1.1 Superpositioning
A key element in any universal programming language is conditional branch-
ing. Any classical program can be modeled as a decision tree where each
node corresponds to a binary state sn and leads to one or more successor
(i)
states sn+1 . On a deterministic Turing machine (TM), only one of those
(k)
transitions sn sn+1 is possible, so the computational path hs0 , s1 , . . . sn i is
predetermined.
On a probabilistic TM, the transitions are characterized by probabilities
P (i)
pi with i pi = 1 and one of the possible successor states sn+1 is chosen
accordingly at random.
Since the eigenvectors |ii directly correspond to classical binary states,
we might interpret a unitary transformation
X
U : |si uss0 |s0 i with s, s0 Bn and uss0 C (3.37)
s0
Classically, this can be viewed as a binary decision tree with a 50% chance
for each bit to flip. For an n-qubit register, this leads to 2n classical compu-
tational paths all of which are followed simultaneously resulting in a super-
position of 2n eigenvectors.
Since the Hadamard transforms for each single qubit commute, we can
a-posteriori emulate classic probabilistic behavior by performing a measure-
ment on the single qubits; thereby, the temporal order of the measurements is
unimportant so we can force a decision on the second qubit before we decide
on the the first and reconstruct the classical computational path in reverse
qcl> measure q[1]; // second qubits gives 0
[2/4] 0.707107 |0000> + 0.707107 |0001>
qcl> measure q[0]; // first qubit gives 1
[2/4] 1 |0001>
The restriction to bijective functions is not a severe as it seems, since for any
general binary function g a corresponding quantum function
Using the controlled-not operator C[[e]] (see 3.4.7.4), this can be implemented
as
If we put the argument qubits a and b into an even superposition of |0i and
|1i, then we can perform the addition on all possible combinations of inputs
simultaneously:
qcl> qureg a[1]; // argument a
qcl> qureg b[1]; // argument b
qcl> qureg s[2]; // target register s=a+b
qcl> Mix(a & b); // bring arguments into superposition
[4/4] 0.5 |0000> + 0.5 |0010> + 0.5 |0001> + 0.5 |0011>
qcl> CNot(s[0],a); // calculate low bit of sum
[4/4] 0.5 |0000> + 0.5 |0010> + 0.5 |0101> + 0.5 |0111>
qcl> CNot(s[0],b);
[4/4] 0.5 |0000> + 0.5 |0110> + 0.5 |0101> + 0.5 |0011>
qcl> CNot(s[1],a & b); // calculate high bit of sum
[4/4] 0.5 |0000> + 0.5 |0110> + 0.5 |0101> + 0.5 |1011>
CHAPTER 3. QUANTUM PROGRAMMING 72
3.5.1.3 Interference
While superpositioning and quantum parallelism allow us to perform an ex-
ponentially large number of classical computations in parallel, the only way
to read out any results is by performing a measurement whereby all but one
of the superpositioned eigenstates get discarded. Since it doesnt make any
difference if the computational path is determined during the calculation (as
with the probabilistic TM) or a-posteriori (by quantum measurement), the
use of quantum computers wouldnt provide any advantage over probabilistic
classical computers.
Quantum states, however, are not merely a probability distribution of
binary values but are vectors i.e. each eigenstate in a superposition isnt
characterized by a real probability, but a complex amplitude, so
1 1
|1 i = (|0i + |1i) and |2 i = (|0i |1i) (3.44)
2 2
describe different states, even if they have the same probability spectrum.
So, while on a probabilistic TM, the probabilities of two different com-
putational paths leading to the same final state s simply add up, this is not
necessarily the case on a quantum computer since generally
are in prefix notation, O stands for a quantum function O : |x, 0i |x, o(x)i,
indices indicate the registers operated on):
G
12 23H 34 K
|x, 0, 0, 0, 0i |x, gx, 0, 0, 0i |x, gx, hgx, 0, 0i (3.52)
45 L
|x, gx, hgx, khgx, 0i |x, gx, hgx, khgx, lkhgxi
Generally, a composition of n non-revertible functions would require n 1
registers to store intermediary results.
A simple and elegant solution of this problem was proposed by Bennet
[8, 9]: If a composition of two non-reversible functions f (x) = h(g(x)) is to
be computed, the scratch space for the intermediate result can be recycled
using the following procedure:
12G 23 H 12 G
|x, 0, 0i |x, g(x), 0i |x, g(x), h(g(x))i |x, 0, f (x)i (3.53)
The last step is merely the inversion of the first step and uncomputes the
intermediate result. The second register can then be reused for further com-
putations.
Without scratch-management, the evaluation of a composition of depth
d needs d operations and consumes d 1 junk registers. Bennets method of
uncomputing can then be used to trade space against time: Totally uncom-
puting of all intermediate results needs 2d 1 operations and d 1 scratch
registers, which is useful, if the scratch can be reused in the further compu-
tation.
By a combined use of r registers as scratch and junk space, a composition
of depth d = (r + 2)(r + 1)/2 can be evaluated with 2d r 1 = (r +
1)2 operations. An calculation of f (x) = l(k(j(i(h(g(x)))))) on a 4-register
machine (1 input, 1 output and 2 scratch/junk registers) would run as follows
(function values are in prefix notation):
register again:
F 123 Fanout F
|x, 0, 0, 0i |x, f (x), j(x), 0i 24 |x, f (x), j(x), f (x)i
123
|x, 0, 0, f (x)i
(3.55)
Again, the last step is the inversion of the first. The intermediate step is
a Fanout operation (see 3.4.7.2) which copies the function result into an
additional empty register. Possible implementations are e.g.
Uf U 1
Swap f
F 0 : |i, 0i |i, f (i)i |f (i), ii |f (i), 0i (3.57)
6
One example would be the Toffoli gate T : |x, y, zi |x (y z), y, zi which can be
used to implement any pseudo-classic operator for 3 or more qubits
Chapter 4
Quantum Algorithms
76
CHAPTER 4. QUANTUM ALGORITHMS 77
Grovers algorithm can then be used to solve the equation C(x) = 1 while
besides the fact that a solution exists and that it is unique, no additional
knowledge about C(x) is required.
Usually, the implementation of query will be complicated enough as not
to allow an efficient algebraic solution, but since the inner structure of C(x)
doesnt matter for the algorithm, we can easily implement a test query with
the solution n as
qufunct query(qureg x,quvoid f,int n) {
int i;
encrypt(p,key,s);
for i=0 to #s-1 { // s -> NOT (s XOR p)
if not bit(p,i) { Not(x[i]); }
}
CNot(f,x); // flip f if s=1111..
}
Note that, unlike the example above, this query function uses a local scratch
register, so it isnt necessary to explicitely uncompute s, as this will be taken
care of by QCLs internal scratch space management (see 3.3.1.5).
Since only one eigenvector |i0 i is supposed to match the search condition
C, the conditional phase shift will turn the initial even superposition into
1 1 X
|0 i = |i0 i + |ii (4.6)
N N i6=i0
The effect of the diffusion operator on an arbitrary eigenvector |ii is
2 NX
1
D |ii = |ii + |ji (4.7)
N j=0
so one iteration on a state of the form
X
|(k, l)i = k|i0 i + l|ii (4.8)
i6=i0
amounts to
Q D N 2 2(N 1) N 2 2
|(k, l)i |(k, l)i |( k+ l, l k)i
N N N N
(4.9)
CHAPTER 4. QUANTUM ALGORITHMS 79
N 2 2(N 1)
kj+1 = kj + lj (4.11)
N N
N 2 2
lj+1 = lj kj (4.12)
N N
Using the substitution sin2 = 1
N
the solution of the above system can
be written in closed form.
4.1.3 Implementation
4.1.3.1 The Query Operator
If we choose to formulate the query as quantum function with a flag qubit
f to allow for a strictly classical implementation, as suggested in 4.1.1, then
the operator Q can be constructed as
by using the conditional phase gate V () (see 3.4.4.4) and considering the
flag register f as temporary scratch space.
CHAPTER 4. QUANTUM ALGORITHMS 80
N
X 1 N
X 1
(i,k) k0 (k,j)
(1) (1) (1) = 2 + (1)(i,k)(k,j) = N ij 2 (4.18)
k=0 k=0
Using the not operator from 3.4.7.4 and a conditional phase gate V ()
we can implement the diffusion operator as
operator diffuse(qureg q) {
Mix(q); // Hadamard Transform
Not(q); // Invert q
CPhase(pi,q); // Rotate if q=1111..
!Not(q); // undo inversion
!Mix(q); // undo Hadamard Transform
}
In fact, the above operator implements D, but since overall phases make
no physical difference, this doesnt matter.
procedure grover(int n) {
int l=floor(log(n,2))+1; // no. of qubits
int m=ceil(pi/8*sqrt(2^l)); // no. of iterations
int x;
int i;
qureg q[l];
qureg f[1];
{
reset;
Mix(q); // prepare superposition
for i= 1 to m { // main loop
query(q,f,n); // calculate C(q)
CPhase(pi,f); // negate |n>
!query(q,f,n); // undo C(q)
diffuse(q); // diffusion operator
}
measure q,x; // measurement
print "measured",x;
} until x==n;
}
The procedure argument n is the number to be found; the size of the quantum
registers as well as the numbers of iterations are set accordingly:
qcl> grover(500);
: 9 qubits, using 9 iterations
: measured 500
qcl> grover(123);
: 7 qubits, using 5 iterations
: measured 74
: measured 123
qcl> grover(1234);
: 11 qubits, using 18 iterations
: measured 1234
sieve) needs O exp ( 64 9
)1/3 N 1/3 (ln N )2/3 operations for factoring a binary
number of N bits [12] i.e. scales exponentially with the input size.
The multiplication of large prime numbers is therefore a one-way function
i.e. a function which can easily be evaluated in one direction, while its
inversion is practically impossible. One-way functions play a major roll in
cryptography and are essential to public key crypto-systems where the key
for encoding is public and only the key for decoding remains secret.
In 1978, Rivest, Shamir and Adleman developed a cryptographic algo-
rithm based on the one-way character of multiplying two large (typically
above 100 decimal digits) prime numbers. The RSA method (named after
the initials of their inventors) became the most popular public key system
and is implemented in many communication programs.
While it is generally believed (although not formally proved) that effi-
cient prime factorization on a classical computer is impossible, an efficient
algorithm for quantum computers has been proposed in 1994 by P.W. Shor
[11].
The first two systems have the trivial solutions y1 = 1 and y2 = 1 which
dont differ from those of the quadratic equation y 2 = 1 in Z or a Galois
field GF(p) (i.e. Zp with prime p). The last two systems have the non-
trivial solutions y3 = a, y4 = a, as postulated by the Chinese remainder
theorem stating that a system of k simultaneous congruences (i.e. a system
of equations of the form y ai mod mi ) with coprime moduli m1 , . . . , mk
(i.e. gcd(mi , mj ) = 1 for all i 6= j) has a unique solution y with 0 x <
m1 m2 . . . mk .
A measurement of the second register with the result k = f (s) with s < r
reduces the state to
dN/re1
X 12
0 N
| i = c0j |rj + s, ki with c0j = (4.24)
j=0 r
1 NX1
2i
DFT : |xi e N xy |yi (4.25)
N y=0
r p1
X 2i r i p1
X 2i
c0i = exp i(jr + s) = e exp ijr (4.27)
N j=0 N N j=0 N
is N
with i = 2i and p =
N r
2n 0 i
If N = 2 is a multiple of r then ci = e / r if i is a multiple of N/r and
0 otherwise. But even if r is not a power of 2, the spectrum of | 0 i shows
distinct peaks with a period of N/r because
(
1 n1
X 1 if Z
lim e2ik = (4.28)
n n
k=0
0 if
6 Z
This is also the reason why we use a first register of 2n qubits when r < 2n
because it guarantees at least 2n elements in the above sum and thus a peak
width of order O(1).
If we now measure the first register, we will get a value c close to N/r
with Zr . This can be written as c/N = c 22n /r. We can think
of this as finding a rational approximation a/b with a, b < 2n for the fixed
point binary number c 22n . An efficient classical algorithm for solving this
CHAPTER 4. QUANTUM ALGORITHMS 85
muln(a,n,b,j,e);
!muln(invmod(a,n),n,j,b,e);
cxor(j,b,e);
cxor(b,j,e);
}
4.2.5 Implementation
4.2.5.1 Auxiliary Functions
The implementation of the Shor algorithm uses the following functions:
boolean testprime(int n)
Tests whether n is a prime number
boolean testprimepower(int n)
Tests whether n is a prime power3
For the actual implementations of these functions, please refer to appendix B.2.
3
Since both testfunctions
are not part of the algorithm itself, short but inefficient
implementations with O( n) have been used
CHAPTER 4. QUANTUM ALGORITHMS 89
{
{ // generate random base
x=floor(random()*(number-3))+2;
} until gcd(x,number)==1;
print "chosen random x =",x;
Mix(reg1); // Hadamard transform
expn(x,number,reg1,reg2); // modular exponentiation
measure reg2; // measure 2nd register
dft(reg1); // Fourier transform
measure reg1,m; // measure 1st register
reset; // clear local registers
CHAPTER 4. QUANTUM ALGORITHMS 90
4.2.5.3 Factoring 15
15 is the smallest number that can be factorized with Shors algorithm, as its
the product of the smallest odd prime numbers 3 and 5. Our implementation
of the modular exponentiation needs 2l + 1 qubits scratch space with l =
dld(15 + 1)e = 4. The algorithm itself needs 3l qubits, so a total of 21 qubits
must be provided.
$ qcl -b21 -i shor.qcl
qcl> shor(15)
: chosen random x = 4
: measured zero in 1st register. trying again ...
: chosen random x = 11
: measured 128 , approximation for 0.500000 is 1 / 2
: possible period is 2
: 11 ^ 1 + 1 mod 15 = 12 , 11 ^ 1 - 1 mod 15 = 10
: 15 = 5 * 3
The first try failed because 0 was measured in the first register of | 0 i and
/r = 0 gives no information about the period r.
One might argue that this is not likely to happen, since the first register
has 8 qubits and 256 possible base-vectors, however, if a number n is to be
CHAPTER 4. QUANTUM ALGORITHMS 91
factored, one might expect a period about n assuming that the prime fac-
tors of n are of the same order of magnitude. This would lead to a period qn
after the DFT and the probability p = 1n to accidentally pick the basevector
|0i, would be p = 25.8%.
In the special case of a start value x = 4 the period of the modular
exponentiation is 2 since 42 mod 15 = 1, consequently the Fourier spectrum
shows 2 peaks at |0i and |128i and p = 1/2.
The second try also had the same probability of failure since 112 mod 15 =
1, but this time, the measurement picked the second peak in the spectrum
at |128i. With 128/28 = 1/2 = /r, the period r = 2 was correctly identified
and the factors gcd(112/2 1 , 15) = {3, 5} to 15 have been found.
Bibliography
[1] Paul Benioff 1997 Models of Quantum Turing Machines, LANL Archive
quant-ph/9708054
[2] J.I. Cirac, P. Zoller 1995 Quantum Computations with Cold trapped Ions,
Phys. Rev. Lett. 74, 1995 , 4091
[3] D. Deutsch, 1985 Quantum theory, the Church-Turing principle and the
universal quantum computer. Proceedings of the Royal Society London
A 400, 97-117
[11] P.W. Shor. 1994 Algorithms for quantum computation: Discrete loga-
rithms and factoring
[13] David Beckman et al. 1996 Efficient networks for quantum factoring
92
BIBLIOGRAPHY 93
[14] F.D. Murnaghan 1962 The Unitary and Rotation Groups, Spartan
Books, Washington
[15] Artur Ekert and Richard Jozsa. 1996 Shors Quantum Algorithm for
Factoring Numbers, Rev. Modern Physics 68 (3), 733-753
[16] G.H. Hardy and E.M. Wright 1965 An Introduction to the Theory of
Numbers (4th edition OUP)
[20] Lov K. Grover 1996 A fast quantum mechanical algorithm for database
search. Proceeding of the 28th Annual ACM Symposium on Theory of
Computing
[21] Michel Boyer, Gilles Brassard, Peter Hoyer, Alain Tapp 1996 Tight
bounds on quantum searching. Proceedings PhysComp96
94
List of Tables
95
Appendix A
QCL Syntax
A.1 Expressions
96
APPENDIX A. QCL SYNTAX 97
A.2 Statements
A.3 Definitions
B.1 default.qcl
99
APPENDIX B. THE SHOR ALGORITHM IN QCL 100
const pi=3.141592653589793238462643383279502884197;
B.2 functions.qcl
set allow-redefines 1;
int findfactor(int n) {
int i;
if n<=0 { exit "findfactor takes only positive args"; }
for i=2 to floor(sqrt(n)) {
if n mod i == 0 { return i; }
}
return 1;
}
boolean testprime(int n) {
int i;
if n<=1 { return false; }
for i=2 to floor(sqrt(n)) {
if n mod i == 0 { return false; }
}
return true;
}
boolean testprimepower(int n) {
int i;
int f;
i=2;
while i<=floor(sqrt(n)) and f==0 {
if n mod i == 0 { f=i; }
i=i+1;
}
APPENDIX B. THE SHOR ALGORITHM IN QCL 102
for i=0 to 30 {
if a/2^i mod 2 == 1 { y=y*u mod n; }
u=u^2 mod n;
}
return y;
}
if gcd(a,n)>1 { return 0; }
for i=1 to n {
if b*a mod n == 1 { return b; }
b=b*a mod n;
}
return 0;
}
while true {
z=y-floor(y);
if z<0.5/qmax^2 { return q1; }
y=1/z;
q2=floor(y)*q1+q0;
APPENDIX B. THE SHOR ALGORITHM IN QCL 103
set allow-redefines 0;
B.3 qufunct.qcl
set allow-redefines 1;
qufunct flip(qureg q) {
int i; // declare loop counter
for i=0 to #q/2-1 { // swap 2 symmetric bits
Swap(q[i],q[#q-i-1]);
}
}
// Conditional Xor
}
CNot(sum[0],e); // add a
}
};
// Add qubit b
if #sum>1 { // set carry if available
CNot(sum[1],b & sum[0]);
}
CNot(sum[0],b); // add b
}
set allow-redefines 0;
B.4 dft.qcl
operator dft(qureg q) { // main operator
const n=#q; // set n to length of input
int i; int j; // declare loop counters
for i=0 to n-1 {
for j=0 to i-1 { // apply conditional phase gates
CPhase(2*pi/2^(i-j+1),q[n-i-1] & q[n-j-1]);
}
Mix(q[n-i-1]); // qubit rotation
}
flip(q); // swap bit order of the output
}
B.5 modarith.qcl
set allow-redefines 1;
include "functions.qcl";
include "qufunct.qcl";
if gcd(a,n)>1 {
exit "omuln: a and n have to be relativly prime";
}
muln(a,n,b,j,e);
!muln(invmod(a,n),n,j,b,e);
cxor(j,b,e);
cxor(b,j,e);
}
set allow-redefines 0;
APPENDIX B. THE SHOR ALGORITHM IN QCL 107
B.6 shor.qcl
include "modarith.qcl";
include "dft.qcl";
{
{ // generate random base
x=floor(random()*(number-3))+2;
} until gcd(x,number)==1;
print "chosen random x =",x;
Mix(reg1); // Hadamard transform
expn(x,number,reg1,reg2); // modular exponentiation
measure reg2; // measure 2nd register
dft(reg1); // Fourier transform
measure reg1,m; // measure 2st register
reset; // clear local registers
if m==0 { // failed if measured 0
print "measured zero in 1st register. trying again ...";
} else {
c=m*0.5^(2*width); // fixed point form of m
q=denominator(c,qmax); // find rational approximation
p=floor(q*c+0.5);
print "measured",m,", approximation for",c,"is",p,"/",q;
if q mod 2==1 and 2*q<qmax { // odd q ? try expanding p/q
print "odd denominator, expanding by 2";
p=2*p; q=2*q;
}
if q mod 2==1 { // failed if odd q
print "odd period. trying again ...";
} else {
print "possible period is",q;
e=powmod(x,q/2,number); // calculate candidates for
a=(e+1) mod number; // possible common factors
APPENDIX B. THE SHOR ALGORITHM IN QCL 108