deskmerc/ quantum

Algorithms / KINGSTON

Quantum Field Report

The noise wall at 299

Scale the modular-arithmetic circuit to the target 299 = 13 × 23.

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

The question

Scale the modular-arithmetic circuit to the target 299 = 13 × 23.

Circuit & method

The 44-qubit reversible circuit uses 17 phase bits. Routing on Kingston raises the native two-qubit gate count to 982,573. Run 256 shots and verify candidate factors classically.

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

Results

One hardware shot yielded the correct factors; ideal simulation gave 75/256. The job was charged 19 QPU seconds. The later report also checks a uniform-random baseline: 170 of 131,072 possible phase readings pass the same decoder, giving about 28% probability of at least one hit in 256 random draws.

Measured outcomesAll-shot success; each bar runs from 0% to 100%.
Hardware verified factors1/256 · 0.4%
Ideal sampled factors75/256 · 29.3%

What this supports

A verified factor is real, but one hit supplies weak evidence of a resolved period signal in this deep circuit. The uniform comparison is a classical decoder check reported in Through the Noise Wall, page 1 and its attachment README.

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
shots
256
execution_cap_s
30
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"
  }
}
queue_snapshot_utc
2026-11-20T03:31:54.130760+00:00
logical_qubits
44
job_tag
shor299-full-30s-20261119
oracle
full reversible modular-multiplication tables in Boolean polynomial form
native_gates
{
  "sx": 1850857,
  "cz": 982573,
  "rz": 526185,
  "measure": 17,
  "x": 7
}
duration_per_shot_s
0.0658302079988239
reset_s
2.212e-06
rep_delay_s
0.00025
estimated_usage_s
18.91709951969892
two_qubit_gates
982573
two_qubit_depth
661540
job_id
dbvruddhdvas73biio8g
ibm_status
DONE
counts
{
  "01010100010000001": 1,
  "10101011100001011": 1,
  "00101111101110011": 1,
  "11100111000101001": 1,
  "11111001100110010": 1,
  "10100010010001010": 1,
  "11011000100001100": 1,
  "11000110011010101": 1,
  "01100000010111000": 1,
  "00110110110100111": 1,
  "01000010000000001": 1,
  "01010101010111010": 1,
  "11110011010001001": 1,
  "10010100001000001": 1,
  "10001100101100000": 1,
  "00100011000100100": 1,
  "00010110000000011": 1,
  "11100100011100101": 1,
  "01011010101000001": 1,
  "10111111001011101": 1,
  "11011010110000000": 1,
  "10001010001111000": 1,
  "10001001000110000": 1,
  "10010100100000000": 1,
  "10100000011100101": 1,
  "11001100000100101": 1,
  "00010000110111000": 1,
  "01111001110011100": 1,
  "10101110100000000": 1,
  "11101110010010100": 1,
  "10101001000000000": 1,
  "00100111100101010": 1,
  "00101111001110010": 1,
  "01110000000000110": 1,
  "10011100000011101": 1,
  "01000000100001101": 1,
  "11000001101000011": 1,
  "10000111100111110": 1,
  "01101111000111010": 1,
  "01110101100011000": 1,
  "01010110100011100": 1,
  "10100101100100011": 1,
  "01010110000010000": 1,
  "10011100001010110": 1,
  "00101110001110001": 1,
  "01010000100100010": 1,
  "00111101101101001": 1,
  "00101011110101000": 1,
  "01001011010010000": 1,
  "11111000001010101": 1,
  "11111011100001110": 1,
  "11011001101100001": 1,
  "11110101100000001": 1,
  "01011001110000010": 1,
  "00101011111011001": 1,
  "01011101110000100": 1,
  "11000010111110101": 1,
  "10110010000100000": 1,
  "11001101010011000": 1,
  "00011001100110101": 1,
  "10111100010010011": 1,
  "10011110000011000": 1,
  "10010100000101000": 1,
  "10101000010010011": 1,
  "00111001100100111": 1,
  "10110010111000001": 1,
  "01011000100000110": 1,
  "10100000000100111": 1,
  "00001100000010101": 1,
  "00110001100110100": 1,
  "01110111110001100": 1,
  "01111101000001110": 1,
  "10010010100011000": 1,
  "10111111101100000": 1,
  "10000011100101110": 1,
  "01100100101001100": 1,
  "11101110000000000": 1,
  "11101100000110001": 1,
  "00000011000101000": 1,
  "10100000100100100": 1,
  "11011110110100100": 1,
  "10100000010000011": 1,
  "01011001100010000": 1,
  "00000111000000100": 1,
  "01100000100100001": 1,
  "10001100111100101": 1,
  "11000101100110000": 1,
  "10001100100111001": 1,
  "01000101000000110": 1,
  "01010010011110010": 1,
  "01011001101011010": 1,
  "00000001111101001": 1,
  "10101001010100001": 1,
  "11010110000000000": 1,
  "11010001000100110": 1,
  "00011011110000010": 1,
  "11111101010101101": 1,
  "11100100010100110": 1,
  "10101100100110101": 1,
  "00010011101001100": 1,
  "11101010001111000": 1,
  "00100110000100101": 1,
  "00100101110100010": 1,
  "01111100000100100": 1,
  "00111010101011101": 1,
  "01101000110100011": 1,
  "10010000000010001": 1,
  "01111111000100000": 1,
  "01001110000000000": 1,
  "10000010010000100": 1,
  "10101100101010110": 1,
  "01101100000010100": 1,
  "11001010000000010": 1,
  "10100100000101000": 1,
  "01110100001101100": 1,
  "01010110100000010": 1,
  "10001000000001011": 1,
  "11101111000111101": 1,
  "11001011100000100": 1,
  "10000011000100101": 1,
  "00000100011110000": 1,
  "10100100100001010": 1,
  "10000110010100101": 1,
  "01010110000011010": 1,
  "11001010101010101": 1,
  "01101000110100010": 1,
  "00110010110100100": 1,
  "00001100010000000": 1,
  "10110110000010001": 1,
  "00110110110010001": 1,
  "01001010011010001": 1,
  "01100110001010110": 1,
  "10100100000111110": 1,
  "01010100001101110": 1,
  "01010011100100110": 1,
  "10011011000000001": 1,
  "10100101001010001": 1,
  "00110010101001101": 1,
  "00010101100100100": 1,
  "00101011100001000": 1,
  "01100110000110010": 1,
  "01100010101100001": 1,
  "10000001000100010": 1,
  "01111011110100100": 1,
  "10100111010100001": 1,
  "00110101100000001": 1,
  "01110110110001001": 1,
  "10110001100101010": 1,
  "10011000100000000": 1,
  "00000001100010000": 1,
  "00010011000110000": 1,
  "11101011000001011": 1,
  "01101101001111110": 1,
  "10100100101011010": 1,
  "00100010000000010": 1,
  "00010010110101000": 1,
  "00100010010110011": 1,
  "11111110000010000": 1,
  "01110011111101100": 1,
  "11111000111000100": 1,
  "01011011100101111": 1,
  "01111001101100010": 1,
  "01100111100100010": 1,
  "01001110001011010": 1,
  "01011000000010000": 1,
  "11001011100100110": 1,
  "00110111100010101": 1,
  "01100101010111001": 1,
  "10101010000010100": 1,
  "01010011111010100": 1,
  "10101010011001111": 1,
  "01000011001110111": 1,
  "11101001011011010": 1,
  "00100010000011010": 1,
  "10100011000010101": 1,
  "10010110010011011": 1,
  "11001001101000000": 1,
  "11101101001000010": 1,
  "01111001000100110": 1,
  "10010110010101010": 1,
  "11100101011011001": 1,
  "10101100110011110": 1,
  "11011110111101110": 1,
  "10100001101010010": 1,
  "11110010000110001": 1,
  "00110010100000000": 1,
  "01100100100101011": 1,
  "00101110010111111": 1,
  "10100000000001111": 1,
  "01001010000000000": 1,
  "01000001001010101": 1,
  "01011111011001100": 1,
  "10001111000010011": 1,
  "11011111111100111": 1,
  "00111100000110001": 1,
  "01000010000100110": 1,
  "10100110100110000": 1,
  "00101010010011010": 1,
  "10011000000010001": 1,
  "01111001110010001": 1,
  "11010010010101000": 1,
  "11000001001000001": 1,
  "00100001100000110": 1,
  "00111001000111100": 1,
  "10111010100011110": 1,
  "00111110100000011": 1,
  "00010011001111110": 1,
  "01100010111100010": 1,
  "11110101000001110": 1,
  "01010010001100000": 1,
  "10000100000111010": 1,
  "00110101010011010": 1,
  "01100000110011001": 1,
  "01000110100010100": 1,
  "11100100000000100": 1,
  "11011110100001000": 1,
  "11101000010010011": 1,
  "00111010000010100": 1,
  "10100001010101000": 1,
  "00101000110100000": 1,
  "01111100000100001": 1,
  "00000111101000010": 1,
  "01101000001111100": 1,
  "01001000110111111": 1,
  "01000010100111111": 1,
  "00000000011100010": 1,
  "00100000100110000": 1,
  "00010100000100100": 1,
  "10001000100101010": 1,
  "00001111100000110": 1,
  "01001010010011101": 1,
  "00100010001001010": 1,
  "10010011110011001": 1,
  "11000110001010000": 1,
  "00001101000100011": 1,
  "10000111100100100": 1,
  "00111000100011001": 1,
  "10011000001000000": 1,
  "11101010100001000": 1,
  "01000011110000010": 1,
  "00010011001101011": 1,
  "01100011001100010": 1,
  "11100011010010000": 1,
  "00111010101000111": 1,
  "11100001000000100": 1,
  "00111011010010011": 1,
  "01100110100001000": 1,
  "01001001101010000": 1,
  "11010001011110010": 1,
  "01011101010001101": 1,
  "00100000100001111": 1,
  "10010010010000111": 1,
  "10010000110110111": 1,
  "11101011100110000": 1,
  "10100100100010010": 1,
  "11111111000110000": 1
}
verified_factor_shots
1
denominators
{
  "132": 1
}
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:32:05.849893Z",
    "finished": "2026-11-20T03:32:57.593288Z",
    "running": "2026-11-20T03:32:06.986116Z"
  },
  "usage": {
    "qpu_charge_time_seconds": 19,
    "value": 0.309276,
    "unit": "resource_units",
    "status": "complete",
    "details": [
      {
        "value": 0.309276,
        "unit": "resource_units",
        "metric": {
          "id": "caffe3ca-729c-5750-8777-df63bbf8bfd9",
          "value": 19
        }
      }
    ]
  },
  "circuits_execution_time_ns": 16854186240
}

