bernstein_vazirani.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # -*- coding: utf-8 -*-
  2. """
  3. Bernstein-Vazirani Algorithm
  4. ============================
  5. This algorithm finds a hidden integer :math:`a \in \{ 0, 1\}^n` from
  6. an oracle :math:`f_a` which returns a bit :math:`a \cdot x \equiv \sum_i a_i x_i \mod 2`
  7. for an input :math:`x \in \{0,1\}^n`.
  8. A classical oracle returns :math:`f_a(x) = a \dot x \mod 2`, while the quantum oracle
  9. must be queried with superpositions of input :math:`x`'s.
  10. To solve this problem classically, the hidden integer can be found by checking the
  11. oracle with the inputs :math:`x = 1,2,\dots,2^i,2^{n-1}`, where each
  12. query reveals the :math:`i`th bit of :math:`a` (:math:`a_i`).
  13. This is the optimal classical solution, and is :math:`O(n)`. Using a quantum oracle and the
  14. Bernstein-Vazirani algorithm, :math:`a` can be found with just one query to the oracle.
  15. The Algorithm
  16. -------------
  17. 1. Initialize :math:`n` qubits in the state :math:`\lvert 0, \dots, 0\rangle`.
  18. 2. Apply the Hadamard gate :math:`H` to each qubit.
  19. 3. Apply the inner product oracle.
  20. 4. Apply the Hadamard gate :math:`H` to each qubit.
  21. 5. Measure the register
  22. From this procedure, we find that the registers measured value is equal to that of
  23. the original hidden integer.
  24. """
  25. def bernstein_vazirani():
  26. import qcgpu
  27. num_qubits = 7 # The number of qubits to use
  28. a = 101 # The hidden integer, bitstring is 1100101
  29. register = qcgpu.State(num_qubits) # Create a new quantum register
  30. register.apply_all(qcgpu.gate.h()) # Apply a hadamard gate to each qubit
  31. # Apply the inner products oracle
  32. for i in range(num_qubits):
  33. if a & (1 << i) != 0:
  34. register.z(i)
  35. register.apply_all(qcgpu.gate.h()) # Apply a hadamard gate to each qubit
  36. results = register.measure(samples=1000) # Measure the register (sample 1000 times)
  37. print(results)
  38. if __name__== "__main__":
  39. bernstein_vazirani()