cl-quantum/examples/grover.lisp

39 lines
1.4 KiB
Common Lisp
Raw Normal View History

2024-12-08 22:06:58 -08:00
;;;; 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)))))