Add examples and clean up some stuff

This commit is contained in:
2024-12-08 22:06:58 -08:00
parent 5adc755be4
commit 9b8584bd6f
10 changed files with 275 additions and 102 deletions
+38
View File
@@ -0,0 +1,38 @@
;;;; An example of Grover's algorithm (quantum search)
(in-package :cl-quantum/examples)
(defun count-grover-iterations (bits targets)
"Count the number of iterations it takes to have a high probability of finding
TARGETS in a search space of 2^BITS."
(values (floor (* (/ pi 4) (sqrt (/ (ash 1 bits) targets))))))
(defun make-grover-circuit (bits target)
"Generate a quantum circuit that runs Grover's algorithm over a state of BITS
bits and finds when the state is equal to TARGET."
(assert (> (ash 1 bits) target)
(bits target)
"Target bit of ~s out of range for state with ~s bits." target bits)
(with-build-circuit
;; Setup
(loop for i below bits do (:h i))
;; Oracle
(loop
repeat (count-grover-iterations bits 1)
do
(loop for i below bits
for cur = (logand (ash target (- i)) 1)
when (zerop cur)
do (:x i))
(:ncz 0 (loop for i from 1 below bits collect i))
(loop for i below bits
for cur = (logand (ash target (- i)) 1)
when (zerop cur)
do (:x i))
;; Diffuser
(loop for i below bits do (:h i))
(loop for i below bits do (:x i))
(:ncz 0 (loop for i from 1 below bits collect i))
(loop for i below bits do (:x i))
(loop for i below bits do (:h i)))))