Supporting records & original figures

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/Shor299-simulator.json · full record
{
  "N": 299,
  "base": 2,
  "phase_bits": 17,
  "work_bits": 9,
  "shots": 256,
  "seed": 1936,
  "counts_decimal": {
    "0": 2,
    "993": 2,
    "1986": 5,
    "2979": 1,
    "3971": 1,
    "3972": 1,
    "4965": 6,
    "5958": 1,
    "5959": 1,
    "6951": 1,
    "7944": 2,
    "8937": 1,
    "8944": 1,
    "9928": 1,
    "9930": 1,
    "10922": 1,
    "11915": 1,
    "11916": 4,
    "12909": 1,
    "13900": 1,
    "13901": 1,
    "14895": 1,
    "16881": 1,
    "17874": 1,
    "18868": 1,
    "20852": 1,
    "23831": 1,
    "23832": 1,
    "24824": 5,
    "26810": 2,
    "27803": 2,
    "28796": 2,
    "29789": 3,
    "30782": 3,
    "31775": 3,
    "33761": 3,
    "35747": 1,
    "36740": 3,
    "37733": 2,
    "37734": 1,
    "38726": 1,
    "39719": 2,
    "40712": 2,
    "41642": 1,
    "41705": 1,
    "41706": 1,
    "42699": 1,
    "43691": 2,
    "44685": 1,
    "45676": 1,
    "49647": 1,
    "49649": 1,
    "49652": 1,
    "51634": 2,
    "51635": 2,
    "53620": 1,
    "53621": 1,
    "54613": 3,
    "56597": 1,
    "56599": 1,
    "56600": 1,
    "57592": 2,
    "58585": 2,
    "59578": 1,
    "60571": 1,
    "60587": 1,
    "61559": 1,
    "61563": 1,
    "61564": 2,
    "62554": 1,
    "62557": 1,
    "63550": 2,
    "64543": 2,
    "65536": 2,
    "66529": 1,
    "67522": 2,
    "68515": 2,
    "69508": 1,
    "71494": 3,
    "72486": 1,
    "72487": 1,
    "73480": 2,
    "74472": 1,
    "74473": 2,
    "76459": 3,
    "78445": 2,
    "79438": 2,
    "79439": 1,
    "80431": 1,
    "80474": 1,
    "81366": 1,
    "81423": 1,
    "81424": 2,
    "83410": 2,
    "84402": 1,
    "84403": 1,
    "85396": 1,
    "86387": 1,
    "87381": 2,
    "87382": 1,
    "88374": 4,
    "88375": 1,
    "89367": 1,
    "90360": 3,
    "92347": 1,
    "93339": 3,
    "93340": 1,
    "93341": 1,
    "94332": 1,
    "95325": 2,
    "95326": 1,
    "96318": 2,
    "97311": 4,
    "98304": 1,
    "99297": 3,
    "100290": 4,
    "101284": 1,
    "102276": 3,
    "103269": 1,
    "104261": 1,
    "104263": 1,
    "106248": 3,
    "107241": 2,
    "108234": 4,
    "109227": 2,
    "110218": 2,
    "110219": 1,
    "111212": 1,
    "111213": 2,
    "112206": 3,
    "114186": 1,
    "114192": 1,
    "115184": 1,
    "115185": 1,
    "116177": 1,
    "117170": 2,
    "117184": 1,
    "119157": 1,
    "120149": 1,
    "120150": 2,
    "121144": 1,
    "122135": 2,
    "123126": 1,
    "123128": 2,
    "124121": 1,
    "125113": 1,
    "125114": 4,
    "126107": 4,
    "127100": 5,
    "128093": 2,
    "129086": 1,
    "130079": 1
  },
  "verified_factor_shots": 75,
  "decoded": {
    "126107": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "78445": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "28796": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "30782": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "100290": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "106248": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "4965": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "993": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "102276": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "112206": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "108234": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "36740": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "88374": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "16881": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "84402": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "96318": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "6951": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "64543": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "90360": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "24824": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "66529": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "72487": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "84403": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "88375": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "42699": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "58585": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "94332": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "60571": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "40712": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "130079": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "114192": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "124121": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "72486": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "12909": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "18868": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    }
  }
}
noise-wall/results/Shor299-simulator.json · full record
{
  "N": 299,
  "base": 2,
  "phase_bits": 17,
  "work_bits": 9,
  "shots": 256,
  "seed": 1936,
  "counts_decimal": {
    "0": 2,
    "993": 2,
    "1986": 5,
    "2979": 1,
    "3971": 1,
    "3972": 1,
    "4965": 6,
    "5958": 1,
    "5959": 1,
    "6951": 1,
    "7944": 2,
    "8937": 1,
    "8944": 1,
    "9928": 1,
    "9930": 1,
    "10922": 1,
    "11915": 1,
    "11916": 4,
    "12909": 1,
    "13900": 1,
    "13901": 1,
    "14895": 1,
    "16881": 1,
    "17874": 1,
    "18868": 1,
    "20852": 1,
    "23831": 1,
    "23832": 1,
    "24824": 5,
    "26810": 2,
    "27803": 2,
    "28796": 2,
    "29789": 3,
    "30782": 3,
    "31775": 3,
    "33761": 3,
    "35747": 1,
    "36740": 3,
    "37733": 2,
    "37734": 1,
    "38726": 1,
    "39719": 2,
    "40712": 2,
    "41642": 1,
    "41705": 1,
    "41706": 1,
    "42699": 1,
    "43691": 2,
    "44685": 1,
    "45676": 1,
    "49647": 1,
    "49649": 1,
    "49652": 1,
    "51634": 2,
    "51635": 2,
    "53620": 1,
    "53621": 1,
    "54613": 3,
    "56597": 1,
    "56599": 1,
    "56600": 1,
    "57592": 2,
    "58585": 2,
    "59578": 1,
    "60571": 1,
    "60587": 1,
    "61559": 1,
    "61563": 1,
    "61564": 2,
    "62554": 1,
    "62557": 1,
    "63550": 2,
    "64543": 2,
    "65536": 2,
    "66529": 1,
    "67522": 2,
    "68515": 2,
    "69508": 1,
    "71494": 3,
    "72486": 1,
    "72487": 1,
    "73480": 2,
    "74472": 1,
    "74473": 2,
    "76459": 3,
    "78445": 2,
    "79438": 2,
    "79439": 1,
    "80431": 1,
    "80474": 1,
    "81366": 1,
    "81423": 1,
    "81424": 2,
    "83410": 2,
    "84402": 1,
    "84403": 1,
    "85396": 1,
    "86387": 1,
    "87381": 2,
    "87382": 1,
    "88374": 4,
    "88375": 1,
    "89367": 1,
    "90360": 3,
    "92347": 1,
    "93339": 3,
    "93340": 1,
    "93341": 1,
    "94332": 1,
    "95325": 2,
    "95326": 1,
    "96318": 2,
    "97311": 4,
    "98304": 1,
    "99297": 3,
    "100290": 4,
    "101284": 1,
    "102276": 3,
    "103269": 1,
    "104261": 1,
    "104263": 1,
    "106248": 3,
    "107241": 2,
    "108234": 4,
    "109227": 2,
    "110218": 2,
    "110219": 1,
    "111212": 1,
    "111213": 2,
    "112206": 3,
    "114186": 1,
    "114192": 1,
    "115184": 1,
    "115185": 1,
    "116177": 1,
    "117170": 2,
    "117184": 1,
    "119157": 1,
    "120149": 1,
    "120150": 2,
    "121144": 1,
    "122135": 2,
    "123126": 1,
    "123128": 2,
    "124121": 1,
    "125113": 1,
    "125114": 4,
    "126107": 4,
    "127100": 5,
    "128093": 2,
    "129086": 1,
    "130079": 1
  },
  "verified_factor_shots": 75,
  "decoded": {
    "126107": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "78445": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "28796": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "30782": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "100290": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "106248": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "4965": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "993": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "102276": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "112206": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "108234": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "36740": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "88374": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "16881": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "84402": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "96318": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "6951": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "64543": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "90360": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "24824": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "66529": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "72487": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "84403": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "88375": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "42699": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "58585": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "94332": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "60571": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "40712": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "130079": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "114192": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "124121": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "72486": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "12909": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    },
    "18868": {
      "denominator": 132,
      "half_power_mod_N": 116,
      "factors": [
        13,
        23
      ]
    }
  }
}

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.

  • run_shor299.pyQuantum Field Report.pdf / Experiment-source.zip · 6,269 bytes
  • shor299.pyQuantum Field Report.pdf / Experiment-source.zip · 6,210 bytes
  • shor299.pyThrough the Noise Wall.pdf / Kingston measurements and source.zip · 6,210 bytes
  • run_shor299.pyThrough the Noise Wall.pdf / Kingston measurements and source.zip · 6,269 bytes
