Introduction to quantum computing
Introduction to quantum computing
Mads Bahrami, (last update: Nov 24, 2025)
Wolfram Research Inc, USA
This book provides a concise and practical introduction to quantum computing, emphasizing an interactive, hands-on approach. It introduces and explores the essential concepts, principles, and foundational quantum algorithms through guided modeling and simulation exercises. Each topic is developed computationally, allowing readers to build both intuition and technical proficiency by directly engaging with the computational mechanics of quantum systems. The approach taken here is computation first, meaning that understanding arises through the act of calculation, echoing David Mermin’s well-known slogan, “shut up and calculate.”
Who is this book for? It is written for anyone curious about learning quantum computation through the lens of discrete vector spaces, seasoned with a delightful touch of quantum computing. I have deliberately avoided delving into the nitty-gritty of mathematical formalism. Instead, my focus is on computation itself, on doing the work, even when the underlying mathematics is complex and hidden behind the scenes. As I mentioned in the abstract, I believe one of the most important steps in learning quantum theory (an abstract and often intimidating subject at first encounter) is to learn by doing the computations.
The environment you will be working in is a Mathematica notebook. Every Mathematica notebook is organized into cells, each marked by a small bracket along the right edge of the window. A cell can contain text, visualizations, data, input code, or nearly anything else that can be expressed in computational form. In essence, it is a flexible workspace where ideas, mathematics, and computation come together seamlessly.
Many of the calculations in this book will be carried out using the Wolfram Quantum Framework. This framework is distributed as a paclet, meaning it is a collection of specialized functions. Once installed, these functions and their documentation pages become integrated into Mathematica, just like its native built-in functions. Do not get intimated by code. Even if it looks complicated, for many parts you can ignore the code and focus on the outcome.
If any question, please reach out to quantum@wolfram.com
Table of Contents
1
.What Is Quantum Computation?
1
.1
.Key Concepts
1
.2
.Classical Computation
1
.3
.Quantum Circuits and Qubits
2
.Quantum States: Single Particle Case
2
.1
.Key Concepts
2
.2
.Bloch Sphere
2
.3
.Bra-Ket Notation
2
.4
.State Vectors, Amplitudes and Density Matrices
2
.5
.Pauli operators and Bloch sphere
2
.6
.Higher Dimensions
3
.Probability and Measurement
3
.1
.Key Concepts
3
.2
.Frequency vs probability
3
.3
.Joint vs Marginal Probabilities
4
.Quantum States: Multi-Particle Cases
4
.1
.Key Concepts
4
.2
.Tensor Product Structure
4
.3
.Separable vs Nonseparable Objects
5
.Superposition and Entanglement
5
.1
.Key Concepts
5
.2
.Superposition
5
.3
.Entanglement
6
.A Quick Tour of Quantum Gates
6
.1
.Key Concepts
6
.2
.Introduction
6
.3
.Single-Qubit Gates
6
.3
.1
.Pauli gates
6
.3
.2
.Hadamard gate
6
.3
.3
.Family of phase-like gates
6
.3
.4
.Family of rotation gates
6
.4
.Multi-Qubit Gates
6
.4
.1
.Family of control NOT
6
.4
.2
.Family of control phase
6
.4
.3
.SWAP and
SWAP
6
.4
.4
.Family of control rotation
6
.4
.5
.Family of Ising rotation
6
.4
.6
.3-qubit gates and more
7
.Deutsch-Jozsa Algorithm
7
.1
.Key Concepts
7
.2
.Statement of the Deutsch-Jozsa Problem
7
.3
.Deutsch-Jozsa Oracles
7
.4
.Deutsch-Jozsa Algorithm
7
.5
.Initialization
8
.Bernstein-Vazirani Algorithm
8
.1
.Key Concepts
8
.2
.Statement of the Bernstein-Vazirani Problem
8
.3
.Quantum Bernstein-Vazirani Algorithm
8
.4
.Effects of Noise
9
.Grover Search Algorithm
9
.1
.Key Concepts
9
.2
.Statement of the Grover Search Problem
9
.3
.Grover oracle
9
.3
.1
.Boolean oracle
9
.3
.2
.Phase oracle
9
.4
.Grover’s Algorithm
10
.Quantum Arithmetic
10
.1
.Key Concepts
10
.2
.Discrete Fourier Transform and QFT
10
.3
.Phase Basis Encoding
10
.4
.Quantum Phase Adders
10
.5
.Generic Addition
10
.6
.Multiplication
11
.Quantum Phase Estimation Algorithm
11
.1
.Key Concepts
11
.2
.Eigenvectors and Eigenvalues
11
.3
.Quantum Phase Estimation: Simple Example
11
.4
.Quantum Phase Estimation: Complicated Example
12
.Shor’s Algorithm for Factorization
12
.1
.Key Concepts
12
.2
.Factorization Through Order Finding
12
.2
.1
.Full algorithm
12
.2
.2
.Example: Step-by-Step Factorization
12
.3
.Order Finding with a Quantum Circuit
12
.3
.1
.Constructing the Operator
U
12
.3
.2
.Quantum Phase Estimation for
U
12
.3
.3
.Post-Processing the Eigenvalue Estimations
12
.3
.4
.Exploring the Details
13
.Quantum Key Distribution: BB84 scheme
13
.1
.One-time pad encryption
13
.2
.Bennett-Brassard quantum solution (BB84)
14
.Acknowledgment
What Is Quantum Computation?
We begin with a brief revisit of classical computation through a series of hands-on examples. From there, the focus transitions to the quantum domain, where you will explore several examples of quantum circuits. Each example is accompanied by corresponding code; it’s perfectly fine if not everything is immediately clear. As you move forward, your grasp of quantum principles and your coding proficiency will develop together, reinforcing one another through practice and exploration.
Key Concepts
Key Concepts
◼
Classical computation
◼
Quantum computation
◼
Quantum bit (qubit)
◼
Quantum circuit
Classical Computation
Classical Computation
In order to understand quantum computation, it helps to compare it to classical computation. To compute something, you have to be able to use rules to determine what should be the output from a list of inputs. You can think of computing as starting with the inputs and following the rules to reach an output.
Consider two binary numbers “01” and “10” and let’s see how we can add them. First, each bit-string is interpreted as a base-2 number rather than ordinary decimal, so “01” becomes one and “10” becomes two.
Define binary strings:
In[]:=
a="01";b="10";
Construct the number from the base-2 digits of :
a
In[]:=
FromDigits[a,2]
Out[]=
1
Construct the number from the base-2 digits of :
b
In[]:=
FromDigits[b,2]
Out[]=
2
Add the numbers using normal addition:
In[]:=
FromDigits[a,2]+FromDigits[b,2]
Out[]=
3
Convert the total back into bit-string:
In[]:=
IntegerString[FromDigits[a,2]+FromDigits[b,2],2]
Out[]=
11
To get a better sense of constructs of numbers in a base , let’s consider symbolic digits and base:
b
In[]:=
ExpandFromDigitsc.4,c.3,c.2,c.1,c.0,b.
Out[]=
c.0+b.c.1+c.2+c.3+c.4
2
b.
3
b.
4
b.
Donating the length of digits by , the maximum power of will be (in the above example, ).
n
b
n-1
b
5-1
b
Let’s consider another example. Add two binary strings 100 and 011:
In[]:=
a="101";b="011";IntegerString[FromDigits[a,2]+FromDigits[b,2],2]
Out[]=
1000
Note that something interesting happened in above calculation. Pay attention to the string length of initial numbers and final total. The original bit-strings had the string length of 3 while the final answer is a four-bit string. Let’s dive in a bit more.
What are all the states of a sequence of three classical bits?
What are the corresponding numbers from above base-2 digits?
To encode that result as a bitstring, we need at least 4 bits (since 8 requires 4-bit representation).
If you insist on staying within 3 bits, perform all operations modulo 8 (wrap-around arithmetic).
Then the 3-bit string of the above result is:
Now let’s try another encoding scheme.
It is also possible to encode information in such sequences of classical bits to represent problems of interest. For example, each of those bit sequences could also encode letter characters with a different encoding scheme:
With yet another encoding scheme, those same bit sequences could represent colors with opacity:
Having seen how a 3-bit register cleanly enumerates eight distinct states and how different encodings map those states to numbers, letters, or colors, we now move to the quantum setting. There the same eight basis strings exist, but a 3-qubit register can also occupy complex superpositions of them, and even entangled combinations that have no classical analogue. The rules for storing and extracting information therefore change: measurement reveals a single basis outcome, while computation exploits interference among amplitudes.
Quantum Circuits and Qubits
Quantum Circuits and Qubits
Now we’ll dive directly into quantum computation. We’ll introduce common terms and concepts widely used in quantum information. Some details will be only briefly mentioned in this chapter. For each topic, we’ll highlight what to focus on for a first exposure, and later we’ll return to expand on each concept in more depth.
In quantum computing, information is encoded in quantum states, which we transform into new states through some operations (i.e., quantum gates) tailored to a computational goal. Both states and transformations (i.e. their gates) have useful visual representations. In this chapter, we will emphasize visual intuition first and introduce the detailed mathematics later.
Since we will use the Wolfram Quantum Framework, we first need to install it.
The diagram below represents an example of a quantum circuit:
Show the vectors corresponding to computational basis of 3-qubits:
The quantum state of the above circuit, just before measurement, is:
The above representation illustrates quantum superposition, which is a linear combination of multiple states with coefficients that, in general, can be complex numbers.
What are the results of running this circuit? Since measurements are included at the end, executing the circuit returns a quantum measurement object in the Wolfram Quantum Framework. This object contains the probability distribution over possible bitstrings and can be sampled to generate measurement outcomes:
Note that by executing the code above, we simulated a quantum computation on a classical computer. This is exactly what a quantum simulator does: it numerically emulates quantum state evolution and measurement according to the rules of quantum mechanics, all while running on classical hardware.
Alarm: saying we “performed a quantum computation” can be misleading, simulators do not provide quantum speedups, are limited by exponential memory growth with qubit count, and only capture noise or device effects if those are explicitly modeled.
What are the results of the measurement in this circuit?
Notice that the possible outcomes of a quantum measurement are simply classical bit sequences. In the earlier classical computation examples, the rules were deterministic: each input led to a definite output. In contrast, quantum computation typically yields a range of possible outcomes, each with a certain probability. This is because quantum theory provides a probabilistic description of measurement results, with the distribution determined by the state just before measurement (and the chosen measurement basis).
Additionally, you can compute how the quantum state evolves as gates are applied. Although we have not yet discussed the state in full detail, for now focus on the linear combination of computational-basis bitstrings and examine the coefficient (amplitude) of each term. These amplitudes update linearly under gates, and their squared magnitudes determine the probabilities of the corresponding bitstrings upon measurement.
Keep in mind that, in the end, the most important information we extract from a quantum system is its measurement results (and their statistics). We will discuss this in more detail in future chapters.
Quantum States: Single Particle Case
We review quantum states for a single system: state vectors, amplitudes, and measurement probabilities. We then contrast pure and mixed states and describe both with the density matrix. Finally, we extend these ideas to higher-dimensional systems.
Key Concepts
Key Concepts
◼
Quantum State
◼
Amplitudes
◼
State Vector
◼
Dirac Notation
◼
Bloch Sphere
◼
Density Matrix
◼
Pure vs Mixed States
Bloch Sphere
Bloch Sphere
Qubits are not classical bits, so listing classical bitstrings does not capture all possible qubit states. How are quantum states represented instead? Let’s begin with some visual intuition. There is a very useful graphical representation of 1-qubit states called the Bloch sphere. The Bloch sphere is named after physicist Felix Bloch:
In this approach, a quantum state is represented by a point in 3D space inside a sphere of radius 1 (the Bloch sphere). The point may lie on the surface, in which case we call it a pure state, or inside the sphere, in which case we call it a mixed state.
Bra-Ket Notation
Bra-Ket Notation
Another common notation in quantum is the bra–ket notation. It is also called the Dirac, after the famous British physicist, Paul M. Dirac.
Show the matrix form and also Dirac notation of NOT gate:
Show the Dirac notation of controlled-Hadamard gate:
Show the matrix of controlled-Hadamard gate in the computational basis:
State Vectors, Amplitudes and Density Matrices
State Vectors, Amplitudes and Density Matrices
Now consider the result of applying a Hadamard gate to the register state of a qubit:
If the initial state isn’t specified, Wolfram’s Quantum framework initializes the n-qubit register to the all-zeros state.
The coefficients of each basis element are known as the quantum amplitudes. A quantum state can be defined by giving its amplitudes:
The above state can be written in Dirac notation:
Notice the relationship between the vector coefficients and the probabilities according to the Born’s rule:
Probabilities are also basis-dependent; unless specified otherwise, they are computed in the computational basis. For example, transform the same state into Pauli-Y basis and calculate the probabilities:
We will discuss the basis transformation later.
Calculate probabilities in the computational basis for a quantum state:
Calculate probabilities in the computational basis for another quantum state:
Although the state vectors above are different, their computational-basis outcome probabilities are identical. This highlights a key point: measurement probabilities are basis-dependent. Next, compute the probabilities of these two states in the Pauli-X basis.
This is a subtle but important point: measurement probabilities are basis-dependent. In the Pauli-X basis, the distinction between the two states is clear, because their outcome probabilities differ.
Given a state vector, one can calculate probabilities manually too:
For probability calculations, always use a normalized state (or normalize the probabilities at the end).
However, there are situations where describing a qubit by a 2-vector is not enough. For example, in the famous Stern–Gerlach experiment—where a beam of silver atoms is sent through an inhomogeneous magnetic gradient—the initial state of the atoms, even if approximated by their electron spin only, may be an ensemble rather than a single pure state.
In such cases, a state vector cannot fully describe the system. Instead, we use a density matrix (or density operator). The demonstration above is modified from an example in the Wolfram Demonstration Project.
Generate a state using above state vector:
Compute the measurement probabilities in the computational basis:
Using this result, now compute the measurement probabilities in the Pauli-X basis:
The result shows that this pure state cannot yield 1/2 measurement probabilities in every basis. This motivates the more general description of quantum states using a density matrix. For example, let’s define a state by half of identify matrix:
Notice the tag “Mixed state” in the summary box of quantum state above.
The Dirac notation of the state is simply the density matrix written in the computational basis.
Now we can show that the measurement probabilities are the same in every basis and equal to 1/2.
An interesting feature of mixed states is that they lie inside the Bloch sphere, whereas pure states (those describable by a single 2-vector) lie only on the surface.
Show the Bloch vector of a mixed state:
Calculate purity for a pure state:
In summary, when thinking about the state of a qubit, you can view it in several equivalent ways:
◼
As a linear combination (a complex-valued 2-vector) in a given basis.
◼
As a real-valued 3-vector representing Cartesian coordinates of the Bloch vector {x,y,z}.
◼
As the same point in spherical coordinates {r,ϕ,θ}.
Generate different representations of a random state:
Pauli operators and Bloch sphere
Pauli operators and Bloch sphere
Pauli operators provide a natural choice for representation of the density matrix:
Check that Pauli matrices are Hermitian:
Find the eigensystem of Pauli-Z:
Verify the −1 eigenvalue by applying the operator to the candidate state and confirming the result is exactly the original state multiplied by −1 (same amplitudes, same relative phases, overall sign flip only):
Verify the +1 eigenvalue by applying the operator to the candidate state and confirming the output equals the input (no change in amplitudes or relative phases).
From now on, unless stated otherwise, we will choose eigenvectors to be normalized. The eigenvectors then form an orthonormal basis for the vector space.
We will call the eigenvector with the positive eigenvalue as by + subscript and the negative one by - subscript. Putting this together, we can represent the Bloch-sphere positions of the eigenvectors of the Pauli operators as follows:
Each of the six states shown above lie along the Cartesian axes of the sphere. For various historical reasons, these states have alternate names in the context of quantum computing.
Note that Pauli-Z eigenvectors are the same as the computational basis:
Higher Dimensions
Higher Dimensions
The simplest quantum system is a qubit, represented by a two-dimensional complex vector space. For example, show the T-type magic state’s amplitudes in the computational basis:
Quantum systems can also be higher-dimensional; a three-level system is called a qutrit, such as a spin-1 system.
Applying the qutrit (3D) Hadamard to the 0 state yields an equal superposition of all three basis states, each with the same magnitude and evenly spaced relative phases:
For the 3D Hadamard we use the same “H” symbol; the difference is that it acts on qutrit (3-level) wires rather than qubit wires.
Pay attention to the notation for the corresponding basis:
Show the matrix form of the 3D Hadamard:
Let’s focus on a special qutrit. A three-level lambda system (Λ system) is an atom or qutrit. Think of the levels forming the shape of the Greek letter Λ: the two lower “arms” meet at the upper “node.” Two lasers are used, one drives the left lower state to the excited state (pump), the other drives the right lower state to the excited state (Stokes).
This setup is a workhorse in quantum optics because it lets you move population or create superpositions between the two stable lower states while keeping the fragile excited state mostly unoccupied, enabling techniques like Stimulated Raman Adiabatic Passage (STIRAP), electromagnetically induced transparency, and coherent population trapping.
Consider an operator as follows:
Find the eigensystem of the Hamiltonian:
As one can see, one of the eigenvectors correspond to the eigenvalue zero.
The above state is called a dark state. A dark state is a special superposition of the two long-lived ground states in a three-level Λ system that does not couple to the excited state under the applied lasers. Practically, the pump tries to lift amplitude from one ground state and the Stokes from the other; in the right superposition their effects on the excited level cancel by destructive interference, so the system does not absorb light.
Check the quantum states are the same:
Probability and Measurement
We will discuss the concept of probability and how it relates to the frequency of different outcomes in a repeatable measurement. Then we will show how probabilities in quantum theory help us calculate joint and marginal probabilities.
Key Concepts
Key Concepts
◼
Random Outcome, Probability Distribution, Marginal Probability, Joint Probability
◼
Marginal Probability
◼
Joint Probability
Frequency vs probability
Frequency vs probability
You’re no doubt familiar with coin flips or dice rolls as ways to generate random outcomes. For our purposes, think of a random outcome as a definite result from a repeatable experiment. Randomness here means that several different outcomes are possible, and while we may know their probabilities, there is no way to determine which specific outcome will occur before running the experiment.
You can find much more information on probability and statistics in any of the following Wolfram U courses: Introduction to Probability, and Introduction to Statistics.
Quantum theory provides a way to compute the probability distribution over possible measurement outcomes. You can think of a probability distribution as a rule that assigns a nonnegative probability to each possible outcome of an experiment, with all probabilities adding up to 1. In quantum circuits, this distribution is typically defined over the discrete set of possible bitstrings.
Let’s look at a couple examples of generating random outcomes to build intuition.
Suppose you want to sample a random integer between 1 and 10. One realization of this process is as follows:
The above function returns a uniformly random integer from 1 to 10 (inclusive).
Now examine the count of each number in the sequence above.
Now examine the frequency of each number in the sequence above:
Now examine the frequency of each number across different sequences as the sequence length increases:
As you can see, with more repetition of the same experiment, the observed frequency of outcomes gets closer to the true probability distribution.
Now let’s consider the case where we assign a specific weight to each number: {1,1,2,3,4,4,3,2,1,1}.
We can compute the corresponding probabilities by normalizing the weights; that is:
We can compute the corresponding probabilities by normalizing the weights; that is:
If we run the experiment many times, we expect the frequency of results to converge to the probabilities above. Now let’s generate different data samples of results for 10, 100, and 10,000 runs. As the number of realizations increases, the observed frequencies should get closer to the expected probabilities.
Calculate frequencies for each experiment:
Visualize the results:
As expected, with more runs of the experiment, the observed frequencies get closer to the expected probabilities (law of large numbers).
Now let’s consider a case analogous to three different players rolling dice and collecting their joint outcomes. Of course, the quantum case can differ markedly from the classical one—classically, similar correlations might require prearranged strategies or communication. For the moment, however, we will set aside interpretation and focus only on the probabilities of the outcomes (i.e., the joint distribution and any marginals), leaving the discussion of correlations for later.
Joint vs Marginal Probabilities
Joint vs Marginal Probabilities
We will prepare the system in a special initial state. For now, we will skip the details of what this state is and focus only on the probability of outcomes. Using quantum theory, we can calculate the joint probabilities of the measurement results, that is, the probabilities for all possible tuples of 0s and 1s listed above.
Generate the corresponding multivariate distribution of outcomes:
Visualize the contingency table of the distribution:
Since we have the multivariate distribution, we can compute the probability of any scenario by summing over the appropriate outcomes. Let’s consider a few cases.
Calculate the probability of getting 0 for qubit-1 and 1 for qubit-3 (and any result for qubit-2)
Let’s calculate the above probability step-by-step:
2
.Extract the probabilities associated with those selected outcomes.
3
.Add those probabilities together.
We can use the multivariate distribution and compute the full list of outcome–probability pairs:
Now suppose we do not care about qubit 3 and want to focus only on the statistics of qubits 1 and 2. To do this, we compute the marginal distribution by summing over the outcomes of qubit 3. (In the quantum formalism, this corresponds to taking the partial trace over qubit 3 to obtain the reduced state of qubits 1 and 2.)
To get the marginal distribution, the calculation as follows:
- first group outcomes based on the values of the first and second elements (we are only interested in the marginal distribution qubit 1 and 2)
- for each group, add up the values of probabilities
- first group outcomes based on the values of the first and second elements (we are only interested in the marginal distribution qubit 1 and 2)
- for each group, add up the values of probabilities
The same process can be done more cleanly using built-in Wolfram Language functionality. This makes it much easier to compute other probabilities as well (you’ll see this shortly).
Calculate the marginal distribution
Visualize the contingency table of the marginal distribution:
Calculate the probability of getting 0 for qubit-1 from the marginal probability distribution:
Calculate the probability of getting 0 for qubit-1 from the overall probability distribution:
Let’s focus again on the computation that we did for finding two-dimensional marginal distribution from the three dimensional one, by averaging over third system:
The analysis above used standard probability theory throughout; only the initial probabilities were derived from quantum mechanics. That said, the rules of quantum theory provide a recipe for obtaining the quantum state of qubits 1 and 2 by averaging over all contributions from qubit 3, and thus getting probabilities directly from a new quantum state. For this aim, one should trace over the degrees of freedom of qubit 3, which yields the reduced state for qubits 1 and 2.
Trace out the qubit-3 (which is the 3rd subsystem) from the overall state:
Note what happened: the three-qubit state was pure, but the reduced state of qubits 1 and 2 is mixed (after tracing out qubit 3, due to entanglement).
As expected, this reduced state yields the same marginal probabilities as before:
Show the probabilities obtained from marginal distribution:
In future chapters, we will discuss in details the idea of tracing out a subsystem and how to describe the state of composite systems in quantum theory.
Quantum States: Multi-Particle Cases
We will discuss the tensoring of vector spaces, which provides a recipe for constructing larger systems from smaller ones. This recipe comes with some unique features. For example, there exist states that cannot be written as a tensor product of smaller states. We will examine these states and their distinctive feature: entanglement.
Key Concepts
Key Concepts
◼
Tensor product
◼
Kronecker product
◼
Composite systems
◼
Separable states vs entangled states
Tensor Product Structure
Tensor Product Structure
Consider a quantum system that is a qubit. This means its state lives in a 2-dimensional Hilbert space. The corresponding computational basis elements are
Of course, quantum systems can have other dimensions. For example, consider a 3-dimensional Hilbert space (a qutrit). The corresponding computational basis elements are
Now consider a composite system made of two qubits. How can we construct the larger space from the Hilbert spaces of the single qubits? This is the fundamental idea behind the tensor product.
The exact computation for basis tensoring is done as follows:
There are some minor details regarding the shapes of arrays after tensoring, which we’ll skip for now. The good news is that this tensor-product structure is fully supported in the Wolfram Quantum Framework: you can obtain the corresponding computational basis of a composite system simply by supplying the dimensions of the subsystems. For example:
This idea of tensoring applies directly to quantum states and operators. For example, we can create the composite state of a two-qubit system from its subsystem states:
Show the traditional form of above composite state:
As another example, let’s create a composite (i.e., multi-particle) operator as Pauli-Z acting on qubit 1 and Pauli-Y acting on qubit 2:
Show the matrix form explicitly:
Separable vs Nonseparable Objects
Separable vs Nonseparable Objects
An important point is this: the larger space built from smaller spaces can contain elements (states or operators) that cannot be written as a simple tensor product of two elements. For now, we will focus only on quantum states.
Consider a uniform superposition of a two qubit system:
The above state can be obtained by two Hadamard operators acting on 2-qubit register state:
Create uniform superposition of qubit 1 and 2:
Create the corresponding tensor product state:
Check the new state is the same as the previous one:
How, in general, can we check whether a state is separable? A systematic way to handle the general cases is the Schmidt decomposition. It says that any two-part pure state can be expressed as a sum of paired basis states for the two subsystems, each paired term weighted by a nonnegative number called a Schmidt coefficient. The state is separable exactly when there is only one nonzero Schmidt coefficient. In that situation, the state reduces to a single paired basis term (often called the Schmidt basis form), which means it is a simple product state rather than an entangled one.
In the Wolfram quantum framework, you only need to transform the state into its Schmidt basis and check Schmidt coefficients.
Show the composite state after the Schmidt decomposition:
Show amplitudes in the Schmidt basis:
Now let’s consider another example. We will use one of Bell states
Show its Dirac notation:
As we can see from the Schmidt decomposition, there is more than one nonzero Schmidt coefficient. This means the state is not separable; in other words, it is entangled.
Check the state is entangled:
An important question is how to quantify entanglement. We will cover standard measures and criteria in the next chapter.
Superposition and Entanglement
We will discuss the concepts of quantum superposition and entanglement in more detail. We will show how a linear combination of quantum states can look different from one basis to another, and how this relates to whether states are separable or entangled. We will then explain how to test whether a state is entangled and how to quantify the amount of entanglement.
Key Concepts
Key Concepts
◼
Superposition
◼
Entanglement
◼
Partial Trace
Superposition
Superposition
Superposition and entanglement are two fundamental characteristic traits of the quantum world. Superposition is a direct consequence of the linearity of quantum dynamics, while entanglement stems from the tensor-product structure of the underlying vector spaces together with the linearity.
Check the final state of the circuit is a uniform superposition:
Show the Dirac notation in the corresponding basis:
This representation can also be misleading, because it is a linear combination (i.e., a quantum superposition) in the computational basis. If you rewrite the same state in a different basis, it may take a very different form.
Transform the state in the Pauli-X basis:
Transform the state in the Pauli-Y basis:
Given the infinite choices of bases to represent a state, which basis is most convenient for a given task? Let’s discuss practical criteria for choosing a basis.
Let’s consider the effect of phase operator on 1-qubit computational basis vs Pauli-X basis:
For the X-rotation gate, the Pauli-X eigenbasis is the most natural basis to describe its effect.
A basis transformation can be done also for a composite state. For example, consider the state coming out of this circuit:
Execute the circuit and show the Dirac notation of the state:
If we transform this state to the Pauli-X basis, the form of the superposition changes. In particular, if the state is an eigenstate of X, it appears as a single basis vector in the X-basis (so the superposition “disappears”). Otherwise, it remains a superposition—just expressed in terms of the X-basis vectors.
In other words, the representation of the state in the computational basis shows a superposition, so it is not immediately clear whether the state is a tensor product of two single-qubit states. However, if we rewrite the same state in another basis (for example, the eigenstates of Pauli-X) and the factorization becomes explicit, then the state is separable (not entangled) and can indeed be written as a tensor product. Note that separability is a property of the state itself, not the basis; a different basis can simply make that property more evident.
If a state is separable, we say it is not entangled.
One way to confirm that a state is separable (for pure states) is to trace out a subsystem and check that the resulting reduced state is the same single-system state you specified in the product. Equivalently, both reduced states are pure, which indicates the overall state is a product (not entangled).
Additionally, for separable states, the reduced state is a pure state:
Let’s discuss entanglement in more detail.
Entanglement
Entanglement
Entanglement is when a composite quantum system has a well-defined overall state, but its parts cannot be assigned complete, independent states.
To create an entangled state, you will need a gate that is not separable. A famous gate that can be used is CNOT. Let’s see the effect of CNOT on the computational basis:
Calculate the final state of above circuit:
Show it in the Dirac notation:
Calculate the corresponding measurement probabilities:
Consider the state one gets after measuring above state. This is usually called post-measurement state. It will be a mixed state of 00 and 11, with the corresponding probabilities. It can be written as:
As you can see, the mixed state yields the same measurement probabilities as the original state.
In other words, one instance of measurement statistics alone does not make it obvious whether the state is entangled.
Test if above pure state is entangled or not:
Test if above the post-measurement state is entangled or not:
For multi-qubit systems, be sure to specify the partition of subsystems when you call QuantumEntangledQ, (always check the documentation pages).
Another way to test whether a state is entangled is as follows. First, compute the reduced states by performing partial traces. Then compare the tensor product of the reduced states with the original state. If they are the same, the state is not entangled; otherwise, it is entangled.
Generate the reduced state of qubit 1:
Generate the reduced state of qubit 2:
Compare the tensor product of the reduced states with the original state:
Since they are not the same, it means the original state was entangled state.
The above criterion works only for pure states. For mixed states, however, separability does not generally imply equality with the product of the marginals (many separable mixed states are mixtures of product states), so additional tests are needed.
Show that above approach does not work for an initial mixed state:
So although the result is False, but the initial state is not entangled.
Last but not least, given an entangled state, an interesting question is to quantify the entanglement. One common measure is called the generalized concurrence, which is a measure for the entanglement monotone. See the documentation page of QuantumEntanglementMonotone for more details.
Calculate the concurrence for the above state:
Calculate the concurrence for the Bell state:
As you can see, the Bell state is maximally entangled, it exhibits the strongest possible two-qubit entanglement (e.g., one bit of entanglement entropy, concurrence equal to 1).
Entanglement can extend beyond only two qubits. The GHZ circuit is shown below:
The outcome of above circuit is a state is usually called as GHZ state:
We also have GHZ as a named state in the Wolfram quantum framework:
Check GHZ state is an entangled state:
Calculate its concurrence:
A Quick Tour of Quantum Gates
This chapter offers a streamlined overview of quantum gates, focusing first on single-qubit operations that create superposition and control phase, then on multi-qubit gates that generate and manipulate entanglement. We survey core primitives and how they compose into universal sets, highlighting the role of controlled interactions such as CNOT, CZ, and SWAP. The goal is to give readers a compact, working intuition for how quantum gates shape computation, from isolated rotations to coordinated, entangling dynamics.
Key Concepts
Key Concepts
◼
Quantum logic operations
◼
Single-qubit quantum gates
◼
Multi-qubit quantum gates
Introduction
Introduction
Quantum circuits are usually represented using conventional names for the corresponding gates. For example, consider the circuit below:
Single-Qubit Gates
Single-Qubit Gates
Single-qubit gates are the building blocks of quantum computation. Each one acts on a single qubit, changing its state without touching the rest of the qubits. You can think of them as moving of a point on the Bloch sphere, steering a qubit from one configuration to another while preserving quantum amplitudes overall. Because any multi-qubit algorithm ultimately relies on carefully shaped single-qubit transformations combined with entangling operations, mastering these gates is essential for designing circuits, controlling interference and preparing useful superpositions.
In practice, single-qubit gates include familiar primitives like Pauli X, Y, and Z, which implement axis flips; the Hadamard, which creates and removes balanced superpositions; phase-type gates such as S and T that adjust relative phase without changing measurement probabilities; and continuously tunable rotations that let hardware enact arbitrary angles around chosen axes. Together they form a universal toolkit for shaping quantum states: calibrating amplitudes, sculpting phases, and setting up interference patterns that later multi-qubit gates can exploit.
Pauli gates
Pauli gates
Pauli operators are a common set of single-qubit gates. The Pauli-Z operator acts like a phase flip: it leaves the 0 state unchanged and adds a minus sign to the 1 state. In other words, if a qubit has some amount of 0 plus some amount of 1, applying Z keeps the 0 part the same and flips the sign of the 1 part. (By comparison, X swaps the 0 and 1 states, and Y also swaps them but introduces a phase.)
Effect of Pauli-Z on the state vector:
Effect of Pauli-Z in the Dirac notation:
The Pauli-Z gate is equivalent to a phase rotation by an angle of pi. Aside from an overall global factor (a “global phase” that doesn’t affect measurement outcomes), they act the same on any qubit: the 0 part is unchanged, and the 1 part picks up a minus sign.
Effect of Phase-π gate in the Dirac notation :
Additionally, Pauli-Z operator can be seen as flipping eigenstates of Pauli-X
The Pauli-Z gate turns the plus state (the equal mix of 0 and 1 with the same sign) into the minus state (the equal mix of 0 and 1 with opposite signs)
Check that applying the Pauli-Z gate to the plus state returns the minus state.
The Pauli-Z gate turns the minus state (equal mix of 0 and 1 with opposite signs) into the plus state (equal mix with the same sign).
Check that applying the Pauli-Z gate to the minus state returns the plus state.
Let’s visualize the effect of the Pauli-Z gate on different states by comparing the Bloch vectors of the initial and final states.
Pauli-X is also called the “NOT” operator because it acts like a NOT gate on the computational basis.
Check that applying Pauli-X to the 0 state yields the 1 state.
Check that applying Pauli - X to the 1 state yields the 0 state .
Let' s visualize the effect of the Pauli - X gate on different states by comparing the Bloch vectors of the initial and final states .
Pauli-Y on the 0 state acts like a phase-sensitive flip: it turns 0 into 1, up to an overall phase.
Similarly, Pauli-Y on the 1 state acts like a phase-sensitive flip: it turns 0 into 1, up to an overall phase.
Let' s visualize the effect of the Pauli - Y gate on different states by comparing the Bloch vectors of the initial and final states. Note that for the computational basis, the overall phase is not observable.
Hadamard gate
Hadamard gate
Another important single-qubit gate is the Hadamard gate.
This gate transforms a register state into a uniform superposition state.
Check the result is truly a uniform superposition:
Show the effect of H-gate on a generic quantum state:
Show matrix form of H-gate:
Family of phase-like gates
Family of phase-like gates
The phase gate is another important single-qubit gate.
It introduces a phase on the 1 state.
Show the matrix form of phase gate:
The S gate is another important single-qubit gate.
It introduces a phase on the 1 state.
Show matric form of S-gate:
S gate is the same as phase-π/2 gate:
The T gate is another common single-qubit gate.
It also introduce a phase on the 1 state.
Show matrix forma of T gate:
T gate is the same as phase - π/4 gate :
The label for the gate is obtained as follows:
Show that the phase shift is similar to a phase operator:
A special case of adding a phase is adding a global phase. This is what we usually call a global phase gate.
Since the phase is global (the same factor in front of all terms in the linear combination), it is not observable—it does not change the physical state.
Family of rotation gates
Family of rotation gates
Rotation around x-axis:
Show the effect of X-rotation on a generic quantum state:
Show the matrix form of x-rotation:
As mentioned before, an x-rotation is a rotation around the x-axis on the Bloch sphere.
Rotation around y-axis:
Show the effect of y-rotation on a generic quantum state:
Show the matrix form of y-rotation:
As mentioned before, an y-rotation is a rotation around the y-axis on the Bloch sphere.
Rotation around z-axis:
Show the effect of z-rotation on a generic quantum state:
Show the matrix form of x-rotation:
As mentioned before, an z-rotation is a rotation around the z-axis on the Bloch sphere.
The U3 gate is a general single-qubit rotation formed by combining the earlier rotations. It is defined by three angles.
Show the matrix forma of U3:
For example, generate three angles, and a point on the Bloch sphere:
Visualize the 3D point and its corresponding Bloch vector:
Visualize the transformed point using Euler rotations and the corresponding Bloch vector after U3:
A special case of the U3 gate is the U2 gate, specified by two angles.
Show matrix form of U2:
Multi-Qubit Gates
Multi-Qubit Gates
We now focus on multi-qubit gates. These are gates that cannot be written as a simple tensor product of single-qubit gates. Among multi-qubit gates, conditional (controlled) gates are especially important, because they serve as universal entanglers. Practically, you can take any of the single-qubit gates discussed before and make a controlled version. You designate a control qubit and a target qubit: the gate checks whether the control is in 0 or 1, and then, depending on the choice, control-0 (if the control is 0) or control-1 (if the control is 1), it applies the chosen gate to the target qubit.
Family of control NOT
Family of control NOT
CNOT (or CX) flips the target qubit when the control qubit is in the 1 state.
How CNOT transform 2-qubit computational basis:
CNOT is the same as CX:
Show the matrix form of CNOT gate:
As mentioned earlier, CNOT is one of the most important multi-qubit gates for generating entangled states. Example: prepare two qubits in a product state by putting qubit 1 into a uniform superposition with a Hadamard gate and leaving qubit 2 in the 0 state.
Check if this state is entangled or not:
Apply CNOT gate on the state and check if it is entangled or not:
As one can see, the CNOT gate transforms the state into an entangled state.
C0-NOT (or C0-X) flips the target qubit when the control qubit is in the 0 state.
How C0-NOT transforms 2-qubit computational basis:
Show the matrix form of C0-NOT gate:
Family of control phase
Family of control phase
Conditional Pauli-Z gate:
How CZ transforms 2-qubit computational basis:
Show the matrix form of CZ gate:
Conditional phase gate:
How CP transforms 2-qubit computational basis:
Show the matrix form of CP gate:
SWAP gate:
How SWAP transforms 2-qubit computational basis:
Show the matrix form of SWAP gate:
Root-SWAP gate:
How Root-SWAP transforms 2-qubit computational basis:
Show the matrix form of Root-SWAP gate:
Family of control rotation
Family of control rotation
Conditional rotation gate with Pauli-Z:
Ising-type entanglers are two-qubit unitaries generated by Pauli product interactions. They are like time evolutions under an “Ising” Hamiltonian. Any nontrivial angle produces entanglement; at special angles they’re locally equivalent to familiar gates such as CNOT. They are also native gates to many types of quantum hardware.
Family of Ising rotation
Family of Ising rotation
Ising ZZ (pure conditional phase):
Ising YY:
Ising XX:
3-qubit gates and more
3-qubit gates and more
Show Toffoli’s matrix form:
Show how a Toffoli gate acts on the computational basis of three-qubits:
Toffoli gate can be decomposed in terms of single-qubit gates and CNOTs as follows:
Show the above circuit acts the same as Toffoli:
Another important 3-qubit gate is Fredkin gate. It is also called CSWAP gate because it is conditional SWAP gate that conditionally exchanges two qubits. It is used in swap-test, data movement, and reversible sorting/comparison.
Show Fredkin’s matrix form:
Show how a Fredkin gate acts on the computational basis of three-qubits:
Fredkin gate can be also decomposed in terms of single-qubit gates and CNOTs as follows:
Show the above circuit acts the same as Fredkin:
Deutsch-Jozsa Algorithm
We will discuss the Deutsch-Jozsa algorithm. It decides whether a promised function on n-bit inputs is constant or balanced using a single oracle call. The Deutsch-Jozsa circuit is designed in a way that if the function is constant, all amplitude concentrates on the all-zeros output; if balanced, that outcome vanishes and some nonzero string appears. A bit-flip oracle and a phase oracle are equivalent here because initializing the target in the minus state turns the bit flip into an input-dependent phase.
Key Concepts
Key Concepts
◼
Boolean function
◼
Constant Boolean function
◼
Balanced Boolean function
◼
Deutsch-Jozsa
Statement of the Deutsch-Jozsa Problem
Statement of the Deutsch-Jozsa Problem
Let’s consider Xor in 3 variables, as a specific case, which is a balanced function. Keep in mind that you have a black-box access to it, and being told that it is either constant or balanced.
Count the number of False and True outputs over all 8 inputs for the 3-bit XOR (parity) function:
Up to the fourth query, all outcomes are identical, so you cannot decide yet. The fifth query produces a different outcome, confirming the function is balanced. Let’s walk through the procedure step by step.
Now consider a different input ordering, for example, swap the 3rd and 5th entries from the previous list.
This time, after the third query, you can conclude the function is balanced. Let’s walk through the steps.
Deutsch-Jozsa Oracles
Deutsch-Jozsa Oracles
Consider the following balanced Boolean function on three input bits:
Show its truth table:
Show explicitly that this function is balanced by listing all eight inputs and verifying that four outputs are 1 and four are 0.
The quantum Deutsch–Jozsa algorithm can use two oracle types. The Boolean oracle acts on an n-qubit input register plus one ancilla qubit: it leaves the input unchanged and flips the ancilla exactly when the function evaluates to 1.
An important feature: if the ancilla is initialized in the minus state, the Boolean oracle leaves it unchanged and instead tags solutions by a negative phase on the corresponding n-qubit terms.
The Deutsch–Jozsa phase oracle uses no ancilla and applies a negative phase to input states that satisfy the function.
Deutsch-Jozsa Algorithm
Deutsch-Jozsa Algorithm
Show the Deutsch–Jozsa circuit for the previously discussed Boolean function:
Pay close attention to the measurements. In Deutsch–Jozsa, the measurements are in the Pauli-X basis. The same circuit can also be presented in an equivalent form as follows.
For the Deutsch–Jozsa phase oracle, as noted, there is no ancillary qubit. The overall circuit is:
Find all constant and balanced Boolean functions on three input bits. (Constant: all 0s or all 1s; Balanced: four 1s and four 0s across the eight inputs.)
For three input bits (eight inputs): 70 balanced functions and 2 constant functions.
Bernstein-Vazirani Algorithm
We will discuss Bernstein-Vazirani algorithm. Bernstein–Vazirani finds a hidden n-bit string using one oracle call instead of n. Prepare the n input qubits in equal superposition and the extra “answer” qubit in a state that turns flips into phases. Query the bit oracle once; its action doesn’t store information in the answer qubit but kicks back a phase pattern onto the inputs that encodes the hidden string. Apply Hadamards to convert that phase pattern into a single basis state corresponding to the hidden string. Measure the inputs and read the string with certainty. The speedup comes from superposition, phase kickback, and interference, reducing queries from n to one.
Key Concepts
Key Concepts
◼
Oracle function
◼
Bernstein-Vazirani (BV) Algorithm
Statement of the Bernstein-Vazirani Problem
Statement of the Bernstein-Vazirani Problem
In many computer science problems, it is common to assume there is some kind of oracle function that is used in order to compute partial results for use in the rest of an algorithm. In practice, the oracle could be a database query or some similar operation.
Let’s consider a secret sequence of 0 and 1:
Check that the result is the same as the secret code:
Quantum Bernstein-Vazirani Algorithm
Quantum Bernstein-Vazirani Algorithm
Recall the secret sequence from before:
The quantum BV oracle for this sequence is given by:
In order to use this oracle to discover the secret code, only one query is necessary. Using the phenomenon of phase kickback, it is possible to send a uniform superposition of all possible sequences (as measured in the computational basis) and encode the solution in the three control qubits.
The full circuit would look like this:
Execute the above circuit and get the result:
It is clear that, in the new basis, the state is represented more compactly, and the idea of a uniform superposition with the answer qubit in the minus state is made explicit.
As before, in you look at the code above, we did a basis transformation.
The final step is measurements. Note we only measure n-qubits.
Therefore, the algorithm gives the secret code in only a single query.
The key feature of the BV algorithm is that the final measurement yields a single, definite result, the secret string. While this is elegant in theory, in practice, noise can interfere with the algorithm’s performance. In the next section, we will briefly discuss the impact of noise.
Effects of Noise
Effects of Noise
While solving the problem in only a single query to the quantum oracle is possible theoretically, real quantum circuits involve some errors caused by various effects. All of the previous circuits you have considered did not take this phenomena into account.
The following circuit defines the BV algorithm but introduces a noise channel just before the measurements can be performed. You might imagine this noise is from imperfect measurement or from the cumulative effect of previous errors in the circuit.
A noisy version of the previous circuit might look like this:
Notice that the measurement distribution now depends on the probability of the noise channels affecting each qubit:
If the so-called depolarizing noise channels affect the qubits with probability under 5%, the chance of returning the secret code is still quite high:
The following animation shows the effect of increasing the depolarizing probability:
As the noise rate increases, the probability of the intended outcome decreases. When noise reaches its maximum level, all outcomes occur with equal probability, meaning the noise effectively randomizes or smears the distribution of results.
Grover Search Algorithm
Key Concepts
Key Concepts
◼
Boolean function
◼
Grover Boolean oracle
◼
Grover Phase oracle
◼
Grover diffusion
Statement of the Grover Search Problem
Statement of the Grover Search Problem
Grover’s search is a core quantum algorithm. The task: given a Boolean function on n-bit inputs with one or more marked inputs (where the function returns True), find a marked input using as few oracle queries as possible.
Define a Boolean function
Now let’s examine its truth table:
Let’s count the number of possible combinations of variable values that yield True when supplied as arguments to the Boolean function
Grover’s key advantage can be illustrated as follows: by repeating the Grover circuit twice, the success probability can reach 100%, whereas a comparable classical strategy is about 20%.
Another subtlety of Grover’s algorithm is that there is an optimal number of Grover iterations to maximize the success probability. As the illustration shows, the classical success probability increases monotonically with more queries, while Grover’s success oscillates and can decrease if you go past the optimum.
Let’s dive in and examine the details of Grover’s algorithm. We will set up the register, define the oracle, apply the Grover iterate (oracle plus diffusion), and analyze how repeated iterations amplify the marked states to enable high-probability retrieval of the solution.
Grover oracle
Grover oracle
Grover’s algorithm commonly uses two oracle types: the Boolean oracle and the phase oracle. Both encode information about the solution to a Boolean function. In the Boolean oracle, the solution is written to an ancillary (target) qubit. In the phase oracle, there is no ancilla; the solution is encoded in the phase. Let’s examine them in more details.
Boolean oracle
Boolean oracle
Using the previous truth table, we can reproduce it with a quantum Boolean oracle. The oracle leaves the index register unchanged and flips the ancillary qubit exactly for inputs that satisfy the Boolean function, matching the table.
First, generate the corresponding Boolean oracle’s quantum circuit:
The diagram of the Boolean oracle:
Show how the oracle transforms states:
As one can see, the Boolean oracle circuit reproduce the same result as the classical ones.
Show the effect of the Boolean oracle on the new initial states:
One can see that the oracle introduces a relative phase only on the terms that are solutions of the Boolean function.
Let’s verify that the final states are physically identical to the initial ones, since the oracle introduced only a global phase (which has no observable effect).
As expected, only the solutions get a different phase shift. Note we have calculated that shift quantum mechanically.
Phase oracle
Phase oracle
Another common Grover oracle is the phase oracle. The key difference from the Boolean oracle is this: with a Boolean oracle, the solution is written to an ancillary (target) qubit; with a phase oracle, there is no ancilla and the solution is encoded as a phase. Let’s examine the phase oracle in more detail.
Create the corresponding phase oracle of the Boolean function:
The diagram of oracle:
As one can see, the oracle circuit reproduce the same result as the classical ones, but this time the solution information is in the phase.
Grover’s Algorithm
Grover’s Algorithm
The full Grover search operation looks like this:
The second block of gates is known as the Grover diffusion operator. The combination of the Boolean oracle and Grover diffusion operator are applied together in one iteration of the algorithm. To take advantage of the phase kickback introduced by the controlled gates, the circuit will need an initial set of gates and finally a measurement of the first three qubits.
One iteration of the Grover algorithm for the current example would look like this:
The measurement distribution for this circuit is shown below:
Recall that, for the states above, the Boolean function outputs are:
From the full measurement distribution, sum only the probabilities of inputs labeled True (1 in the above list).
As one can see, with the chance of around 65%, we can get the correct solution of the Boolean function by only one iteration of Grover.
Now what happens if two iterations are used instead of one?
The circuit is longer, but now the probability for obtaining the desired outcome is increased:
In this case, with the chance of most 100%, we can get the correct solution of the Boolean function by only two iterations of Grover.
We can also calculate the success probability given the number of Grover iteration:
As you can see, the probability rises then falls and rises again as more and more Grover iterations are applied.
Quantum Arithmetic
We will cover quantum arithmetic circuits centered on the Quantum Fourier Transform, showing how QFT enables addition and multiplication, how these operations are implemented in the Fourier basis, and how to transform to and from that basis.
Key Concepts
Key Concepts
◼
Discrete Fourier Transform
◼
Quantum Fourier Transform (QFT)
◼
Fourier (phase) Basis
◼
Phase adder
Discrete Fourier Transform and QFT
Discrete Fourier Transform and QFT
The discrete Fourier transform is a mathematical transformation that is very useful in processing data. It has many applications and is often employed when one wants to analyze signals over time.
The Quantum Fourier Transform maps an n-qubit computational-basis state to a uniform superposition whose phases encode the original index in Fourier order:
In fact, QFT is a basis change. For a general 2-qubit state with four amplitudes (ordered as 00, 01, 10, 11), the 2-qubit QFT applies a 4-point discrete Fourier transform to those amplitudes. Each basis component spreads over all four outputs with specific relative phases; the new four amplitudes are the Discrete Fourier Transform of the original four.
The circuit to implement a 3-qubit QFT is given below:
One can show that the overall effect of QFT (i.e. its matrix) is exactly the same as usual Fourier matrix:
Transforming a quantum state into the Fourier basis is exactly the action of the QFT on that state. Think of the QFT as the basis change to the Fourier basis.
Phase Basis Encoding
Phase Basis Encoding
As we discussed before, the computational basis is not the only way to encode classical information in a quantum state. Recall that the relative phase between two states can be experimentally distinguished. Thus, even if two states have the same probability to obtain outcomes in the computational basis, they are not the same state and will give different probabilities for outcomes in some other basis.
With this in mind, consider the following circuit:
The above circuit encodes an integer in n qubits. Here, the integer 1 is encoded in three qubits. In 3-bit binary, 1 is 001.
But how do you "read out" this phase information if all the measurements are performed in the computational basis? If you simply try to measure, the information encoded in the qubit phases is lost.
As you can see from the changing colors in the above plot, the information of the input state is transferred to information about the relative phases of each qubit (with respect to a uniform superposition in the computational basis). But that information is not accessible if measuring in the computational basis:
As you can see from the plot, the phase information is not immediately accessible in the computational basis. Instead, you must perform the inverse of the quantum fourier transform, and then measure.
By performing the inverse quantum Fourier transform, all of the phase information is now encoded in the computational basis. The measurement outcome is now the same as the number which was encoded in the phase basis:
With the phase basis and QFT in hand, you can implement quantum arithmetic circuits. The final state 001 matches the 3-qubit binary encoding of the integer 1.
Quantum Phase Adders
Quantum Phase Adders
This circuit first performs a quantum Fourier transform to get the input information into the phase basis, then applies an operation to add 3 in the phase basis, then performs an inverse quantum Fourier transform, and finally measures the results:
Find the measurement probabilities:
Given the outcome with maximum probability, determine the corresponding integer (using the bitstring-to-integer mapping):
Generic Addition
Generic Addition
Let’s walk through the above circuit step-by-step: Initialize the first three wires in 101 (which is 5) and the last three in 001 (which is 1). Apply QFT to the last three (to move them to the Fourier basis), use the phase adder to add in the Fourier basis, then apply the inverse QFT to return them to the computational basis. Recall the final result is encoded in the last three qubits.
With probability 1, the measured outcome of this circuit gives the state corresponding to 4 when the input states both correspond to 2.
Multiplication
Multiplication
The above circuit combines QFT and inverse QFT blocks with the multiplication subroutine in the Fourier basis.
Create the multiplication circuit:
Show the circuit diagram:
Show the expanded diagram up to the level 2:
As expected, you get 9 with 100% probability when running this circuit:
001100 bit-string corresponds to 12:
Quantum Phase Estimation Algorithm
We will discuss the Quantum Phase Estimation (QPE) algorithm. This algorithm estimates the eigenvlaues of a unitary by applying controlled powers of it to an eigenstate, imprinting the phase on ancilla qubits, then using the inverse quantum Fourier transform to read out a binary approximation; precision scales with the number of ancillas, enabling applications like factoring and eigenvalue estimation.
Key Concepts
Key Concepts
◼
Eigenvalue
◼
Eigenvector
◼
Quantum Fourier Transform
◼
Quantum Phase Estimation (QPE)
Eigenvectors and Eigenvalues
Eigenvectors and Eigenvalues
Eigenvectors and eigenvalues are concepts from the theory of linear algebra, and they are frequently used in analyzing the solutions of all sorts of mathematical models.
As an example, consider the matrix corresponding to the Pauli Z operator in the computational basis:
Check the matrix is Hermitian:
Check all eigenvalues are Real:
Of course, there is also a direct way of checking unitarity in the Wolfram Language:
Find the corresponding eigenphases:
Let’s consider a random unitary matrix:
Remember that any random generation follows a specific distribution. Here, the random unitaries are sampled uniformly from the unitary group (the Haar measure over n-dimensional unitary matrices).
Given above random unitary operator, let’s obtain its eigenvalues:
Quantum Phase Estimation: Simple Example
Quantum Phase Estimation: Simple Example
So far we computed eigenvalues classically. Quantum Phase Estimation uses phase kickback to extract an eigenstate’s phase, providing the information needed to recover the eigenvalues. For pedagogical purposes, consider the following unitary operator; we will use QPE to estimate its eigenphases.
Calculate the eigenvalues:
Calculate the eigenphases:
Let’s explore QFE for the unitary operator we generate above. Let’s consider the first eigenvector:
Prepare the target in the unitary’s first eigenstate. Initialize the control qubits in uniform superposition with Hadamards. Apply the sequence of controlled powers, then the inverse QFT, and measure the control register.
Execute the circuit and plot the measurement probabilities.
Compute the percentage error in the estimated phase (argument) of the first eigenvalue:
Quantum Phase Estimation: Complicated Example
Quantum Phase Estimation: Complicated Example
Visualize the overall Dirichlet kernel, and the individual kernels, for different linear combinations of eigenstates.
Consider the same circuit, but prepare the target qubit in a fixed (pedagogical) pure state chosen to mimic a random state, so we can illustrate the key effects clearly.
Plot the measurement probabilities for the control qubits.
We simulated the circuit without explicit measurement. After the unitary evolution, we traced out the target qubit to obtain the reduced state of the control register, then read off the computational-basis probabilities from that reduced state.
Now let’s obtain the overall Dirichlet kernel from simulations without assuming any knowledge of the unitary’s eigenstates or eigenphases. First, implement code that mimics experimental outcomes: a variable (randomResult) samples control-register measurement results according to the predicted probabilities each time the it is executed.
Calculate a smooth kernel distribution based on the data obtained above (after transforming it into the corresponding integers):
Note that the smooth distribution we obtained is the overall Dirichlet kernel.
As you can see, it has only one peak. Let’s increase our resolution by adding more control qubits, while preparing the target qubit in the same state:
Repeat the same steps to obtain the corresponding overall Dirichlet kernel.
Given new data, find the overall Dirichlet kernel
Now we can see two peaks clearly.
Let’s get two measurement results corresponding to the two peak we obtained:
Calculate the estimated eigenphases for the two peaks:
Compare the estimated values with the true values:
In practice, the situation can be more complex. If increasing the number of control qubits still yields no clear multiple peaks, the target’s initial state likely needs adjustment. With suitable state-preparation strategies, you can obtain informative outcomes. These techniques are beyond this course, but are worth exploring—the computational machinery is exactly what we’ve used above.
Shor’s Algorithm for Factorization
We will present a concise overview of Shor’s algorithm as a hybrid quantum–classical method for integer factorization. The classical stages reduce factoring to order finding and later convert the quantum output into nontrivial factors via greatest common divisors. The quantum core uses phase estimation on a modular multiplication unitary to extract periodicity, from which the order is inferred and factors are recovered with high probability. An illustrative example and operator construction clarify how the circuit is built and why it yields an efficient factoring procedure compared to known classical algorithms.
Key Concepts
Key Concepts
◼
Hybrid algorithm
◼
Shor’s algorithm
◼
Order finding problem
Factorization Through Order Finding
Factorization Through Order Finding
Efficient integer factoring matters in many applications (e.g., cryptography). For some special integers, fast classical methods exist. More generally, factoring can be reduced to an order-finding problem, for which there is an efficient quantum algorithm: Shor’s order-finding. In a hybrid approach, classical pre-processing reformulates factoring as order finding, the quantum routine solves that subproblem, and classical post-processing converts its output back to the factors. If both classical stages are efficient, this hybrid yields a faster overall factoring method than known classical algorithms.
Full algorithm
Full algorithm
The steps for Shor’s probabilistic algorithm to factor are as follows:
2
.2
.Otherwise, you have already found a nontrivial factor.
3
.1
.If is even, continue.
3
.2
.If is odd, the algorithm failed, and you must try with a new .
4
.2
.Otherwise, you must try with a new .
Example: Step-by-Step Factorization
Example: Step-by-Step Factorization
Verify that is neither even nor a prime number:
Check that and are coprime:
Compute the multiplicative order of modulo :
Note that above step is the one that has a quantum subroutine. We will discuss it later.
Order Finding with a Quantum Circuit
Order Finding with a Quantum Circuit
Remember that a quantum operator can be specified as a matrix that defines its action on states. What happens if you try to define a multiplication operator using the most straightforward approach? Is such an operator unitary?
You can mathematically specify such a matrix without difficultly; however, the resulting matrix is not unitary. This is mathematically fine, but you cannot implement such an operation using any rules consistent with quantum mechanics. Thus, the simplest approach to define a quantum operator for this problem is ruled out.
Instead, specify an operator such that it has the expected action on elements which are less than , and leaves elements through the maximum size of the Hilbert space unchanged.
Therefore, the desired unitary operator can be implemented as follows:
Notice that this operator raised to the multiplicative order of modulo gives the identity operator:
Consider the following phase estimation circuit for the unitary operator that implements multiplication by modulo (in this case 13 modulo 15):
Compute the measurement distribution:
Plot the distribution:
Post-Processing the Eigenvalue Estimations
Post-Processing the Eigenvalue Estimations
Exploring the Details
Exploring the Details
First, let’s label the new basis elements according to their eigenvalues (and an arbitrary index, since there are repeated eigenvalues):
Now, each new basis vector has an arbitrary index and you can see its corresponding eigenvalue:
This (perhaps surprising) fact is what allows the quantum phase estimation algorithm to sample uniformly from the distinct eigenvalues.
Quantum Key Distribution: BB84 scheme
BB84 (named after Bennett and Brassard's 1984 paper) is a quantum protocol for securely establishing a shared secret key between two parties. It is the earliest and most well-known example of Quantum Key Distribution (QKD), and it uses properties of quantum mechanics, such as the fact that measuring a quantum state disturbs it, to detect any eavesdropping and ensure the secrecy of the generated key.
Key Concepts
Key Concepts
◼
BB84 protocol.
◼
Quantum Key Distribution
One-time pad encryption
One-time pad encryption
In this section, we briefly review the one-time pad encryption by using a secret key, securely shared between two parties (e.g., Alice and Bob). We let Alice and Bob share the same secret key securely. Once they have that key, they use it in an ordinary classical one-time pad encryption.
First, Alice and Bob need a way to turn text into bits. Let’s define a function that is doing just that.
Define a function that returns the ASCII bits of a string:
When you give it a string like “Wolfram”, it takes each character, finds its ASCII code (a number that represents that character), and then converts that number into its binary representation, that is, a sequence of zeros and ones.
Select a secret key (shared securely between Alice and bob):
The output is a list of lists: one list of seven bits for each character. This list of bit blocks is what both Alice and Bob possess as their shared secret key.
Then Alice prepares the message she wants to send, which here is the word “Quantum”.
Select a message (Alice wants to send it to Bob):
Now Alice has two aligned lists: one is the message bits, one is the key bits, both the same length, with each character of the message lined up with a corresponding character of the key. To encrypt, Alice combines the message bits with the key bits using the bitwise XOR operation. XOR is a very simple rule on individual bits: if the two bits are the same, the result is zero; if they are different, the result is one. The result is a ciphertext that looks like nonsense if you try to interpret it as plain text, and without the key, it gives no information about the original message.
Generate a ciphertext by taking the XOR of each bit of the message with each bit of the secret key (Alice does this, and send the ciphertext to Bob):
Alice then sends this ciphertext over the classical channel to Bob. An eavesdropper can see the ciphertext, but without the key, the one-time pad guarantees that the message is information-theoretically secure, provided the key is truly random, at least as long as the message, and used only once. When Bob receives the ciphertext, he decrypts it using the exact same operation: bitwise XOR with the same key.
Decode the ciphertext by taking the XOR of each bit of it with each bit of the secret key (Given Alice message, Bob does this step):
Show the text of the decoded text:
So, in plain language, Alice and Bob shared a secret string of bits. Alice turned her message into bits, combined it with the secret bits using XOR to produce an encrypted bit string, and send that to Bob. Bob used the same secret bits and the same XOR operation to reverse the process and get the original message back.
Bennett-Brassard quantum solution (BB84)
Bennett-Brassard quantum solution (BB84)
As an example of a quantum key distribution (QKD), we consider BB84 protocol. It starts with Alice. She decides she’s going to send nine qubits to Bob. Note that the number of qubits (here nine) is completely your choice and not special to BB84 at all. For each qubit, Alice needs two random choices: which bit she wants to encode (zero or one), and which basis she wants to use to encode it. In BB84, there are two possible bases: the Z basis and the X basis. We will first choose nine random bits for Alice, and then nine random bases, each either Z or X. So, for each position from one to nine, Alice now has a pair: a bit and a basis.
Generate bases and bits of Alice randomly for nine qubits:
Depending on what bit and what base, Alice follows the following protocol for sending a qubit to Bob:
Visualize Alice’s protocol:
Also recall the common convention for the computational basis:
Next, take every pair of Alice’s random bit and basis and pass them through Alice’s sending rules. That produces a list of nine actual qubit states: some of them are plain zero or one in the Z basis, and some are the plus or minus states in the X basis.
Therefore, given Alice’s bit and bases that are generated randomly, she will send Bob these qubits:
The above sequence of qubits is what Alice will physically send down the quantum channel to Bob.
Now it’s Bob’s turn. Bob doesn’t know which basis Alice used for each qubit, so he follows the BB84 rule: for every qubit he receives, he randomly chooses a basis of his own, again either Z or X.
Bob randomly generate a sequence of either Z-basis or X-basis of measurement:
It means, Bob applies the measurement operators in above bases on qubits he relieved from Alice. Each measurement destroys the original qubit state and produces an outcome in the basis Bob chose. To see a specific “run” of what could happen, we will simulate one possible set of outcomes, giving a concrete basis state for each qubit, such as the plus or minus state in X, or the plus or minus state in Z.
Generate measurement objects for Bob:
Return one possible realization of Bob' s series of measurements (note some will always return the same result, some randomly, depending on what Alice' s qubit is and what direction Bob measures):
Once Bob has a list of measurement outcomes, he needs to convert these into bits. The convention in this code is simple: whenever he gets the “plus” outcome in either basis, he calls that bit zero; whenever he gets the “minus” outcome in either basis, he calls that bit one.
At this stage, Alice has her original sequence of bits and bases; Bob has his bits and his bases. Many of Bob’s bits will not match Alice’s bits, because sometimes he measured in the “wrong” basis. That is the core of BB84: if Bob chooses a different basis from Alice, his result is completely random and carries no reliable information about Alice’s bit.
The next step is the classical sifting process. Alice and Bob now talk over a normal (but authenticated) classical channel. Importantly, they do not reveal their bits. Instead, they reveal only the bases they used for each position. For each index from one to nine, they compare Alice’s basis and Bob’s basis. If they used the same basis, they keep that position; if they used different bases, they discard it.
Zip together Alice’s bits, Alice’s bases, and Bob’s bases into triples, then select only the triples where Alice’s basis equals Bob’s basis:
Alice extracts her bits from these surviving triples to get her secret key. Bob does the same with his bits: he takes his bits from the positions where the bases match.
Both resulting lists of bits are identical! Alice and Bob have successfully distilled a shorter, but shared, secret key out of the original nine transmissions.
The key that came out is shorter than the number of qubits Alice sent. That’s expected. Whenever Bob happened to guess the wrong basis, that position got thrown away. In the long run, about half the positions survive. If Alice and Bob want a key of a certain length, they just keep running this process, Alice sending more qubits, Bob measuring with random bases, and both of them doing the public basis comparison and discarding mismatches, until the number of agreed positions reaches the desired length. This can be implemented as follows.
This can be implemented as follows. Take the current partial keys for Alice and Bob, runs one more “round” of the protocol for a single qubit (choosing a random bit and basis for Alice, generating a qubit, choosing a random basis for Bob, measuring, mapping Bob’s outcome to a bit), then checks if the bases matched. If they did, append the new bit to both Alice’s and Bob’s keys; if not, leave the keys unchanged. Then, using NestWhile, repeatedly call this function, starting from empty keys, until Alice’s key reaches a length of five bits.
For example, the key length is set as 5 bits in the following:
All of this is the “quantum” front end that you can connect to the one-time pad we discussed about earlier. BB84 gives Alice and Bob a shared random key, built in such a way that any eavesdropping would disturb the statistics of their measurements and be detectable. Once they have that key, they can use it exactly as in the one-time pad example: combine it with a message using XOR to encrypt, and combine again with the same key to decrypt.
Acknowledgment
A portion of this book builds on an early draft prepared by John McNally of Wolfram Research during his work on this project. Many of the ideas and their presentation grew through countless conversations with colleagues at Wolfram Research, including Nikolay Murzin, Bruno Tenorio, and Sebastian Rodriguez. I would also like to express my gratitude to Stephen Wolfram, founder and CEO of Wolfram Research, for his steady support throughout the years I’ve led the quantum initiative. Finally, my heartfelt thanks go to the late Michael Trott (friend, mentor, and teacher) who, sadly, passed away before I completed this draft. He is deeply missed.