deskmerc/ quantum

Algorithms / KINGSTON

Quantum Field Report

Factoring 15 with order finding

Use phase estimation to look for the order of 2 modulo 15.

IBM job ID
dbvrp5anj2vs73dd2fd0
Submitted
19 Nov 2026 · 21:20 CST
QPU charge
2 seconds
Backend
ibm_kingston
Sampling
256 shots per recorded setting/case
Provenance
Quantum Field Report, page 8.

The question

Use phase estimation to look for the order of 2 modulo 15.

Circuit & method

An eight-qubit circuit uses a bit-rotation implementation of modular multiplication and compiles to 73 native CZ gates on Kingston. Classical continued fractions, modular checks and greatest common divisors verify samples.

PrepareState, codeword or problem instance
Run on KingstonRecorded physical circuit and settings
Measure & checkCounts, decoding and classical verification

Results

118/256 hardware shots yielded verified factors 3 × 5, compared with 152/256 in ideal simulation.

Measured outcomesAll-shot success; each bar runs from 0% to 100%.
Hardware verified factors118/256 · 46.1%
Ideal sampled factors152/256 · 59.4%

What this supports

The small modulus has a specially compact arithmetic circuit. A passing sample is a classically verified factor extraction, not evidence of advantage over classical factoring.

Percentages are rounded for reading. The original integer counts, physical layouts, settings and available uncertainty calculations remain in the records below. Sampling intervals do not account for drift or every systematic error.

Full experiment record

Every top-level field from the primary hardware JSON is reproduced below, including the complete saved measurement distributions where present. Field names and outcome strings retain their original order and spelling.

stage
done
backend
ibm_kingston
queues
{
  "ibm_fez": {
    "backend_name": "ibm_fez",
    "backend_version": "",
    "operational": true,
    "pending_jobs": 2,
    "status_msg": "active"
  },
  "ibm_kingston": {
    "backend_name": "ibm_kingston",
    "backend_version": "",
    "operational": true,
    "pending_jobs": 0,
    "status_msg": "active"
  },
  "ibm_marrakesh": {
    "backend_name": "ibm_marrakesh",
    "backend_version": "",
    "operational": true,
    "pending_jobs": 0,
    "status_msg": "active"
  }
}
shots
256
queue_snapshot_utc
2026-11-20T03:20:52.849486+00:00
tag
order-finding-15-20261119-first
gates
{
  "sx": 139,
  "rz": 112,
  "cz": 73,
  "x": 9,
  "measure": 4
}
initial_layout
[
  54,
  51,
  59,
  55,
  33,
  52,
  39,
  53
]
two_qubit_depth
62
two_qubit_gates
73
job_id
dbvrp5anj2vs73dd2fd0
ibm_status
DONE
counts
{
  "0000": 62,
  "0001": 4,
  "0100": 66,
  "0101": 3,
  "1000": 62,
  "1001": 2,
  "1100": 52,
  "1101": 4,
  "1110": 1
}
verified_factor_shots
{
  "3 x 5": 118
}
quarter_phase_shots
118
four_peak_shots
242
metrics
{
  "caller": "qiskit",
  "qiskit_version": "qiskit_ibm_runtime-0.52.1,qiskit-2.6.2*,qiskit_aer-0.17.2",
  "timestamps": {
    "created": "2026-11-20T03:20:53.367668Z",
    "finished": "2026-11-20T03:20:58.448125Z",
    "running": "2026-11-20T03:20:54.501137Z"
  },
  "usage": {
    "qpu_charge_time_seconds": 2,
    "value": 0.029506,
    "unit": "resource_units",
    "status": "complete",
    "details": [
      {
        "value": 0.029506,
        "unit": "resource_units",
        "metric": {
          "id": "caffe3ca-729c-5750-8777-df63bbf8bfd9",
          "value": 2
        }
      }
    ]
  },
  "circuits_execution_time_ns": 68315648
}

Simulation & checks

These are the supplied simulator records and their preserved variants. Their model, seed, settings and results appear exactly as saved. Shared simulator references on fresh-map pages describe the ideal graph protocol, rather than a new hardware-matched calibration.