field-report/outputs/run_shor299.py · complete source
"""Submit one full base-2 Shor circuit only if the 256-shot estimate fits 30 s."""
import os
os.environ.setdefault("RAYON_NUM_THREADS", "2")
import getpass
import json
import logging
import math
import sys
import time
import traceback
from collections import Counter, deque
from datetime import datetime, timezone

from qiskit import transpile
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

from shor299 import ROOT, SHOTS, SEED, decode, hardware_circuit, polynomial_lookup

FILE = ROOT / "Shor299-hardware.json"
TAG = "shor299-full-30s-20261119"
LIMIT = 30


def save(record):
    tmp = FILE.with_suffix(".tmp")
    tmp.write_text(json.dumps(record, indent=2), encoding="utf8")
    tmp.replace(FILE)


def nearby_layout(backend, width):
    props = backend.properties()
    bad = set(props.faulty_qubits())
    bad_edges = {tuple(sorted(g.qubits)) for g in props.faulty_gates() if len(g.qubits)==2}
    neighbors = {}
    for x,y in backend.coupling_map.get_edges():
        if x in bad or y in bad or tuple(sorted((x,y))) in bad_edges:
            continue
        neighbors.setdefault(x,set()).add(y)
        neighbors.setdefault(y,set()).add(x)
    for root in sorted(neighbors, key=lambda x:-len(neighbors[x])):
        seen, todo, result = {root}, deque([root]), []
        while todo and len(result)<width:
            q = todo.popleft()
            result.append(q)
            for v in sorted(neighbors[q]-seen):
                seen.add(v)
                todo.append(v)
        if len(result)==width:
            return result
    raise RuntimeError("Insufficient connected qubits")


