You are handed a function $f$ that you cannot open: you can only call it with an input of $n$ bits and read one bit of answer. You are guaranteed that it is of only two kinds, constant (the same answer for all inputs) or balanced (0 for exactly half of the inputs and 1 for the other half), and you must say which. This is the Deutsch-Jozsa problem. A deterministic classical algorithm, in the worst case, needs $2^{n-1} + 1$ calls; the quantum circuit uses just one and never errs. It is a historical example (Deutsch and Jozsa, 1992) in which a quantum computation beats a classical one, and it must be read with a caution that this article puts in front of you with numbers: against a classical algorithm that allows itself a small probability of error, the advantage disappears.
This is the fourth lesson of Quantum Computing in Italiano. You need the Hadamard and the CNOT from the lesson on gates and the idea of interference from the first. The listings are in NumPy (Python 3.14.4, NumPy 2.5.4), executed in local simulation; I repeated the quantum result with Qiskit 2.6.2.
How many questions a classical algorithm needs
Let $N = 2^n$ be the number of inputs. A deterministic algorithm that has read $N/2$ answers, all equal, cannot yet decide: it could be the constant function, but it could also be a balanced one that happened to give the first $N/2$ answers equal. So $N/2 + 1$ calls are needed in the worst case. The first listing checks it for $N = 8$ by enumerating the 70 balanced functions: for each number $k$ of calls it checks whether there is a balanced function whose first $k$ answers are all equal.
The second case is that of someone who accepts a small error. It queries $k$ randomly chosen points and declares "constant" if the answers are all equal. On a constant function it never errs; on a balanced one it errs with probability $2\binom{N/2}{k}/\binom{N}{k}$, which for large $N$ tends to $2^{1-k}$.
import itertools
from fractions import Fraction
from math import comb
import numpy as np
# Deterministic case, N = 8: after k queries (any points, by symmetry the first k)
# is there a balanced function whose answers are all equal?
N = 8
balanced = [b for b in itertools.product((0, 1), repeat=N) if sum(b) == N // 2]
print("balanced functions on 8 points:", len(balanced))
for k in range(1, 7):
ambiguous = any(len(set(b[:k])) == 1 for b in balanced)
print(f"k = {k}: does a balanced function always answer the same? {ambiguous}")
# Probabilistic case: k random points, "constant" if the k answers are equal.
# A balanced function fools the algorithm with probability 2*C(N/2,k)/C(N,k).
def error(N, k):
return Fraction(2 * comb(N // 2, k), comb(N, k))
for N in (8, 1024, 2 ** 20):
rows = [f"k={k}: {float(error(N, k)):.4f}" for k in (1, 2, 3, 4, 5)]
print(f"N = {N:8d} ->", " ".join(rows))
# Check with samples: N = 1024, k = 3, one fixed balanced function
rng = np.random.default_rng(9)
N = 1024
f = np.zeros(N, dtype=int)
f[rng.choice(N, size=N // 2, replace=False)] = 1
trials = 200000
errors = 0
for _ in range(trials):
points = rng.choice(N, size=3, replace=False)
errors += len(set(f[points])) == 1
print("N=1024, k=3: estimated error", errors / trials, " exact", round(float(error(N, 3)), 4))
# Output:
# balanced functions on 8 points: 70
# k = 1: does a balanced function always answer the same? True
# k = 2: does a balanced function always answer the same? True
# k = 3: does a balanced function always answer the same? True
# k = 4: does a balanced function always answer the same? True
# k = 5: does a balanced function always answer the same? False
# k = 6: does a balanced function always answer the same? False
# N = 8 -> k=1: 1.0000 k=2: 0.4286 k=3: 0.1429 k=4: 0.0286 k=5: 0.0000
# N = 1024 -> k=1: 1.0000 k=2: 0.4995 k=3: 0.2493 k=4: 0.1243 k=5: 0.0619
# N = 1048576 -> k=1: 1.0000 k=2: 0.5000 k=3: 0.2500 k=4: 0.1250 k=5: 0.0625
# N=1024, k=3: estimated error 0.249565 exact 0.2493
The listing shows five things. On 8 points there are 70 balanced functions, and for $k = 1, \dots, 4$ there is one that always answers the same: the first False appears at $k = 5 = N/2 + 1$. The function error uses Fraction and math.comb to compute the probability exactly. With $k = 3$ the error is 0.1429 for $N = 8$, 0.2493 for $N = 1024$ and 0.2500 for $N = 2^{20}$: from the third point on it no longer depends on $N$. With 5 points it is about 0.0625 for large $N$, that is $2^{-4}$. The last line checks the formula for $N = 1024$ with 200,000 fixed-seed trials: 0.249565 against 0.2493 exact.
The point to take away is this: if an error below 30% or 15% is good enough for you, three or four queries are enough whatever $n$ is. The advantage of the quantum circuit is real only against the algorithm that allows no errors.
The circuit: Hadamard, phase oracle, Hadamard
The circuit has three steps on the $n$ input qubits, all starting from $|0\dots0\rangle$. You apply $H^{\otimes n}$ and obtain the uniform superposition, with amplitude $1/\sqrt N$ for each $x$. The oracle multiplies each amplitude by $(-1)^{f(x)}$. You apply $H^{\otimes n}$ again and measure. The amplitude of $|0\dots0\rangle$ at the end is the average of the signs:
If $f$ is constant the sum is $\pm N$ and the probability of reading all zeros is 1. If it is balanced, half of the signs are +1 and half −1, the sum is 0 and that probability is 0. This is the interference of the article on the qubit: the amplitudes add up or cancel before the measurement.
The phase oracle is obtained from the "bit" oracle $U_f|x\rangle|y\rangle = |x\rangle|y \oplus f(x)\rangle$ if the auxiliary qubit is in the state $|-\rangle$: the auxiliary stays unchanged and the sign $(-1)^{f(x)}$ moves onto the input register (the phase kickback). The listing does both versions and compares them.
import itertools
import numpy as np
def walsh_hadamard(n):
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
W = np.eye(1)
for _ in range(n):
W = np.kron(W, H)
return W
def deutsch_jozsa(f, n):
"""f: array of N=2^n values 0/1. Returns P(measuring 0...0) on the n input qubits."""
W = walsh_hadamard(n)
state = np.zeros(2 ** n)
state[0] = 1.0
state = W @ state # uniform superposition
state = (-1.0) ** f * state # phase oracle: (-1)^f(x)
state = W @ state # interference
return float(state[0] ** 2)
# All 256 functions f: {0,1}^3 -> {0,1}
n, N = 3, 8
classes = {"constant": [], "balanced": [], "other": []}
for bits in itertools.product((0, 1), repeat=N):
f = np.array(bits)
weight = int(f.sum())
key = "constant" if weight in (0, N) else "balanced" if weight == N // 2 else "other"
classes[key].append(deutsch_jozsa(f, n))
for k, v in classes.items():
v = np.array(v)
print(f"{k:10s}: {len(v):3d} functions, P(0...0) between {v.min():.4f} and {v.max():.4f}")
# The same with the explicit ancilla: oracle U_f|x,y> = |x, y xor f(x)>, ancilla in |->
def bit_oracle(f, n):
N = 2 ** n
U = np.zeros((2 * N, 2 * N))
for x in range(N):
for y in (0, 1):
U[2 * x + (y ^ int(f[x])), 2 * x + y] = 1.0
return U
rng = np.random.default_rng(1)
f = np.zeros(N, dtype=int)
f[rng.choice(N, size=N // 2, replace=False)] = 1 # a random balanced function
ket0 = np.zeros(2 * N); ket0[0] = 1 # |000>|0>
H1 = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
X1 = np.array([[0, 1], [1, 0]])
pre = np.kron(walsh_hadamard(n), H1 @ X1) # H on the n qubits, X then H on the ancilla -> |->
post = np.kron(walsh_hadamard(n), np.eye(2))
fin = post @ bit_oracle(f, n) @ pre @ ket0
p_zero = float((fin[0] ** 2 + fin[1] ** 2))
print("f =", f.tolist())
print("with ancilla: P(0...0) =", round(p_zero, 6), "; phase oracle:", round(deutsch_jozsa(f, n), 6))
# A constant function and one of weight 1 (which violates the promise)
print("f = 1 everywhere :", round(deutsch_jozsa(np.ones(N, dtype=int), n), 6))
one = np.zeros(N, dtype=int); one[5] = 1
print("f = 1 only at x=5 :", round(deutsch_jozsa(one, n), 6), " (formula (1-2w/N)^2 =", round((1 - 2 / N) ** 2, 6), ")")
# n = 10: 1024 amplitudes, a random balanced function
n = 10
N = 2 ** n
f = np.zeros(N, dtype=int)
f[rng.choice(N, size=N // 2, replace=False)] = 1
print("n = 10, balanced: P(0...0) =", round(deutsch_jozsa(f, n), 6), "; constant: ", round(deutsch_jozsa(np.zeros(N, dtype=int), n), 6))
# Output:
# constant : 2 functions, P(0...0) between 1.0000 and 1.0000
# balanced : 70 functions, P(0...0) between 0.0000 and 0.0000
# other : 184 functions, P(0...0) between 0.0625 and 0.5625
# f = [0, 0, 1, 1, 0, 1, 0, 1]
# with ancilla: P(0...0) = 0.0 ; phase oracle: 0.0
# f = 1 everywhere : 1.0
# f = 1 only at x=5 : 0.5625 (formula (1-2w/N)^2 = 0.5625 )
# n = 10, balanced: P(0...0) = 0.0 ; constant: 1.0
The function walsh_hadamard builds $H^{\otimes n}$ with np.kron; deutsch_jozsa applies the three steps and returns state[0] ** 2, the probability of reading all zeros (the input is real and the matrices are too, so there are no phases to handle). For $n = 3$ the program enumerates all 256 functions: the 2 constant ones have probability 1.0000, the 70 balanced ones 0.0000 (up to floating-point rounding), and the 184 "other" ones, which violate the promise, give intermediate values between 0.0625 and 0.5625. The second block uses the bit oracle with the auxiliary: bit_oracle builds the permutation matrix $U_f$, and the result with the auxiliary (0.0) coincides with that of the phase oracle for the same balanced function.
The last lines show the flip side of the promise. A function that is 1 at a single point (one[5] = 1) is neither constant nor balanced, and gives probability 0.5625, equal to $(1 - 2w/N)^2$ with $w = 1$ points at 1 out of $N = 8$: there is no way to tell from the result that the promise does not hold. For $n = 10$, with 1024 amplitudes, the program confirms: a random balanced function gives 0.0 and the constant one 1.0.
What really matters
| Algorithm | Queries | Error |
|---|---|---|
| Classical deterministic | $N/2 + 1$ in the worst case (5 for $N = 8$) | none |
| Classical probabilistic, $k = 3$ | 3, for any $N$ | on balanced functions about 0.25 for large $N$, 0 on constant ones |
| Quantum (ideal simulation) | 1 call of the oracle | none |
The table summarizes the three costs in the measure you derived: the quantum algorithm has the advantage only if the comparison is with the deterministic row. With a modest error tolerance, the middle row is just as short and does not depend on $n$. This is why Deutsch-Jozsa is taught as a demonstration of the mechanism (interference that concentrates probability) and not as an application. Cleve and colleagues, in the paper "Quantum Algorithms Revisited", read this and other algorithms as interference between computational paths; I read only the abstract.
Two limits remain anyway. The first is that the count is made in oracle queries: building $U_f$ for a specific function costs gates, and that cost does not enter the comparison. The second is that a real device never gives exactly 0 or 1: a decision threshold would be needed, and how reliable it is depends on the machine. It is not a figure of this article.
The mistakes made most often
- Applying the algorithm to a function that does not respect the promise and interpreting 0.5625 as "balanced".
- Forgetting the auxiliary in $|-\rangle$ when using the bit oracle: without it the sign does not move onto the input register.
- Comparing the circuit with the deterministic algorithm and concluding "exponential speedup" without saying that a classical algorithm exists with three questions and an error of 25%.
- Counting a single call as the total cost, ignoring the gates that realize the oracle.
The four mistakes have the same shape: attributing to the algorithm an advantage that belongs to a particular comparison. Before quoting a speedup factor it is always worth saying against which classical algorithm it is measured and at which error tolerance.
What you can do now
You can simulate the Deutsch-Jozsa circuit for any small $n$, verify it on all 256 functions of 3 bits, explain why the auxiliary in $|-\rangle$ turns the bit oracle into a phase oracle, and compute with an exact formula how many questions a classical algorithm needs with a fixed error. Above all you can say who the advantage is against. In the next lesson, Grover, the advantage is more modest in form but holds even against probabilistic algorithms.
Frequently asked questions
What does the result of the Deutsch-Jozsa algorithm guarantee?
It guarantees the answer only if the function is constant or balanced. In that case, in the ideal simulation, the probability of reading all zeros is 1 for the constant function and 0 for the balanced one. Outside the promise it gives intermediate values, such as 0.5625 for a function that is 1 at one point out of 8.
Why is the auxiliary qubit in |−> needed?
With the auxiliary in $|-\rangle$, the oracle that adds $f(x)$ to its bit leaves the auxiliary as it is and multiplies the amplitude of $|x\rangle$ by $(-1)^{f(x)}$: this is the phase kickback. The listing checks that the two oracles give the same probability.
Is Deutsch-Jozsa an exponential speedup?
Only with respect to a deterministic classical algorithm, which in the worst case asks $2^{n-1}+1$ questions. A probabilistic classical algorithm with three questions errs on a balanced function with probability about 0.25 for any large $n$, so against it the advantage is not exponential.
How many times is the oracle called?
Just once, whatever $n$ is. The cost in gates of realizing the oracle of a specific function is not included in this count.
The previous lesson of the series is the one on entanglement and quantum teleportation (article 3).
Sources
- D. Deutsch, R. Jozsa, "Rapid solution of problems by quantum computation", Proc. R. Soc. Lond. A 439, 553 (1992) - the original problem and algorithm; title, journal and year checked on Crossref, the text was not read, consulted on 2026-11-13
- R. Cleve, A. Ekert, C. Macchiavello, M. Mosca, "Quantum Algorithms Revisited", arXiv:quant-ph/9708016 (1997) - the reading of quantum algorithms as interference; abstract read, consulted on 2026-11-13
- Qiskit on PyPI - current version 2.6.2 (uploaded on 2026-11-05), used to repeat the circuit, consulted on 2026-11-13
The two listings were run twice with Python 3.14.4 and NumPy 2.5.4, with identical output. The circuit with a phase oracle was repeated with Qiskit 2.6.2 on three functions (balanced, constant, one-point): 0.0, 1.0 and 0.5625 as in the listing. The formulas $2^{n-1}+1$ and $2\binom{N/2}{k}/\binom{N}{k}$ are derived here with the reasoning given and checked by enumeration ($N = 8$) and by sampling ($N = 1024$), not read from a source.
Commenti
Caricamento commenti...
Sign in to comment