# How to implement multi controlled X gates in Qasm

I wanted to know the easiest way to implement a large multi controlled x gate using Qasm and not Qiskit, if it's possible

• What do you mean by large here? Commented Mar 6 at 19:02

There's no definition of multi-controlled X (MCX) gates in the standard qasm spec. What qasm allows you to do is define custom gates. You would have to define your own MCX gate by using gates that do exist in qasm.

You can see the list of supported gates in the documentation for qasm (available for version 2.0 here)

If you want, you can see how you might decompose the MCX gate for a fixed number of controls by using, for example, qiskit (which supports MCX). If you create a circuit in qiskit containing an MCX gate, the output would contain a custom definition for the MCX gate (for a particular number of controls), and the rest of the qasm file will use that definition.

As pointed out by @xzkxyz, general multi-controlled X gates are not in the QASM2 spec. However CX gates and CCX gates are part of the QASM2 spec.

If you have a qiskit QuantumCircuit, you can export it to QASM with the QuantumCircuit.qasm method.

I'll show what happens if you add a MCX gate to a qiskit circuit with a fixed number of controls and export to qasm.

from qiskit import QuantumCircuit

qc = QuantumCircuit(4)
qc.mcx([0, 1, 2], [3]) # Add MCX with 3 control qubits
print(qc.qasm())


Output:

OPENQASM 2.0;
include "qelib1.inc";
gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; }
qreg q[4];
mcx q[0],q[1],q[2],q[3];


If we look at the output string we see that the MCX (with three controls) is implmented in terms of QASM supported operations. (cx gates, h gates, p gates etc)

If you're using OpenQASM 3, you can use the ctrl (and negctrl) modifier to turn a gate into a controlled gate; you can stack modifiers to make a multi-controlled gate. A C4XGate would then look like

ctrl @ ctrl @ ctrl @ ctrl @ x q[0], q[1], q[2], q[3], q[4]


You can run OpenQASM programs with these modifiers with the Amazon Braket SDK's local simulator; you can find examples in the "Gate Modifiers" section of this notebook.