How to flip qubit C if (A xor B)=1?

Assume I have tree qubits (A,B, and C)

I would like to flip qubit C if (A xor B)=1. The gate CCNOT(A,B,C) will flip C if A and B are both one.

Please let me know if there is a solution.

• You mean something like this? algassert.com/quirk#circuit={%22cols%22:[[%22%E2%80%A2%22,%22%E2%97%A6%22,%22X%22],[%22%E2%97%A6%22,%22%E2%80%A2%22,%22X%22]]} Feb 21, 2022 at 0:39
• Yes, thank you. Is there a name for such gates in Qiskit? Feb 21, 2022 at 1:19

why not just use two CNOTs to get the parity of qubits 0 and 1 on qubit 2? This circuit will set q_2 = q_0 XOR q_1:

from qiskit.circuit import QuantumCircuit
from qiskit import Aer, transpile

backend_sim = Aer.get_backend('statevector_simulator')
c = QuantumCircuit(3, 3)

# you can try here all 4 combinations
c.x(0)
c.x(1)

# the entanglement circuit
c.cnot(0, 2)
c.cnot(1, 2)
c.measure(range(3), range(3))
print(c.draw())

backend_sim.run(transpile(c, backend_sim)).result().get_counts()

• There should be third CNOT to uncompute (unentangled) qubits q0 and q1 as no control qubit is changed when controlled gate is used. Feb 21, 2022 at 6:50
• @MartinVesely could you please explain what you mean? The truth table for this gate in the computational basis is identity for q0'=q0, q1'=q1 and q2' = q2 ^ q0 ^ q1, where q_i' are the output states. Is this not enough?
– Lior
Feb 21, 2022 at 8:03
• I am sorry, this is my oversight. Firsly I think that you apply CNOT on qubits 0 and 1 and then CNOT on 1 and 2 which is also correct but the uncomputation is needed. In Your case you have CNOT (0,2) and CNOT(1,2), so qubits 0 and 1 remain unchanged and no uncomputation is needed. Sorry again :-) Feb 21, 2022 at 12:12
• Thank you so much Feb 21, 2022 at 20:26

I am not aware of such gate in qiskit's standard library, but you can create it as a custom gate.

As stated in the comment, the gate you are looking for is

I am not sure of such gate exists in the qiskit's standard library. But you can build it as a custom gate. First note that

Then you can do this as

from qiskit import QuantumCircuit

my_gate = QuantumCircuit(3)
my_gate.x(1)
my_gate.ccx(0,1,2)
my_gate.x(1)

my_gate.x(0)
my_gate.ccx(0,1,2)
my_gate.x(0)

custom_gate = my_gate.to_gate()

• This seems too complicated. Just use two CNOTs - first one between qubits 0 and 1, this give you q0 XOR q1 and then second CNOT between q1 and q2 to obtain desired negation if q0 XOR q1 is 1. And of course add third CNOT to uncompute q0 and q1. Feb 21, 2022 at 6:47
• Thank you both of you, this is helpful. Feb 21, 2022 at 20:25

Quirk has a concept of "combined parity controls" for this. But you can also just decompose into a pair of CNOTs or X-controlled Zs.

More abstractly, if you generalize the concept of one operation controlling another, then the operation you want is $$\text{Control}(Z_1 Z_2, X_3)$$ where

$$\text{Control}(A, B) = \exp\left(-\frac{i}{\pi} \ln(A) \ln(B)\right)$$