field-report/outputs/Shor15-simulator.json · full record
{
  "counts": {
    "0000": 64,
    "0100": 74,
    "1000": 40,
    "1100": 78
  },
  "verified_factor_shots": {
    "3 x 5": 152
  },
  "quarter_phase_shots": 152,
  "four_peak_shots": 256,
  "shots": 256,
  "seed": 1936,
  "ideal_phase_probabilities": [
    0.25,
    0.0,
    0.0,
    0.0,
    0.25,
    0.0,
    0.0,
    0.0,
    0.25,
    0.0,
    0.0,
    0.0,
    0.25,
    0.0,
    0.0,
    0.0
  ]
}
noise-wall/results/Shor15-simulator.json · full record
{
  "counts": {
    "0000": 64,
    "0100": 74,
    "1000": 40,
    "1100": 78
  },
  "verified_factor_shots": {
    "3 x 5": 152
  },
  "quarter_phase_shots": 152,
  "four_peak_shots": 256,
  "shots": 256,
  "seed": 1936,
  "ideal_phase_probabilities": [
    0.25,
    0.0,
    0.0,
    0.0,
    0.25,
    0.0,
    0.0,
    0.0,
    0.25,
    0.0,
    0.0,
    0.0,
    0.25,
    0.0,
    0.0,
    0.0
  ]
}

Source code

Original experiment and verification programs are preserved byte for byte. These are historical listings; dependencies, authentication prompts and machine-specific input paths may need adjustment before a rerun.

  • shor15.pyQuantum Field Report.pdf / Experiment-source.zip · 7,594 bytes
  • shor15.pyThrough the Noise Wall.pdf / Kingston measurements and source.zip · 7,594 bytes
field-report/outputs/shor15.py · complete source
"""Order finding for multiplication by two modulo fifteen; one eight-qubit circuit."""
import argparse
import getpass
import json
import logging
import sys
import time
import traceback
from datetime import datetime, timezone
from fractions import Fraction
from math import gcd
from pathlib import Path

from qiskit import QuantumCircuit
from qiskit.circuit.library import QFTGate
from qiskit.primitives import StatevectorSampler
from qiskit.quantum_info import Operator, Statevector
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

ROOT = Path(__file__).resolve().parent
RESULT = ROOT / "Shor15-hardware.json"
SIM = ROOT / "Shor15-simulator.json"
TAG = "order-finding-15-20261119-first"
SHOTS = 256
SEED = 1936
PHASE = 4
N = 15
BASE = 2


def write(path, record):
    temp = path.with_suffix(".tmp")
    temp.write_text(json.dumps(record, indent=2), encoding="utf-8")
    temp.replace(path)


def controlled_multiplier(constant):
    # A cyclic left rotation is doubling on residues 0..14. Fix unused state 15.
    qc = QuantumCircuit(5, name=f"controlled_mul{constant}")
    swaps = {2: [(2, 3), (1, 2), (0, 1)], 4: [(0, 2), (1, 3)]}
    for first, second in swaps[constant]:
        qc.cswap(0, 1+first, 1+second)
    return qc


def circuit():
    qc = QuantumCircuit(PHASE + 4, PHASE, name="order_of_2_mod_15")
    work = list(range(PHASE, PHASE+4))
    qc.x(work[0])
    qc.h(range(PHASE))
    for bit in range(PHASE):
        constant = pow(BASE, 2**bit, N)
        if constant != 1:
            qc.compose(controlled_multiplier(constant), [bit, *work], inplace=True)
    qc.append(QFTGate(PHASE).inverse(), range(PHASE))
    qc.measure(range(PHASE), range(PHASE))
    return qc