def prepare(backend, qc):
    isa = transpile(qc, backend, initial_layout=nearby_layout(backend,qc.num_qubits),
                    optimization_level=1, routing_method="sabre", seed_transpiler=SEED)
    backend.check_faulty(isa)
    duration = isa.estimate_duration(backend.target)
    rep = backend.default_rep_delay
    used = set(isa.layout.initial_index_layout(filter_ancillas=True))
    reset = max(backend.target["reset"][q,].duration for q in used)
    estimate = 2 + SHOTS*(duration+rep+reset)
    counts = dict(isa.count_ops())
    return isa, {"native_gates":counts, "duration_per_shot_s":duration, "reset_s":reset,
                 "rep_delay_s":rep, "estimated_usage_s":estimate,
                 "two_qubit_gates":sum(counts.get(g,0) for g in ("cz","cx","ecr")),
                 "two_qubit_depth":isa.depth(lambda op:len(op.qubits)==2)}


def run():
    if not sys.stdin.isatty():
        raise RuntimeError("Interactive console required")
    rec = json.loads(FILE.read_text()) if FILE.exists() else {}
    if rec.get("stage") in ("done","over_budget","terminal_error"):
        return
    key = getpass.getpass("IBM Cloud API key (hidden): ").strip()
    if not key:
        return
    service = QiskitRuntimeService(channel="ibm_quantum_platform", token=key,
                                   plans_preference=["open"], region="us-east")
    if "job_id" in rec:
        job = service.job(rec["job_id"])
    elif rec.get("stage")=="submitting":
        jobs = service.jobs(job_tags=[TAG],limit=2)
        if len(jobs)!=1:
            raise RuntimeError("Reconcile previous submission")
        job = jobs[0]
    else:
        targets = {b.name:b for b in service.backends(simulator=False,min_num_qubits=44) if not b.is_mock}
        qc = hardware_circuit(polynomial_lookup)
        compiled = {}
        while True:
            queues = {k:b.status().to_dict() for k,b in targets.items()}
            active = [k for k,v in queues.items() if v["operational"] and v["status_msg"].lower()=="active"]
            name = min(active,key=lambda k:(queues[k]["pending_jobs"],k))
            rec = {"stage":"compiling","backend":name, "shots":SHOTS, "execution_cap_s":LIMIT,
                   "queues":queues,"queue_snapshot_utc":datetime.now(timezone.utc).isoformat(),
                   "logical_qubits":qc.num_qubits, "job_tag":TAG,
                   "oracle":"full reversible modular-multiplication tables in Boolean polynomial form"}
            save(rec)
            if name in compiled:
                break
            compiled[name] = prepare(targets[name],qc)
        isa, sizing = compiled[name]
        rec.update(sizing)
        if math.ceil(sizing["estimated_usage_s"])>LIMIT:
            rec["stage"]="over_budget"
            save(rec)
            return
        sampler = SamplerV2(mode=targets[name],options={"max_execution_time":LIMIT,
                            "environment":{"job_tags":[TAG]},
                            "twirling":{"enable_measure":False,"enable_gates":False},
                            "dynamical_decoupling":{"enable":False}})
        rec["stage"]="submitting"
        save(rec)
        job = sampler.run([isa],shots=SHOTS)
    rec.update(job_id=job.job_id(),stage="submitted")
    save(rec)
    while True:
        status = str(job.status())
        if status != rec.get("ibm_status"):
            rec["ibm_status"]=status
            save(rec)
        if status in ("DONE","ERROR","CANCELLED"):
            break
        time.sleep(8)
    if status=="DONE":
        counts = job.result()[0].data.c.get_counts()
        assert sum(counts.values())==SHOTS
        denoms = Counter()
        for s,n in counts.items():
            result = decode(int(s,2))
            if result:
                denoms[result["denominator"]]+=n
        rec.update(counts=counts, verified_factor_shots=sum(denoms.values()),denominators=denoms)
    else:
        rec["ibm_error"]=str(job.error_message())[:1500]
    for _ in range(120):
        metrics = job.metrics()
        if metrics.get("usage",{}).get("status")=="complete":
            break
        time.sleep(5)
    rec.update(stage="done" if status=="DONE" else "terminal_error", metrics=metrics)
    save(rec)


