M A N N I N G Mariia Mykhailova Solving problems with Q# and Qiskit IN DEPTH
Quantum application software development workflow Address the issues revealed by testing. Optimize the algorithm based on performance evaluation results. Come up with an algorithm. Check that the code is correct by running it on quantum simulators. Estimate performance of the algorithm and its resource requirements. Run the end-to-end code on a quantum computer to get the problem answer. Implement classical code. Implement quantum code.Develop Validate Evaluate Run on hardware
Quantum Programming in Depth Solving problems with Q# and Qiskit Mariia Mykhailova M A N N I N G SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com © 2025 Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. ∞ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Development editor: Dustin Archibald Technical editor: Guenevere E. Prawiroatmodjo Review editor: Dunja Nikitovic Production editor: Keri Hales Copy editor: Alisa Larson Proofreader: Jason Everett Technical proofreader: Edoardo Altamura Typesetter: Ammar Taha Mohamedy Cover designer: Marija Tudor ISBN 9781633436909 Printed in the United States of America
brief contents 1 Quantum computing: The hype and the promise 1 Part 1 Building your own library ............................. 17 2 Preparing quantum states 19 3 Implementing quantum operations 51 Part 2 Learning information about a quantum system .............................................. 87 4 Analyzing quantum states 89 5 Analyzing quantum operations 121 Part 3 Solving a classical problem using a quantum algorithm ...................................... 153 6 Evaluating classical functions on a quantum computer 155 7 Grover’s search algorithm 190 8 SolvingNqueens puzzle usingGrover’s algorithm 215 9 Evaluating the performance of quantumalgorithms 241 iii
contents preface ix acknowledgments xi about this book xiii about the author xvii about the cover illustration xviii 1 Quantum computing: The hype and the promise 1 1.1 Your second book on quantum computing: The prerequisites 2 1.2 The hype and the promise: What kinds of problems can quantum computing solve? 3 1.3 A peek inside the fridge: How does quantum computing work? 5 Algorithms 5 Hardware 7 Software 9 Quantum application software development workflow 11 1.4 Why learn quantum computing? 12 1.5 Learning quantum computing through quantum programming 13 1.6 Further reading 14 Part 1 Building your own library ............................. 17 2 Preparing quantum states 19 2.1 Preparing a single-qubit state 21 Math 22 Qiskit 24 Q# 25 iv
CONTENTS v 2.2 What does your solution do? 27 Qiskit 28 Q# 29 2.3 Preparing a two-qubit state 30 Refresher: Controlled gates in Dirac notation 31 Math 33 Qiskit 34 Q# 36 2.4 Testing your solution 39 Qiskit 40 Q# 42 2.5 Preparing a multiqubit state 43 Math 44 Qiskit 46 Q# 47 2.6 Further reading 48 2.7 Going beyond 49 3 Implementing quantum operations 51 3.1 Implementing a single-qubit gate 55 Math 56 Qiskit 58 Q# 58 3.2 What does your solution do? 59 Qiskit 59 Q# 60 3.3 Testing your solution 62 Qiskit 62 Q# 63 3.4 Matrix decomposition 64 3.5 Implementing a two-qubit block-diagonal unitary with 2× 2 blocks 66 Refresher: Controlled gates in matrix notation 66 Math 68 Qiskit 69 Q# 70 3.6 Implementing a two-qubit CS unitary 71 Math 71 Qiskit 72 Q# 72 3.7 Implementing a two-qubit block-antidiagonal unitary with 2× 2 blocks 73 Math 73 Qiskit 74 Q# 74 3.8 Implementing a two-block block-diagonal unitary of arbitrary size 75 Math 76 Qiskit 78 Q# 79 3.9 Implementing a CS unitary of arbitrary size 80 Math 80 Qiskit 82 Q# 82 3.10 Implementing an arbitrary unitary of arbitrary size 83 Math 83 Qiskit 84 3.11 Further reading 84 3.12 Going beyond 85
vi CONTENTS Part 2 Learning information about a quantum system ............................................... 87 4 Analyzing quantum states 89 4.1 Reading out information from a quantum system 91 Math 91 Qiskit 93 Q# 95 4.2 Distinguishing superposition states consisting of distinct basis states 98 Math 99 Qiskit 101 Q# 102 4.3 Distinguishing superposition states consisting of overlapping basis states 102 Math 103 Qiskit 105 Q# 106 4.4 Distinguishing nonorthogonal states with minimum error 106 Math 106 Qiskit 109 Q# 109 4.5 Reconstructing the state from multiple copies 109 Math 110 Qiskit 111 Q# 112 4.6 Joint/parity measurements: Extracting partial information from a state 113 Math 114 Qiskit 116 Q# 117 4.7 Further reading 118 4.8 Going beyond 118 5 Analyzing quantum operations 121 5.1 Distinguishing unitaries 123 Math 123 Qiskit 127 Q# 128 5.2 Reconstructing the unitary 129 Math 130 Qiskit 131 Q# 132 5.3 Finding eigenvalue of the given eigenvector: The phase estimation problem 133 Phase kickback 136 Iterative phase estimation 137 Adaptive phase estimation 139 Quantum Fourier transform 142 Quantum phase estimation 144 Qiskit 146 Q# 148 5.4 Going beyond 150 Part 3 Solving a classical problem using a quantum algorithm .......................................153 6 Evaluating classical functions on a quantum computer 155 6.1 Reversible computing: Mapping classical computation onto quantum 157
CONTENTS vii 6.2 Evaluating single-bit functions 160 Math 161 Qiskit 165 Q# 166 6.3 Testing reversible computations 168 Qiskit 170 Q# 171 6.4 Evaluating Boolean operations 173 Math 174 Qiskit 178 Q# 179 6.5 Evaluating Boolean expressions 180 Math 181 Qiskit 185 Q# 186 6.6 Going beyond 188 7 Grover’s search algorithm 190 7.1 Quantum oracles 193 Math 194 Qiskit 199 Q# 201 7.2 Grover’s search algorithm 202 Definitions 203 Math 208 Qiskit 211 Q# 212 7.3 Going beyond 213 8 SolvingN queens puzzle usingGrover’s algorithm 215 8.1 Naive solution 218 8.2 Encoding constraints in the search space 221 Math 221 Qiskit 224 Q# 228 8.3 Changing problem encoding 232 Math 233 Qiskit 235 Q# 237 8.4 Going beyond 239 9 Evaluating the performance of quantumalgorithms 241 9.1 Choosing the classical solution for comparison 244 9.2 Performance comparisons: Asymptotic vs. practical 246 9.3 Estimating performance of a quantum solution 247 9.4 Azure Quantum Resource Estimator: An overview 251 9.5 Solutions’ performance for the N queens puzzle 255 9.6 Further reading 256 9.7 Going beyond 256 appendix A Setting up your environment 259 index 263
preface I joined Microsoft Quantum and, by extension, the world of quantum computing in early 2017, just as the team started developing the quantum programming language that later became Q#. I spent a big part of the next eight years learning quantum computing myself and helping others do the same, both as part of my job at Microsoft and in the course I teach at Northeastern University. And, while doing this, I noticed several gaps in the way quantum computing was taught. First, a lot of material on quantum computing focused on its mathematical aspects only. I am an applied mathematician by training, so I’m comfortable with math. But I’m a software engineer by trade, and I’m a lot more comfortable with algorithms when I can implement them and experiment with running them! My first project in quantum computing education, the Quantum Katas, focused on introducing the basics—quantum states and gates, measurements, and simple algorithms—through a series of programming problems that the learner would solve to internalize the theory. The second gap shows up later in the learning journey. There are plenty of “quantum computing 101” resources that focus on introductory concepts. But, once you’ve mastered the basics, what’s next? What does “quantum computing 201” look like? If you’ve only ever run simple circuits, how do you start implementing real quantum algorithms? How do you test the quantum code you write?What do you need to know about quantum programming for future fault-tolerant quantum computers? And, ultimately, how do you figure out whether your quantum solution to the problem you’re looking at is going to do better than a classical algorithm? This book aims to answer these questions. viii
PREFACE ix The book offers you a selection of problems, from building quantum programming libraries to solving classical problems using quantum algorithms, and walks you through the solutions. As part of the discussion, I introduce the quantum software development workflow, from figuring out the algorithm suitable to solve the problem at hand to implementing the solution, testing it, and evaluating its performance. Each problem ends up being implemented as an end-to-end software project. Throughout the book I use Qiskit and Q#—two of the quantum programming languages used for quantum computing research today—to make sure the tools and methods I talk about are relevant to the current quantum programming landscape. There are, of course, plenty of topics I could not include in the book: domain- specific applications, the architecture of fault-tolerant quantum computers and the software stack we’re building for them, and debugging large-scale quantum algorithms, among others. I hope that this book will show you how to think about quantum computing as a software engineer and problem solver and thus equip you with the mindset you’ll need to continue your pursuit of knowledge!
acknowledgments First and foremost, I want to thank all the students I’ve had the privilege of teaching and all the learners and software developers I’ve had the pleasure of working with outside the formal classroom setting. It was their experiences, questions, and doubts that inspiredme to write this book and helpedme shape the answers and explanations it needed to provide. Next, my gratitude goes to mentors and peers who taught me everything I know about quantum computing and quantum programming. Here is an incomplete list: Everybody in the Quantum Architectures and Computation group, for welcom- ing me to the world of quantum computing back in 2017 and guiding me through my first steps in it. Wim van Dam, for the discussions of quantum algorithms in general and phase estimation in particular. Mathias Soeken, Michal Stechly, and everybody at the Quantum Resource Esti- mation Workshop at IEEE Quantum Week, for the conversations about evalu- ating the performance of quantum algorithms that ultimately convinced me to dedicate a whole chapter to this topic. Thanks to everyone who works on creating quantum software development toolkits, especially Azure Quantum Development Kit and Qiskit. It would be a lot harder to write a book about quantum programming if quantum programming tools didn’t exist! I want to thank the members of Manning’s acquisitions, development, and pro- duction teams who made this book possible and helped it become the best version of itself. Many thanks go to the reviewers and the Manning Early Access Program x
ACKNOWLEDGMENTS xi (MEAP) subscribers: Alain Couniot, Alberto Maldonado-Romo, Alexey Vyskubov, Amit Rambhai Modhwadia, Anup K Parikh, Bhagvan Kommadi, Brandon Darlington- Goddard, Christophe Pere, Daniel Guijo, Domingo Salazar, Fulvio Bruno, Gary Pass, James Weaver, Kaelyn Ferris, Kelvin D. Meeks, Krzysztof Kamyczek, Laud Bentil, Marco Venere, Maxime Boillot, Michael Wright, Michal Stechly, Nupur Baghel, Patrick Regan, Piero Giacomelli, Pierre Wan-Fat, Potito Coluccelli, Prasad Kukka- malla, Premkumar Reddy Jakkidi, Ricardo Verschueren, Saidaiah Yechuri, Moham- mad Shahnawaz Akhter, Shivani Mayekar, Sonja Krause-Harder, Srikar Vedantam, Srinivas Vamsi Parasa, Tony Holdroyd, and William E. Wheeler. I am also grateful to my technical editor, Guen Prawiroatmodjo, experimental physicist and software engineer, as well as my technical proofer, Edoardo Altamura. Your feedback and suggestions helped make this a better book. On a more personal note, I’d like to start by thanking my awesome husband, Sergii Dymchenko. From giving me Python advice to reminding me to exercise, he was there every step, helping me get this book done and keeping me sane. To my friends, thank you for your unwavering support and patience during the writing of this book; you will be seeing more of me now that I’m done! And finally, thanks to the creators of Good Omens TV show, the fandom, and the King County Library System: you were the perfect escape when I needed to take a break from all things quantum!
about this book Quantum Programming in Depth isn’t designed to teach you quantum computing from scratch, although I hope that you will learn a lot from it regardless of how much you already know when you start. It is meant to help you deepen your understanding of the fundamental concepts and apply them to solve problems, as well as expand your experience in quantum software development. This is a book you should not just browse or flick through. Each chapter offers you a project to do or a series of problems to solve, and, while it walks you through the mathematical solutions and then the coding implementations, you will learn the most if you try to solve the tasks and write the code yourself, and then take the time to attempt the additional projects from Going Beyond idea lists. The more effort you invest into working through this book, the easier you’ll find quantum computing problems you’ll encounter afterward. Who should read this book This book was written for people who are interested in learning quantum computing and quantum programming beyond the basics. It is aimed at learners who have taken an introductory course and want to deepen their knowledge, or perhaps have studied the theory and want to get hands-on experience putting it into practice. You should already have an understanding of basic concepts and terminology, such as quantum gates, measurements, and Dirac notation. This book will help you go from passing familiarity with the concepts of quantum computing to using them to solve realistic problems. You will become more confident as you write quantumprograms, test them, and learn to think about their performance to better understand the potential use cases of quantum computing. xii
ABOUT THIS BOOK xiii How this book is organized: A roadmap This book has nine chapters. The first chapter gives you a quick overview of quantum computing, the kinds of problems it might solve more efficiently than classical computing, and quantum hardware and software development. The remaining chapters are grouped into three parts. Part 1 includes two projects that can be used as building blocks for other, more complicated algorithms. This part also shows you how to write quantum code in Q# and Qiskit, run it on simulators, and test it: In chapter 2, you’ll create a library that prepares arbitrary quantum states. In chapter 3, you’ll learn to implement unitary transformations that are not part of the built-in gate set. Part 2 offers a collection of smaller projects that focus on learning information about quantum systems: Chapter 4 focuses on using measurements to get the necessary information about quantum states. Chapter 5 uses the tools from the previous chapter to get information about uni- tary transformations. A big part of chapter 5 is dedicated to the phase estimation problem, one of important tools in the quantum computing toolbox. Part 3 covers the end-to-end process of solving a classical problem using a quantum algorithm: Chapter 6 shows how classical functions can be represented and evaluated as part of quantum computations—this is the first step of quantum solutions to a lot of classical problems. Chapter 7 introduces Grover’s algorithm, one of the most famous quantum algorithms for solving search problems. In chapter 8, you’ll learn to use Grover’s search algorithm to solve realistic problems and see the steps that are involved in that. Finally, chapter 9 discusses the performance of quantum programs and the way we think about comparing quantum solutions with classical ones to figure out whether a quantum algorithm can show a practical quantum advantage for a particular problem. Each chapter is broken down into sections that focus on solving a specific task, learning to use a specific tool from the development toolkit, or implementing one part of the larger project. The goal of each section is to end up with working code in both Qiskit and Q#. At the end of each chapter, you’ll find a short section, Going Beyond, which provides a list of ideas of the ways to further develop the project from this chapter and similar projects you can do on your own. I encourage you to give them a try!
xiv ABOUT THIS BOOK About the code All the code written in this book can be found at https://github.com/tcNickolas/ quantum-programming-in-depth. The project folder for each section includes the complete tests for the code developed in this section, even if they are omitted from the book itself. Sections 2.1–2.3, 3.1–3.2, and 6.2 are the exception to this rule, since I don’t introduce the way to test the code written in these sections until later. The code for each problem solved is available in both Qiskit and Q#. Installation instructions for both Qiskit and Azure Quantum Development Kit, as well as the pytest package, are available in the appendix and in the GitHub repository. This book contains many examples of source code both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/quantum-programming-in-depth. The complete code for the examples in the book is available for download from the Manning website at https://www.manning.com/books/quantum-programming-in -depth and from GitHub at https://github.com/tcNickolas/quantum-programming -in-depth. liveBook discussion forum Purchase of Quantum Programming in Depth includes free access to liveBook, Man- ning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning .com/book/quantum-programming-in-depth/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/ discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest her interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.
ABOUT THIS BOOK xv Other online resources Are you looking to start with the very basics of quantum computing or even the linear algebra necessary for getting started? TheQuantumKatas (https://quantum.microsoft .com/experience/quantum-katas) are online tutorials that follow the same practical hands-on approach to learning as this book. They offer plenty of programming problems and exercises in Q#, so completing them gives you a head start on the projects in this book! As you work your way through the book and the code in each chapter, here are some additional resources to help you: Qiskit: – Qiskit documentation (https://docs.quantum.ibm.com/)—Complete docu- mentation for using Qiskit and IBM Quantum in a quantum software devel- opment workflow – Qiskit on GitHub (https://github.com/Qiskit/)—Repositories that host Qiskit source code, as well as a collection of tools for working with Qiskit. Q#: – Q# documentation (https://learn.microsoft.com/azure/quantum/)—Com- plete documentation for usingQ# and AzureQuantum in a quantum software development workflow. – Q# on GitHub (https://github.com/microsoft/qsharp/)—Source code for Q# compiler, simulators, and libraries, as well as a collection of Q# sample programs.
about the author Mariia Mykhailova is a principal quantum software developer at PsiQuantum, working on software for fault- tolerant quantum computation. Prior to that, she was a quantum software engineer at Microsoft Quantum, joining the team in early 2017, just in time to participate in the development of the first version of the quantum program- ming language that became Q#. Mariia created the Quan- tum Katas project, an open source collection of hands-on tutorials and programming problems for learning quan- tum computing. She is also a part-time lecturer at Northeastern University, teaching Introduction to Quantum Computing since 2020, and the author of the O’Reilly book Q# Pocket Guide. xvi
about the cover illustration The figure on the cover of Quantum Programming in Depth is “Habitant de Juppa,” taken from Balthasar Hacquet’s Images and Descriptions of Southwestern and Eastern Wenda, Illyrians, and Slavs, published in 1815. In those days, it was easy to identify where people lived and what their trade or station in life was just by their dress. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional culture centuries ago, brought back to life by pictures from collections such as this one. xvii
(This page has no text content)
Comments 0
Loading comments...
Reply to Comment
Edit Comment