Quantum Counterfeit Coins
Quantum algorithms that provably outperform classical ones are rare. Most require specific problem structures or unproven complexity assumptions. The counterfeit coin problem is different: simple to state, and the quantum speedup is unconditional - queries versus classically.
This post covers the problem, classical solution, and a detailed walkthrough of the quantum algorithm with full Dirac notation and my Cirq implementation.
The Counterfeit Coin Problem
The problem dates back to 1945 when E. D. Schell posed it in the American Mathematical Monthly:
You have coins that look identical. One of them is counterfeit and weighs slightly less than the others. You have a balance scale that tells you whether the left side is heavier, lighter, or equal to the right side. What’s the minimum number of weighings needed to identify the counterfeit coin?
For concreteness, imagine you have 16 coins. One is fake. How do you find it?
The Classical Solution
The classical approach is binary search. At each step, you divide the coins into groups and weigh them against each other:
- Split the 16 coins into two groups of 8
- Weigh them - the lighter side contains the counterfeit
- Split those 8 coins into two groups of 4
- Continue halving until you find the fake
This requires weighings. For 16 coins, that’s 4 weighings. For 1 million coins? Just 20 weighings.
Binary search is remarkably efficient, and it’s provably optimal for classical algorithms. Any deterministic classical algorithm requires queries to the balance scale.
But what if the balance scale is quantum?
Quantum Approach
In 2010, Iwama, Nishimura, Raymond, and Teruyama showed something remarkable: a quantum algorithm can find the counterfeit coin in weighings - independent of the number of coins.
For 16 coins or 16 billion coins, you need just one quantum query to the balance. Classical binary search requires queries; the quantum algorithm needs .
It turns out the counterfeit coin problem can be reformulated as an instance of the Bernstein-Vazirani problem, which quantum computers solve in a single query.
The Bernstein-Vazirani Algorithm
First, some background on Bernstein-Vazirani.
The Problem
Given a function defined as:
where is an unknown secret string, find using as few queries to as possible.
Classical complexity: We need queries (one for each bit of ).
Quantum complexity: Just 1 query.
Why Does This Matter for Coins?
We can encode the counterfeit coin’s position as a secret string. If the counterfeit is at position , let (the string with a 1 only at position ). Then:
The function tells us whether coin is in our query or not. The quantum balance acts as this oracle - it returns information about whether the counterfeit is among the coins we’re weighing.
The Quantum Algorithm
The quantum solution builds up in four steps.
Setup
We have coins (I’ll use ). We need qubits:
- Qubits through : represent which coins to place on the scale
- Qubit : ancilla qubit for the balance result
The counterfeit coin is at position (unknown to us, but the oracle knows).
import cirq
from collections import Counter
n = num_coins = 16
num_qubits = num_coins + 1
m = counterfeit_index = 7 # The oracle's secret
qbs = cirq.LineQubit.range(num_qubits)
Note: In this simulation, we know m to construct the oracle. In a real scenario, the oracle would be a black-box physical process (the quantum balance) that we query without knowing which coin is counterfeit.
Step 1: Create a Superposition
First, we create an equal superposition over all possible coin selections:
Each basis state represents a weighing configuration: coin is on the scale if .
circuit = cirq.Circuit(cirq.H.on_each(*qbs[:-1]))
Step 2: Filter for Even-Weight Strings
There’s a subtlety here. We need our superposition to contain only strings with even Hamming weight (even number of 1s).
Why? This constraint comes from the mathematical structure of the algorithm, not from physical balance requirements. The Bernstein-Vazirani reduction requires the query strings to form a subspace where the inner product properties work out correctly. Even-weight strings form exactly such a subspace - they’re closed under XOR and have the right interference properties for the final Hadamard transform to reveal the secret.
We compute the parity using a cascade of CNOT gates:
circuit.append([cirq.CNOT(qbs[i], qbs[n]) for i in range(n)])
Then we flip and measure the ancilla:
circuit.append([cirq.X(qbs[n]), cirq.measure(qbs[n], key="is_even")])
After the X gate, the ancilla is if the parity was even, if odd.
If we measure 1: We have successfully projected onto the even-weight subspace. This happens with probability exactly .
If we measure 0: The parity was odd. We must restart.
The state after successful projection is:
Step 3: The Quantum Oracle (Balance Query)
Next we query the quantum balance using the Bernstein-Vazirani oracle. This is implemented as a controlled sub-circuit that only runs if our parity check succeeded:
sub_circuit = cirq.Circuit()
sub_circuit.append(cirq.H(qbs[n]))
sub_circuit.append(cirq.CNOT(qbs[m], qbs[n]))
sub_circuit.append(cirq.H.on_each(*qbs[:-1]))
Breaking this down mathematically.
Preparing the Ancilla
We start by applying Hadamard to the ancilla (which is after our successful parity check):
Our full state is now:
The Oracle Query
The oracle applies a CNOT with the counterfeit qubit as control and the ancilla as target. This computes:
This is phase kickback. The oracle flips the ancilla when , but because the ancilla is in the state, this manifests as a phase flip on the input register.
After the oracle:
The phase encodes the counterfeit position .
Final Hadamard Transform
Now we apply Hadamard gates to all coin qubits:
The full state becomes:
Rearranging:
where is the unit vector with 1 at position .
The inner sum is non-zero only when has even Hamming weight, i.e., when has the opposite parity of . Since has Hamming weight 1 (odd), we need to have odd weight.
For such , the inner sum equals , giving us:
Wait - this is a superposition over odd-weight strings. How do we find ?
Step 4: Measurement and Identification
The phases from the oracle create destructive interference that eliminates most terms, leaving the final state concentrated on specific strings that reveal .
When we measure, we get one of two outcomes:
- (all zeros except position is 1)
- (all ones except position is 0)
Both are odd-weight strings (Hamming weight 1 or ), and both reveal as the unique bit that differs from the rest.
Why does this happen? The oracle phase correlates perfectly with bit across all even-weight basis states. When we apply the final Hadamard transform, constructive interference occurs only for strings where bit is “special” - either the only 1 or the only 0. All other odd-weight strings destructively cancel.
In practice, measure all qubits and find the bit that differs from the majority.
circuit.append(cirq.CircuitOperation(sub_circuit.freeze()).with_classical_controls("is_even"))
circuit.append([cirq.measure(qbs[i], key=f"qubit({i:02})") for i in range(n)])
Running the Algorithm
simulator = cirq.Simulator()
results = simulator.run(circuit)
num_iterations = 1
while True:
if results.measurements["is_even"][0] == 1:
print("iteration:", num_iterations)
print(results)
break
results = simulator.run(circuit)
num_iterations += 1
The algorithm repeats until we get a successful parity projection (expected 2 attempts on average).
Finding the Counterfeit
data = [results.data[f"qubit({i:02})"][0] for i in range(n)]
counts = Counter(data)
# Find the least common measured value
least_common = min(counts, key=counts.get)
least_common_index = data.index(least_common)
print("index of counterfeit coin:", least_common_index)
Output:
iteration: 1
index of counterfeit coin: 7
The counterfeit was at index 7, and we found it with a single oracle query!
The Complete Circuit
The full circuit (for 16 coins):
0: ───H───@─────────────────────────────────────────────────────────────[...]───M──
│ ║
1: ───H───┼───@─────────────────────────────────────────────────────────[...]───M──
│ │ ║
2: ───H───┼───┼───@─────────────────────────────────────────────────────[...]───M──
│ │ │ ║
... ... ║
│ │ │ ║
7: ───H───┼───┼───┼───@─────────────────────────────────────────────────[BV ]───M──
│ │ │ │ ║
... ... ║
│ │ │ │ ║
16: ──────X───X───X───X───...───X───M('is_even')────────────────────────╩═══────────
The [BV] box contains the Bernstein-Vazirani subcircuit that runs conditionally on is_even = 1.
Complexity Analysis
Comparing the quantum and classical approaches:
| Classical | Quantum | |
|---|---|---|
| Query Complexity | ||
| Total Operations | gates | |
| Success Probability | 100% | 50% per attempt |
The quantum algorithm uses oracle queries but requires quantum gates to prepare the superposition and compute parity. The 50% success rate means we need an expected 2 runs.
The speedup is in query complexity - the number of times we consult the balance. This is the standard measure for oracle problems, and here quantum computing reduces to .
Note: This analysis assumes ideal, noiseless quantum operations. Real quantum hardware introduces errors that would require error correction or multiple trials, but the fundamental query complexity advantage remains.
Multiple Counterfeit Coins
The original paper also considers the case of counterfeit coins among total:
- Classical: queries
- Quantum: queries
This is a quartic speedup, and notably the quantum complexity is independent of .
Conclusion
The counterfeit coin problem illustrates quantum speedup cleanly. By recasting a classical search problem as an instance of Bernstein-Vazirani, we reduce the query complexity from logarithmic to constant.
The algorithm demonstrates fundamental principles: superposition lets us query all coin configurations at once, phase kickback encodes the oracle’s answer in quantum phases, and interference via the final Hadamard extracts the hidden information.
The speedup here is provable and unconditional - no complexity assumptions required. For anyone interested in quantum computing, the counterfeit coin problem is a clean example of quantum advantage in action.
Further Reading
- Quantum Algorithm Zoo - comprehensive catalog of quantum algorithms with proven speedups
- Bernstein-Vazirani algorithm - the underlying quantum algorithm
- Quantum counting - related quantum search techniques
References
- Iwama, K., Nishimura, H., Raymond, R., & Teruyama, J. (2012). Quantum Counterfeit Coin Problems. Theoretical Computer Science.
- Bernstein, E., & Vazirani, U. (1997). Quantum Complexity Theory. SIAM Journal on Computing.
- Terhal, B. M., & Smolin, J. A. (1998). Single quantum querying of a database. Physical Review A.