-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBernstein Vazirani.slq
56 lines (44 loc) · 1.16 KB
/
Bernstein Vazirani.slq
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Bernstein-Vazirani algorithm
// - Returns s where f(x) = s·x mod 2
//
def bernstein_vazirani[n:!ℕ](f: const uint[n] !→ lifted 𝔹):!uint[n]{
cand := 0:uint[n];
for k in [0..n) { cand[k] := H(cand[k]); }
// state ignoring normalization:
// ∑ᵥ|v⟩
if f(cand) {
phase(π);
}
// state ignoring normalization:
// ∑ᵥ(-1)^f(v) |v⟩
// = ∑ᵥ(-1)^(s·v) |v⟩
// = (|0⟩+(-1)^(s₁)|1⟩) ⊗ ⋯ ⊗ (|0⟩+(-1)^(sₙ)|1⟩)
for k in [0..n) { cand[k] := H(cand[k]); }
s := measure(cand);
return s;
}
/* TEST */
def f[n:!ℕ](s:!uint[n])(x:uint[n])lifted:𝔹{
y := scal(s, x)%2;
return y==1;
}
def scal[n:!ℕ](const x:uint[n], const y:uint[n])qfree:uint[n] {
// computes the scalar product x·y
count := 0:uint[n];
for k in [0..n) {
count+=x[k] && y[k];
}
return count;
}
def main() {
// test with all secret strings on 3 bits
for i in [0..8) {
s := i coerce !uint[3];
s₀ := bernstein_vazirani(f(s));
assert(s==s₀);
}
// test with secret string s = 01
s := 1 coerce !uint[2];
s₀ := bernstein_vazirani(f(s));
return s₀;
}