forked from microsoft/Quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleGrover.qs
41 lines (37 loc) · 1.56 KB
/
SimpleGrover.qs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Quantum.Samples.SimpleGrover {
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Math;
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.Measurement;
/// # Summary
/// This operation applies Grover's algorithm to search all possible inputs
/// to an operation to find a particular marked state.
@EntryPoint()
operation SearchForMarkedInput(nQubits : Int) : Result[] {
using (qubits = Qubit[nQubits]) {
// Initialize a uniform superposition over all possible inputs.
PrepareUniform(qubits);
// The search itself consists of repeatedly reflecting about the
// marked state and our start state, which we can write out in Q#
// as a for loop.
for (idxIteration in 0..NIterations(nQubits) - 1) {
ReflectAboutMarked(qubits);
ReflectAboutUniform(qubits);
}
// Measure and return the answer.
return ForEach(MResetZ, qubits);
}
}
/// # Summary
/// Returns the number of Grover iterations needed to find a single marked
/// item, given the number of qubits in a register.
function NIterations(nQubits : Int) : Int {
let nItems = 1 <<< nQubits; // 2^numQubits
// compute number of iterations:
let angle = ArcSin(1. / Sqrt(IntAsDouble(nItems)));
let nIterations = Round(0.25 * PI() / angle - 0.5);
return nIterations;
}
}