|
| 1 | +# Shor period finding example |
| 2 | +# Find the period of f(x) = 13^x mod 15 |
| 3 | + |
| 4 | +import math |
| 5 | +import os |
| 6 | + |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +from dotenv import load_dotenv |
| 9 | +from mqss.qiskit_adapter import MQSSQiskitAdapter |
| 10 | +from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister |
| 11 | + |
| 12 | +# Load environment variables |
| 13 | +load_dotenv() |
| 14 | +token = os.getenv("MQP_TOKEN") |
| 15 | +backend_name = os.getenv("MQP_BACKEND") |
| 16 | + |
| 17 | +adapter = MQSSQiskitAdapter(token=token) |
| 18 | +backend = adapter.get_backend(backend_name) |
| 19 | + |
| 20 | +# Parameters |
| 21 | +n = 4 # number of qubits in x-register |
| 22 | +shots = 200 |
| 23 | + |
| 24 | + |
| 25 | +def f(x): |
| 26 | + return pow(13, x, 15) |
| 27 | + |
| 28 | + |
| 29 | +# Build circuit |
| 30 | +qr_x = QuantumRegister(n, "x") |
| 31 | +qr_fx = QuantumRegister(4, "f(x)") |
| 32 | +cr_x = ClassicalRegister(n, "c_x") |
| 33 | +qc = QuantumCircuit(qr_x, qr_fx, cr_x) |
| 34 | + |
| 35 | +# Superposition |
| 36 | +for q in range(n): |
| 37 | + qc.h(qr_x[q]) |
| 38 | +qc.barrier() |
| 39 | + |
| 40 | +# f(x) implementation |
| 41 | +qc.x(qr_fx[0]) |
| 42 | +qc.x(qr_fx[2]) |
| 43 | +qc.x(qr_x[0]) |
| 44 | +qc.ccx(qr_x[0], qr_x[1], qr_fx[0]) |
| 45 | +qc.x(qr_x[0]) |
| 46 | +qc.ccx(qr_x[0], qr_x[1], qr_fx[1]) |
| 47 | +qc.x(qr_x[0]) |
| 48 | +qc.x(qr_x[1]) |
| 49 | +qc.ccx(qr_x[0], qr_x[1], qr_fx[2]) |
| 50 | +qc.x(qr_x[0]) |
| 51 | +qc.ccx(qr_x[0], qr_x[1], qr_fx[3]) |
| 52 | +qc.x(qr_x[1]) |
| 53 | +qc.barrier() |
| 54 | + |
| 55 | +# QFT |
| 56 | +for q in range(n - 1, -1, -1): |
| 57 | + qc.h(q) |
| 58 | + for k in range(1, q + 1): |
| 59 | + qc.cp(math.pi / 2**k, q - k, q) |
| 60 | + qc.barrier() |
| 61 | +for q in range(n // 2): |
| 62 | + qc.swap(q, (n - 1) - q) |
| 63 | +qc.barrier() |
| 64 | + |
| 65 | +qc.measure(qr_x, cr_x) |
| 66 | + |
| 67 | +# Run job |
| 68 | +job = backend.run(qc, shots=shots, queued=True) |
| 69 | +counts = job.result().get_counts() |
| 70 | +print("Results:", counts) |
| 71 | + |
| 72 | +# Normalize and plot |
| 73 | +keys = list(counts.keys()) |
| 74 | +x_vals = [int(k, 2) for k in keys] |
| 75 | +probs = [v / sum(counts.values()) for v in counts.values()] |
| 76 | + |
| 77 | +x_sorted, p_sorted = zip(*sorted(zip(x_vals, probs))) |
| 78 | + |
| 79 | +plt.figure() |
| 80 | +plt.grid(zorder=0, axis="y", linestyle="--") |
| 81 | +plt.bar(x_sorted, p_sorted, zorder=3) |
| 82 | +plt.xticks(rotation=65) |
| 83 | +plt.ylabel("Probability") |
| 84 | +plt.xlabel("x") |
| 85 | +plt.show() |
0 commit comments