I have been trying to build a Shor's Algorithm simulation for N = 15 on Qiskit's framework. Having referenced the Qiskit textbook, I built a circuit that largely resembles what they have done, with a few minor caveats. I am getting some strange and unexpected measurements, could anybody find where my problem is? Below is my code.
N = 15 a = np.random.randint(2, 15) if math.gcd(a, N) != 1: raise ValueError("Non-trivial factor.") print(a) def a_mod15(a, x): if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(x): if a in [2, 13]: U.swap(0, 1) U.swap(1, 2) U.swap(2, 3) if a in [7, 8]: U.swap(2, 3) U.swap(1, 2) U.swap(0, 1) if a == 11: U.swap(1, 3) U.swap(0, 2) if a in [7, 11, 13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, x) c_U = U.control() return c_U def mod_exp(qc, n, m, a): for x in range(n): qc.append(a_mod15(a, 2**x), [x] + list(range(n, n + m))) def iqft(qc, n): qc.append(QFT(len(n), do_swaps = False).inverse(), n) def circ(n, m, a): # Let n = 'X register' # Let m = 'W register' qc = QuantumCircuit(n + m, n) qc.h(range(n)) qc.x(n + m - 1) mod_exp(qc, n, m, a) iqft(qc, range(n)) qc.measure(range(n), range(n)) return qc n = 4 m = 4 qc = circ(n, m, a) qc.draw(fold=-1) simulator = Aer.get_backend('qasm_simulator') counts = execute(qc, backend=simulator).result().get_counts(qc) plot_histogram(counts) These are the expected Qiskit results (note they used 8 counting qubits and I used 4): 
