mod bbht;
pub use bbht::search_unknown;
use core::f64::consts::FRAC_PI_4;
use rand_core::Rng;
use crate::{Oracle, PhaseOracle, StateVector};
#[must_use]
pub fn optimal_iterations(states: usize, marked: usize) -> usize {
if marked == 0 || marked >= states {
return 0;
}
let theta = libm::asin(libm::sqrt(ratio(marked, states)));
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "0 < θ ≤ π/2, so π/(4θ) is finite, at least 1/2 and below 2^12 for 2^24 states"
)]
let iterations = libm::floor(FRAC_PI_4 / theta) as usize;
iterations
}
pub fn amplify<O, F, C>(
state: &mut StateVector,
oracle: &mut PhaseOracle<O, F, C>,
iterations: usize,
) where
O: Oracle<C>,
F: Fn(usize) -> Option<C>,
{
state.reset();
hadamard_all(state);
for _ in 0..iterations {
oracle.apply(state);
diffuse(state);
}
}
pub fn search_known<O, F, C, R>(
state: &mut StateVector,
oracle: &mut PhaseOracle<O, F, C>,
marked: usize,
rng: &mut R,
) -> Option<usize>
where
O: Oracle<C>,
F: Fn(usize) -> Option<C>,
R: Rng + ?Sized,
{
amplify(state, oracle, optimal_iterations(state.states(), marked));
let index = state.sample(rng);
oracle.check(index).then_some(index)
}
fn diffuse(state: &mut StateVector) {
hadamard_all(state);
x_all(state);
state.mcz(0..state.qubits());
x_all(state);
hadamard_all(state);
}
fn hadamard_all(state: &mut StateVector) {
for qubit in 0..state.qubits() {
state.h(qubit);
}
}
fn x_all(state: &mut StateVector) {
for qubit in 0..state.qubits() {
state.x(qubit);
}
}
fn ratio(part: usize, whole: usize) -> f64 {
#[expect(
clippy::cast_precision_loss,
reason = "state counts are at most 2^24, exact in f64"
)]
let ratio = part as f64 / whole as f64;
ratio
}
#[cfg(test)]
mod tests {
use super::optimal_iterations;
#[test]
fn counts_the_optimal_iterations() {
assert_eq!(optimal_iterations(16, 0), 0);
assert_eq!(optimal_iterations(16, 16), 0);
assert_eq!(optimal_iterations(4, 1), 1);
assert_eq!(optimal_iterations(16, 5), 1);
assert_eq!(optimal_iterations(1024, 1), 25);
}
}