def analyze(counts):
    if sum(counts.values()) != SHOTS:
        raise ValueError("Unexpected shot count")
    solutions = {}
    exact_quarters = 0
    for bits, count in counts.items():
        phase = Fraction(int(bits, 2), 2**PHASE)
        if phase in (Fraction(1, 4), Fraction(3, 4)):
            exact_quarters += count
        candidate = phase.limit_denominator(N-1).denominator
        if candidate % 2 or pow(BASE, candidate, N) != 1:
            continue
        half = pow(BASE, candidate//2, N)
        factors = sorted([gcd(half-1, N), gcd(half+1, N)])
        if factors[0] > 1 and factors[0] * factors[1] == N:
            label = " x ".join(map(str, factors))
            solutions[label] = solutions.get(label, 0) + count
    return {"counts":dict(sorted(counts.items())), "verified_factor_shots":solutions,
            "quarter_phase_shots":exact_quarters,
            "four_peak_shots":sum(counts.get(format(v,"04b"),0) for v in (0,4,8,12))}


def simulate():
    import numpy as np
    for constant in (2, 4):
        product = [(x*constant) % N for x in range(N)] + [N]
        expected = [2*(product[x//2] if x%2 else x//2) + x%2 for x in range(32)]
        assert np.allclose(Operator(controlled_multiplier(constant)).data, np.eye(32)[:, expected])
    qc = circuit()
    probabilities = Statevector.from_instruction(qc.remove_final_measurements(inplace=False)).probabilities(
        qargs=list(range(PHASE)))
    ideal = np.zeros(16)
    ideal[::4] = 0.25
    assert np.allclose(probabilities, ideal)
    result = StatevectorSampler(seed=SEED).run([qc], shots=SHOTS).result()[0]
    record = analyze(result.data.c.get_counts())
    record.update(shots=SHOTS, seed=SEED, ideal_phase_probabilities=ideal.tolist())
    write(SIM, record)
    print(record)


def compile_for(qc, backend):
    pm = generate_preset_pass_manager(backend=backend, optimization_level=3, seed_transpiler=SEED)
    return pm.run(qc)


def hardware():
    if not SIM.exists() or not sys.stdin.isatty():
        raise RuntimeError("Run the local check first and open an interactive key prompt")
    if RESULT.exists() and json.loads(RESULT.read_text())["stage"] == "done":
        return
    token = getpass.getpass("IBM Cloud API key (hidden): ").strip()
    if not token:
        return
    service = QiskitRuntimeService(channel="ibm_quantum_platform", token=token,
                                   plans_preference=["open"], region="us-east")
    if RESULT.exists():
        record = json.loads(RESULT.read_text())
        if "job_id" in record:
            job = service.job(record["job_id"])
        else:
            matches = service.jobs(job_tags=[TAG], limit=2)
            if len(matches) != 1:
                raise RuntimeError("Reconcile the previous submission before retrying")
            job = matches[0]
    else:
        qc = circuit()
        devices = {b.name:b for b in service.backends(simulator=False, min_num_qubits=qc.num_qubits)
                   if not b.is_mock}
        prepared = {}
        while True:
            queues = {name:b.status().to_dict() for name,b in devices.items()}
            active = [name for name,s in queues.items() if s["operational"] and s["status_msg"].lower()=="active"]
            if not active:
                raise RuntimeError("No active processor")
            name = min(active, key=lambda k:(queues[k]["pending_jobs"],k))
            if name in prepared:
                break
            prepared[name] = compile_for(qc, devices[name])
            devices[name].check_faulty(prepared[name])
        isa = prepared[name]
        record = {"stage":"submitting", "backend":name, "queues":queues, "shots":SHOTS,
                  "queue_snapshot_utc":datetime.now(timezone.utc).isoformat(), "tag":TAG,
                  "gates":dict(isa.count_ops()), "initial_layout":isa.layout.initial_index_layout(filter_ancillas=True),
                  "two_qubit_depth":isa.depth(lambda op:len(op.qubits)==2),
                  "two_qubit_gates":sum(len(op.qubits)==2 for op in isa.data)}
        sampler = SamplerV2(mode=devices[name], options={"environment":{"job_tags":[TAG]},
                            "twirling":{"enable_gates":False,"enable_measure":False}})
        with RESULT.open("x", encoding="utf8") as f:
            json.dump(record, f, indent=2)
        job = sampler.run([isa], shots=SHOTS)
    record.update(stage="submitted", job_id=job.job_id())
    write(RESULT, record)
    print("Submitted", record["backend"], job.job_id(), flush=True)
    while True:
        status = str(job.status())
        if status != record.get("ibm_status"):
            record["ibm_status"] = status
            write(RESULT, record)
        if status in ("DONE", "ERROR", "CANCELLED"):
            break
        time.sleep(10)
    record.update(analyze(job.result()[0].data.c.get_counts()), stage="measured")
    write(RESULT, record)
    for _ in range(120):
        metrics = job.metrics()
        if metrics.get("usage",{}).get("status") == "complete":
            break
        time.sleep(5)
    record.update(stage="done", metrics=metrics)
    write(RESULT, record)
    print("Factors and shot counts:", record["verified_factor_shots"])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("mode", choices=["simulate", "hardware"])
    if parser.parse_args().mode == "simulate":
        simulate()
    else:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            frames = [[Path(f.filename).name, f.lineno, f.name] for f in traceback.extract_tb(exc.__traceback__)]
            write(ROOT.parent/"work"/"shor-error.json", {"type":type(exc).__name__, "frames":frames})
            print(type(exc).__name__)
        input("Press Enter to close.")
noise-wall/source/shor15.py · complete source
"""Order finding for multiplication by two modulo fifteen; one eight-qubit circuit."""
import argparse
import getpass
import json
import logging
import sys
import time
import traceback
from datetime import datetime, timezone
from fractions import Fraction
from math import gcd
from pathlib import Path

from qiskit import QuantumCircuit
from qiskit.circuit.library import QFTGate
from qiskit.primitives import StatevectorSampler
from qiskit.quantum_info import Operator, Statevector
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

ROOT = Path(__file__).resolve().parent
RESULT = ROOT / "Shor15-hardware.json"
SIM = ROOT / "Shor15-simulator.json"
TAG = "order-finding-15-20261119-first"
SHOTS = 256
SEED = 1936
PHASE = 4
N = 15
BASE = 2


def write(path, record):
    temp = path.with_suffix(".tmp")
    temp.write_text(json.dumps(record, indent=2), encoding="utf-8")
    temp.replace(path)


def controlled_multiplier(constant):
    # A cyclic left rotation is doubling on residues 0..14. Fix unused state 15.
    qc = QuantumCircuit(5, name=f"controlled_mul{constant}")
    swaps = {2: [(2, 3), (1, 2), (0, 1)], 4: [(0, 2), (1, 3)]}
    for first, second in swaps[constant]:
        qc.cswap(0, 1+first, 1+second)
    return qc


def circuit():
    qc = QuantumCircuit(PHASE + 4, PHASE, name="order_of_2_mod_15")
    work = list(range(PHASE, PHASE+4))
    qc.x(work[0])
    qc.h(range(PHASE))
    for bit in range(PHASE):
        constant = pow(BASE, 2**bit, N)
        if constant != 1:
            qc.compose(controlled_multiplier(constant), [bit, *work], inplace=True)
    qc.append(QFTGate(PHASE).inverse(), range(PHASE))
    qc.measure(range(PHASE), range(PHASE))
    return qc


def analyze(counts):
    if sum(counts.values()) != SHOTS:
        raise ValueError("Unexpected shot count")
    solutions = {}
    exact_quarters = 0
    for bits, count in counts.items():
        phase = Fraction(int(bits, 2), 2**PHASE)
        if phase in (Fraction(1, 4), Fraction(3, 4)):
            exact_quarters += count
        candidate = phase.limit_denominator(N-1).denominator
        if candidate % 2 or pow(BASE, candidate, N) != 1:
            continue
        half = pow(BASE, candidate//2, N)
        factors = sorted([gcd(half-1, N), gcd(half+1, N)])
        if factors[0] > 1 and factors[0] * factors[1] == N:
            label = " x ".join(map(str, factors))
            solutions[label] = solutions.get(label, 0) + count
    return {"counts":dict(sorted(counts.items())), "verified_factor_shots":solutions,
            "quarter_phase_shots":exact_quarters,
            "four_peak_shots":sum(counts.get(format(v,"04b"),0) for v in (0,4,8,12))}


def simulate():
    import numpy as np
    for constant in (2, 4):
        product = [(x*constant) % N for x in range(N)] + [N]
        expected = [2*(product[x//2] if x%2 else x//2) + x%2 for x in range(32)]
        assert np.allclose(Operator(controlled_multiplier(constant)).data, np.eye(32)[:, expected])
    qc = circuit()
    probabilities = Statevector.from_instruction(qc.remove_final_measurements(inplace=False)).probabilities(
        qargs=list(range(PHASE)))
    ideal = np.zeros(16)
    ideal[::4] = 0.25
    assert np.allclose(probabilities, ideal)
    result = StatevectorSampler(seed=SEED).run([qc], shots=SHOTS).result()[0]
    record = analyze(result.data.c.get_counts())
    record.update(shots=SHOTS, seed=SEED, ideal_phase_probabilities=ideal.tolist())
    write(SIM, record)
    print(record)


def compile_for(qc, backend):
    pm = generate_preset_pass_manager(backend=backend, optimization_level=3, seed_transpiler=SEED)
    return pm.run(qc)


def hardware():
    if not SIM.exists() or not sys.stdin.isatty():
        raise RuntimeError("Run the local check first and open an interactive key prompt")
    if RESULT.exists() and json.loads(RESULT.read_text())["stage"] == "done":
        return
    token = getpass.getpass("IBM Cloud API key (hidden): ").strip()
    if not token:
        return
    service = QiskitRuntimeService(channel="ibm_quantum_platform", token=token,
                                   plans_preference=["open"], region="us-east")
    if RESULT.exists():
        record = json.loads(RESULT.read_text())
        if "job_id" in record:
            job = service.job(record["job_id"])
        else:
            matches = service.jobs(job_tags=[TAG], limit=2)
            if len(matches) != 1:
                raise RuntimeError("Reconcile the previous submission before retrying")
            job = matches[0]
    else:
        qc = circuit()
        devices = {b.name:b for b in service.backends(simulator=False, min_num_qubits=qc.num_qubits)
                   if not b.is_mock}
        prepared = {}
        while True:
            queues = {name:b.status().to_dict() for name,b in devices.items()}
            active = [name for name,s in queues.items() if s["operational"] and s["status_msg"].lower()=="active"]
            if not active:
                raise RuntimeError("No active processor")
            name = min(active, key=lambda k:(queues[k]["pending_jobs"],k))
            if name in prepared:
                break
            prepared[name] = compile_for(qc, devices[name])
            devices[name].check_faulty(prepared[name])
        isa = prepared[name]
        record = {"stage":"submitting", "backend":name, "queues":queues, "shots":SHOTS,
                  "queue_snapshot_utc":datetime.now(timezone.utc).isoformat(), "tag":TAG,
                  "gates":dict(isa.count_ops()), "initial_layout":isa.layout.initial_index_layout(filter_ancillas=True),
                  "two_qubit_depth":isa.depth(lambda op:len(op.qubits)==2),
                  "two_qubit_gates":sum(len(op.qubits)==2 for op in isa.data)}
        sampler = SamplerV2(mode=devices[name], options={"environment":{"job_tags":[TAG]},
                            "twirling":{"enable_gates":False,"enable_measure":False}})
        with RESULT.open("x", encoding="utf8") as f:
            json.dump(record, f, indent=2)
        job = sampler.run([isa], shots=SHOTS)
    record.update(stage="submitted", job_id=job.job_id())
    write(RESULT, record)
    print("Submitted", record["backend"], job.job_id(), flush=True)
    while True:
        status = str(job.status())
        if status != record.get("ibm_status"):
            record["ibm_status"] = status
            write(RESULT, record)
        if status in ("DONE", "ERROR", "CANCELLED"):
            break
        time.sleep(10)
    record.update(analyze(job.result()[0].data.c.get_counts()), stage="measured")
    write(RESULT, record)
    for _ in range(120):
        metrics = job.metrics()
        if metrics.get("usage",{}).get("status") == "complete":
            break
        time.sleep(5)
    record.update(stage="done", metrics=metrics)
    write(RESULT, record)
    print("Factors and shot counts:", record["verified_factor_shots"])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("mode", choices=["simulate", "hardware"])
    if parser.parse_args().mode == "simulate":
        simulate()
    else:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            frames = [[Path(f.filename).name, f.lineno, f.name] for f in traceback.extract_tb(exc.__traceback__)]
            write(ROOT.parent/"work"/"shor-error.json", {"type":type(exc).__name__, "frames":frames})
            print(type(exc).__name__)
        input("Press Enter to close.")

Personal comments

Personal comments will be added here.