# General number of classical bits: recycles qubits

I am trying to write a Qiskit routine to perform qubit recycling for Shor's algorithm. This is a procedure by which the M-bit control register is replaced by a single quantum register, and the measurements of this register are fed forward to choose the phase gates for the QFT. The circuit is as follows for M=5 control qubits:

n_control = 1
n_work = L

# Quantum circuit
m = QuantumRegister(n_control, name='m')
w = QuantumRegister(n_work, name='w')

# classical registers
cl_reg = list(range(M))
for c in range(M):
cl_name = 'cl' + str(c)
cl_reg[c] = ClassicalRegister(1, name=cl_name)
# hard-wired for M=5 # <==x I need to generalize this line
qc = QuantumCircuit(m, w, cl_reg[0], cl_reg[1], cl_reg[2], cl_reg[3], cl_reg[4])

# Work register in state |1>
qc.x(1)

# increment counter
for cnt in range(M):

# initialize control register to 0
qc.initialize([1, 0], m)

# Apply H to control register
qc.h(0)

# apply ME operator
power = 2**(M-cnt-1)
qc.append(c_U1(N, a, n_work, power, u_ver, trnc_lv, barrier=False),
[0] + [i+n_control for i in range(n_work)])

# decorate control register using feed-forward phase operators
qc.h(0)
for myn in range(cnt):
qc.p(np.pi/2**(cnt-myn), 0).c_if(cl_reg[myn], 1)

# measure control register
qc.measure(m, cl_reg[cnt])
qc.barrier()

# draw circuit
qc.draw(fold=50)
plt.show()


Unfortunately, the code

qc = QuantumCircuit(m, w, [cl_reg[i] for i in range(M)])

gives an error, as I can't use a list in QuantumCircuit. How can I attach a general number M of classical registers without hard-wiring the value of M as in the code above? Also, I need separate classical registers for each bit of M, so I can't collapse the classical register to a single register. And I need to cut on previous registers, so I need to remember results of past measurements.

• Maybe a better way of asking the question is as follows. I have a qiskit code that implements the recycled qubit circuit originally posted. My code works for general values of M, except for the quantum circuit initialization. I have hardwired this to M=5 in the example code and the figure. Can someone help me with quantum circuit initialization for a general M? Commented Jun 15 at 12:45

qc = QuantumCircuit(m, w, *[cl_reg[i] for i in range(M)])