if __name__=="__main__":
    logging.disable(logging.CRITICAL)
    try:
        run()
    except Exception as exc:
        from pathlib import Path
        frames = [[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(exc.__traceback__)]
        (ROOT.parent/"work"/"shor299-error.json").write_text(json.dumps({"type":type(exc).__name__,"frames":frames}))
        print(type(exc).__name__)
    input("Press Enter to close.")
field-report/outputs/shor299.py · complete source
"""Ideal iterative Shor simulation and a reversible lookup circuit for N=299."""
import argparse
import json
from collections import Counter
from fractions import Fraction
from math import gcd
from pathlib import Path

import numpy as np

N, BASE, SHOTS, SEED = 299, 2, 256, 1936
WIDTH = N.bit_length()
PRECISION = (N*N-1).bit_length()
ROOT = Path(__file__).resolve().parent


def simulate_phases(n, base, bits, shots, seed):
    # Each row is one trajectory. The control is measured and reset after every bit.
    rng = np.random.default_rng(seed)
    residues = np.arange(1 << n.bit_length())
    work = np.zeros((shots, len(residues)), dtype=complex)
    work[:, 1] = 1
    outcomes = np.zeros(shots, dtype=int)
    for step in range(bits):
        power = pow(base, 1 << (bits-1-step), n)
        inverse = pow(power, -1, n)
        permuted = work[:, np.where(residues < n, residues*inverse % n, residues)]
        rotation = np.exp(-2j*np.pi*outcomes / (1 << (step+1)))
        rotated = rotation[:, None] * permuted
        plus = (work + rotated) / 2
        p_zero = (abs(plus)**2).sum(axis=1)
        one = rng.random(shots) >= np.clip(p_zero, 0, 1)
        work = np.where(one[:, None], (work-rotated)/2, plus)
        work /= np.linalg.norm(work, axis=1)[:, None]
        outcomes += one.astype(int) << step
    return outcomes


def decode(y):
    phase = Fraction(int(y), 1 << PRECISION)
    candidate = phase.limit_denominator(N-1).denominator
    if candidate % 2 or pow(BASE, candidate, N) != 1:
        return None
    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:
        return {"denominator":candidate, "half_power_mod_N":half, "factors":factors}
    return None


def simulate():
    check = simulate_phases(15, 2, 4, 256, SEED)
    assert set(check) == {0, 4, 8, 12}
    samples = simulate_phases(N, BASE, PRECISION, SHOTS, SEED)
    counts = Counter(map(int, samples))
    decoded = {y:result for y in counts if (result := decode(y)) is not None}
    record = {"N":N, "base":BASE, "phase_bits":PRECISION, "work_bits":WIDTH,
              "shots":SHOTS, "seed":SEED, "counts_decimal":dict(sorted(counts.items())),
              "verified_factor_shots":sum(counts[y] for y in decoded), "decoded":decoded}
    (ROOT/"Shor299-simulator.json").write_text(json.dumps(record, indent=2))
    print(record["verified_factor_shots"], next(iter(decoded.items())), "of", SHOTS)


def lookup(qc, k, control, work, target, scratch):
    # Reversibly XOR f(x) into target if control is set. Descend a binary
    # prefix tree and share the prefix flags between neighboring table entries.
    # Relative phases of each compute/uncompute pair cancel on every input.
    def visit(depth, prefix, enabled):
        if depth == WIDTH:
            value = (k*prefix) % N if prefix < N else prefix
            for b in range(WIDTH):
                if (value >> b) & 1:
                    qc.cx(enabled, target[b])
            return
        bit = work[WIDTH-1-depth]
        flag = scratch[depth]
        for value in (0, 1):
            if value == 0:
                qc.x(bit)
            qc.rccx(enabled, bit, flag)
            visit(depth+1, 2*prefix+value, flag)
            qc.rccx(enabled, bit, flag)
            if value == 0:
                qc.x(bit)
    visit(0, 0, control)


def polynomial_lookup(qc, k, control, work, target, scratch):
    # Positive-polarity Boolean expansion of the entire same reversible table.
    # Each prefix AND is computed once and reused by all its descendants.
    indices = np.arange(1 << WIDTH)
    values = np.where(indices < N, (indices*k) % N, indices)
    coeff = values.copy()
    for i in range(WIDTH):
        mask = indices[(indices & (1 << i)) != 0]
        coeff[mask] ^= coeff[mask ^ (1 << i)]
    check = coeff.copy()
    for i in range(WIDTH):
        mask = indices[(indices & (1 << i)) != 0]
        check[mask] ^= check[mask ^ (1 << i)]
    assert np.array_equal(check, values) and coeff[0] == 0

    def visit(mask, start, enabled, depth):
        for i in range(start, WIDTH):
            new_mask = mask | (1 << i)
            value = int(coeff[new_mask])
            if i == WIDTH-1 and not value:
                continue
            flag = scratch[depth]
            qc.rccx(enabled, work[i], flag)
            for j in range(WIDTH):
                if (value >> j) & 1:
                    qc.cx(flag, target[j])
            visit(new_mask, i+1, flag, depth+1)
            qc.rccx(enabled, work[i], flag)

    visit(0, 0, control, 0)


def hardware_circuit(table=lookup):
    from qiskit import QuantumCircuit
    from qiskit.circuit.library import QFTGate
    q = QuantumCircuit(PRECISION+3*WIDTH, PRECISION)
    work, target, scratch = [list(range(PRECISION+j*WIDTH, PRECISION+(j+1)*WIDTH)) for j in range(3)]
    q.x(work[0])
    q.h(range(PRECISION))
    for bit in range(PRECISION):
        k = pow(BASE, 1 << bit, N)
        if k == 1:
            continue
        table(q, k, bit, work, target, scratch)
        for x, y in zip(work, target):
            q.cswap(bit, x, y)
        table(q, pow(k, -1, N), bit, work, target, scratch)
    q.append(QFTGate(PRECISION).inverse(), range(PRECISION))
    q.measure(range(PRECISION), range(PRECISION))
    return q


def size():
    from qiskit import transpile
    q = hardware_circuit()
    native = transpile(q, basis_gates=["rz","sx","x","cz"], optimization_level=1, seed_transpiler=SEED)
    record = {"logical_width_including_scratch":q.num_qubits, "phase_bits":PRECISION,
              "counts_before_decomposition":dict(q.count_ops()),
              "basis_counts_all_to_all":dict(native.count_ops()),
              "two_qubit_depth_all_to_all":native.depth(lambda op:len(op.qubits)==2),
              "connectivity":"all-to-all, no device routing"}
    (ROOT/"Shor299-circuit-size.json").write_text(json.dumps(record, indent=2))
    print(record)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=["simulate","size"])
    args = parser.parse_args()
    (simulate if args.action == "simulate" else size)()
