I am looking for guidance in more generally how to developed n-bit gates in Cirq.

I am working on a QNN paper and I need to develop a n-controlled gate to be able to measure the cost function of the circuit.


2 Answers 2


This is actually very easy in Cirq. The controlled_by method can be used to automatically make any given gate controlled by an arbitrary number of control qubits. Here is a simple example for creating an X gate with 5 controls:

import cirq

qb = [cirq.LineQubit(i) for i in range(6)]

cnX = cirq.X.controlled_by(qb[0], qb[1], qb[2], qb[3], qb[4])

circuit = cirq.Circuit()
  • 1
    $\begingroup$ Thank you. I am wondering though: how can this solution work when you have n-qubits and you cannot hardcode it like the example above? $\endgroup$ Commented Jun 26, 2019 at 19:04
  • $\begingroup$ Use an unpacking asterisk, e.g. cnX = cirq.X.controlled_by(*qb[:-1]) $\endgroup$ Commented Jun 27, 2019 at 2:47
  • $\begingroup$ The specific form in this answer is going to stop working in Cirq v0.6.0, due to some tricky issues around cnX knowing some of its qubits but not all. (The meaning of num_qubits became ambiguous in ways that led to bugs. E.g. is it the total qubit count or the unspecified qubit count?) But the form cirq.X(target).controlled_by(*controls) will still work, and we added cirq.X.controlled(control_count). $\endgroup$ Commented Oct 26, 2019 at 8:41

For doing CnX (N-CNOT or N-Tofolli) gate,

The following is the correct way to do using cirq.

from cirq import X, Circuit

qbits = cirq.LineQubit.range(NUM_QBITS)
qa = cirq.NamedQubit("ansilla")

cnX = X.controlled(NUM_QBITS).on(*qbits[:NUM_QBITS], qa)


Demo: https://to.absk.im/32QqLku


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.