noise-wall/source/shor299.py · complete source
"""Ideal iterative Shor simulation and a reversible lookup circuit for N=299."""
import argparse
import json
from collections import Counter
from fractions import Fraction
from math import gcd
from pathlib import Path

import numpy as np

N, BASE, SHOTS, SEED = 299, 2, 256, 1936
WIDTH = N.bit_length()
PRECISION = (N*N-1).bit_length()
ROOT = Path(__file__).resolve().parent


def simulate_phases(n, base, bits, shots, seed):
    # Each row is one trajectory. The control is measured and reset after every bit.
    rng = np.random.default_rng(seed)
    residues = np.arange(1 << n.bit_length())
    work = np.zeros((shots, len(residues)), dtype=complex)
    work[:, 1] = 1
    outcomes = np.zeros(shots, dtype=int)
    for step in range(bits):
        power = pow(base, 1 << (bits-1-step), n)
        inverse = pow(power, -1, n)
        permuted = work[:, np.where(residues < n, residues*inverse % n, residues)]
        rotation = np.exp(-2j*np.pi*outcomes / (1 << (step+1)))
        rotated = rotation[:, None] * permuted
        plus = (work + rotated) / 2
        p_zero = (abs(plus)**2).sum(axis=1)
        one = rng.random(shots) >= np.clip(p_zero, 0, 1)
        work = np.where(one[:, None], (work-rotated)/2, plus)
        work /= np.linalg.norm(work, axis=1)[:, None]
        outcomes += one.astype(int) << step
    return outcomes


def decode(y):
    phase = Fraction(int(y), 1 << PRECISION)
    candidate = phase.limit_denominator(N-1).denominator
    if candidate % 2 or pow(BASE, candidate, N) != 1:
        return None
    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:
        return {"denominator":candidate, "half_power_mod_N":half, "factors":factors}
    return None


def simulate():
    check = simulate_phases(15, 2, 4, 256, SEED)
    assert set(check) == {0, 4, 8, 12}
    samples = simulate_phases(N, BASE, PRECISION, SHOTS, SEED)
    counts = Counter(map(int, samples))
    decoded = {y:result for y in counts if (result := decode(y)) is not None}
    record = {"N":N, "base":BASE, "phase_bits":PRECISION, "work_bits":WIDTH,
              "shots":SHOTS, "seed":SEED, "counts_decimal":dict(sorted(counts.items())),
              "verified_factor_shots":sum(counts[y] for y in decoded), "decoded":decoded}
    (ROOT/"Shor299-simulator.json").write_text(json.dumps(record, indent=2))
    print(record["verified_factor_shots"], next(iter(decoded.items())), "of", SHOTS)


def lookup(qc, k, control, work, target, scratch):
    # Reversibly XOR f(x) into target if control is set. Descend a binary
    # prefix tree and share the prefix flags between neighboring table entries.
    # Relative phases of each compute/uncompute pair cancel on every input.
    def visit(depth, prefix, enabled):
        if depth == WIDTH:
            value = (k*prefix) % N if prefix < N else prefix
            for b in range(WIDTH):
                if (value >> b) & 1:
                    qc.cx(enabled, target[b])
            return
        bit = work[WIDTH-1-depth]
        flag = scratch[depth]
        for value in (0, 1):
            if value == 0:
                qc.x(bit)
            qc.rccx(enabled, bit, flag)
            visit(depth+1, 2*prefix+value, flag)
            qc.rccx(enabled, bit, flag)
            if value == 0:
                qc.x(bit)
    visit(0, 0, control)


def polynomial_lookup(qc, k, control, work, target, scratch):
    # Positive-polarity Boolean expansion of the entire same reversible table.
    # Each prefix AND is computed once and reused by all its descendants.
    indices = np.arange(1 << WIDTH)
    values = np.where(indices < N, (indices*k) % N, indices)
    coeff = values.copy()
    for i in range(WIDTH):
        mask = indices[(indices & (1 << i)) != 0]
        coeff[mask] ^= coeff[mask ^ (1 << i)]
    check = coeff.copy()
    for i in range(WIDTH):
        mask = indices[(indices & (1 << i)) != 0]
        check[mask] ^= check[mask ^ (1 << i)]
    assert np.array_equal(check, values) and coeff[0] == 0

    def visit(mask, start, enabled, depth):
        for i in range(start, WIDTH):
            new_mask = mask | (1 << i)
            value = int(coeff[new_mask])
            if i == WIDTH-1 and not value:
                continue
            flag = scratch[depth]
            qc.rccx(enabled, work[i], flag)
            for j in range(WIDTH):
                if (value >> j) & 1:
                    qc.cx(flag, target[j])
            visit(new_mask, i+1, flag, depth+1)
            qc.rccx(enabled, work[i], flag)

    visit(0, 0, control, 0)


def hardware_circuit(table=lookup):
    from qiskit import QuantumCircuit
    from qiskit.circuit.library import QFTGate
    q = QuantumCircuit(PRECISION+3*WIDTH, PRECISION)
    work, target, scratch = [list(range(PRECISION+j*WIDTH, PRECISION+(j+1)*WIDTH)) for j in range(3)]
    q.x(work[0])
    q.h(range(PRECISION))
    for bit in range(PRECISION):
        k = pow(BASE, 1 << bit, N)
        if k == 1:
            continue
        table(q, k, bit, work, target, scratch)
        for x, y in zip(work, target):
            q.cswap(bit, x, y)
        table(q, pow(k, -1, N), bit, work, target, scratch)
    q.append(QFTGate(PRECISION).inverse(), range(PRECISION))
    q.measure(range(PRECISION), range(PRECISION))
    return q


def size():
    from qiskit import transpile
    q = hardware_circuit()
    native = transpile(q, basis_gates=["rz","sx","x","cz"], optimization_level=1, seed_transpiler=SEED)
    record = {"logical_width_including_scratch":q.num_qubits, "phase_bits":PRECISION,
              "counts_before_decomposition":dict(q.count_ops()),
              "basis_counts_all_to_all":dict(native.count_ops()),
              "two_qubit_depth_all_to_all":native.depth(lambda op:len(op.qubits)==2),
              "connectivity":"all-to-all, no device routing"}
    (ROOT/"Shor299-circuit-size.json").write_text(json.dumps(record, indent=2))
    print(record)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=["simulate","size"])
    args = parser.parse_args()
    (simulate if args.action == "simulate" else size)()
noise-wall/source/run_shor299.py · complete source
"""Submit one full base-2 Shor circuit only if the 256-shot estimate fits 30 s."""
import os
os.environ.setdefault("RAYON_NUM_THREADS", "2")
import getpass
import json
import logging
import math
import sys
import time
import traceback
from collections import Counter, deque
from datetime import datetime, timezone

from qiskit import transpile
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

from shor299 import ROOT, SHOTS, SEED, decode, hardware_circuit, polynomial_lookup

FILE = ROOT / "Shor299-hardware.json"
TAG = "shor299-full-30s-20261119"
LIMIT = 30


def save(record):
    tmp = FILE.with_suffix(".tmp")
    tmp.write_text(json.dumps(record, indent=2), encoding="utf8")
    tmp.replace(FILE)


def nearby_layout(backend, width):
    props = backend.properties()
    bad = set(props.faulty_qubits())
    bad_edges = {tuple(sorted(g.qubits)) for g in props.faulty_gates() if len(g.qubits)==2}
    neighbors = {}
    for x,y in backend.coupling_map.get_edges():
        if x in bad or y in bad or tuple(sorted((x,y))) in bad_edges:
            continue
        neighbors.setdefault(x,set()).add(y)
        neighbors.setdefault(y,set()).add(x)
    for root in sorted(neighbors, key=lambda x:-len(neighbors[x])):
        seen, todo, result = {root}, deque([root]), []
        while todo and len(result)<width:
            q = todo.popleft()
            result.append(q)
            for v in sorted(neighbors[q]-seen):
                seen.add(v)
                todo.append(v)
        if len(result)==width:
            return result
    raise RuntimeError("Insufficient connected qubits")


def prepare(backend, qc):
    isa = transpile(qc, backend, initial_layout=nearby_layout(backend,qc.num_qubits),
                    optimization_level=1, routing_method="sabre", seed_transpiler=SEED)
    backend.check_faulty(isa)
    duration = isa.estimate_duration(backend.target)
    rep = backend.default_rep_delay
    used = set(isa.layout.initial_index_layout(filter_ancillas=True))
    reset = max(backend.target["reset"][q,].duration for q in used)
    estimate = 2 + SHOTS*(duration+rep+reset)
    counts = dict(isa.count_ops())
    return isa, {"native_gates":counts, "duration_per_shot_s":duration, "reset_s":reset,
                 "rep_delay_s":rep, "estimated_usage_s":estimate,
                 "two_qubit_gates":sum(counts.get(g,0) for g in ("cz","cx","ecr")),
                 "two_qubit_depth":isa.depth(lambda op:len(op.qubits)==2)}


def run():
    if not sys.stdin.isatty():
        raise RuntimeError("Interactive console required")
    rec = json.loads(FILE.read_text()) if FILE.exists() else {}
    if rec.get("stage") in ("done","over_budget","terminal_error"):
        return
    key = getpass.getpass("IBM Cloud API key (hidden): ").strip()
    if not key:
        return
    service = QiskitRuntimeService(channel="ibm_quantum_platform", token=key,
                                   plans_preference=["open"], region="us-east")
    if "job_id" in rec:
        job = service.job(rec["job_id"])
    elif rec.get("stage")=="submitting":
        jobs = service.jobs(job_tags=[TAG],limit=2)
        if len(jobs)!=1:
            raise RuntimeError("Reconcile previous submission")
        job = jobs[0]
    else:
        targets = {b.name:b for b in service.backends(simulator=False,min_num_qubits=44) if not b.is_mock}
        qc = hardware_circuit(polynomial_lookup)
        compiled = {}
        while True:
            queues = {k:b.status().to_dict() for k,b in targets.items()}
            active = [k for k,v in queues.items() if v["operational"] and v["status_msg"].lower()=="active"]
            name = min(active,key=lambda k:(queues[k]["pending_jobs"],k))
            rec = {"stage":"compiling","backend":name, "shots":SHOTS, "execution_cap_s":LIMIT,
                   "queues":queues,"queue_snapshot_utc":datetime.now(timezone.utc).isoformat(),
                   "logical_qubits":qc.num_qubits, "job_tag":TAG,
                   "oracle":"full reversible modular-multiplication tables in Boolean polynomial form"}
            save(rec)
            if name in compiled:
                break
            compiled[name] = prepare(targets[name],qc)
        isa, sizing = compiled[name]
        rec.update(sizing)
        if math.ceil(sizing["estimated_usage_s"])>LIMIT:
            rec["stage"]="over_budget"
            save(rec)
            return
        sampler = SamplerV2(mode=targets[name],options={"max_execution_time":LIMIT,
                            "environment":{"job_tags":[TAG]},
                            "twirling":{"enable_measure":False,"enable_gates":False},
                            "dynamical_decoupling":{"enable":False}})
        rec["stage"]="submitting"
        save(rec)
        job = sampler.run([isa],shots=SHOTS)
    rec.update(job_id=job.job_id(),stage="submitted")
    save(rec)
    while True:
        status = str(job.status())
        if status != rec.get("ibm_status"):
            rec["ibm_status"]=status
            save(rec)
        if status in ("DONE","ERROR","CANCELLED"):
            break
        time.sleep(8)
    if status=="DONE":
        counts = job.result()[0].data.c.get_counts()
        assert sum(counts.values())==SHOTS
        denoms = Counter()
        for s,n in counts.items():
            result = decode(int(s,2))
            if result:
                denoms[result["denominator"]]+=n
        rec.update(counts=counts, verified_factor_shots=sum(denoms.values()),denominators=denoms)
    else:
        rec["ibm_error"]=str(job.error_message())[:1500]
    for _ in range(120):
        metrics = job.metrics()
        if metrics.get("usage",{}).get("status")=="complete":
            break
        time.sleep(5)
    rec.update(stage="done" if status=="DONE" else "terminal_error", metrics=metrics)
    save(rec)


if __name__=="__main__":
    logging.disable(logging.CRITICAL)
    try:
        run()
    except Exception as exc:
        from pathlib import Path
        frames = [[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(exc.__traceback__)]
        (ROOT.parent/"work"/"shor299-error.json").write_text(json.dumps({"type":type(exc).__name__,"frames":frames}))
        print(type(exc).__name__)
    input("Press Enter to close.")

Personal comments

Personal comments will be added here.