├── quickref └── qsharp-quick-reference.pdf ├── Hopper_Seattle-IntroToQuantumComputing.pptx ├── DeutschJozsaAlgorithm ├── DeutschJozsaAlgorithm.csproj ├── DeutschJozsaAlgorithm.sln ├── Driver.cs ├── Algorithm.qs ├── OracleCounterSimulator.cs ├── Tests.qs └── Oracles.qs ├── LICENSE ├── .gitignore └── README.md /quickref/qsharp-quick-reference.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/GHC18-IntroToQuantumComputing/HEAD/quickref/qsharp-quick-reference.pdf -------------------------------------------------------------------------------- /Hopper_Seattle-IntroToQuantumComputing.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/GHC18-IntroToQuantumComputing/HEAD/Hopper_Seattle-IntroToQuantumComputing.pptx -------------------------------------------------------------------------------- /DeutschJozsaAlgorithm/DeutschJozsaAlgorithm.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | netcoreapp2.0 5 | x64 6 | Quantum.DeutschJozsaAlgorithm 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /DeutschJozsaAlgorithm/DeutschJozsaAlgorithm.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27130.2036 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeutschJozsaAlgorithm", "DeutschJozsaAlgorithm.csproj", "{2A17B028-A29B-4D54-AF9B-7AE28EBC117D}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {2A17B028-A29B-4D54-AF9B-7AE28EBC117D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {2A17B028-A29B-4D54-AF9B-7AE28EBC117D}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {2A17B028-A29B-4D54-AF9B-7AE28EBC117D}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {2A17B028-A29B-4D54-AF9B-7AE28EBC117D}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {AF2CE740-7B56-478E-B3C7-60A2D0149EA8} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /DeutschJozsaAlgorithm/Driver.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | ///////////////////////////////////////////////////////////////////////////////////////////////// 5 | // This file contains C# code which runs the tests for your implementation. 6 | // You do not need to modify anything in this file. 7 | // The algorithm on which you'll be working can be found in Algorithms.qs file. 8 | ///////////////////////////////////////////////////////////////////////////////////////////////// 9 | 10 | namespace Quantum.DeutschJozsaAlgorithm 11 | { 12 | class Driver 13 | { 14 | static void Main(string[] args) 15 | { 16 | using (var sim = new OracleCounterSimulator()) { 17 | try 18 | { 19 | var runResult = RunAlgorithmOnTests.Run(sim).Result; 20 | System.Console.WriteLine(); 21 | System.Console.WriteLine("Deutsch-Jozsa algorithm is " + (runResult ? "correct!" : "incorrect :-(")); 22 | } 23 | catch (System.Exception e) { 24 | System.Console.WriteLine("Exception: " + e.InnerException.Message); 25 | } 26 | System.Console.WriteLine("Press any key to continue..."); 27 | System.Console.ReadKey(); 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /DeutschJozsaAlgorithm/Algorithm.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | ///////////////////////////////////////////////////////////////////////////////////////////////// 5 | // This file contains the template of Deutsch-Jozsa algorithm which you will be working on. 6 | ///////////////////////////////////////////////////////////////////////////////////////////////// 7 | 8 | namespace Quantum.DeutschJozsaAlgorithm { 9 | open Microsoft.Quantum.Primitive; 10 | open Microsoft.Quantum.Canon; 11 | open Microsoft.Quantum.Extensions.Diagnostics; 12 | 13 | // Inputs: 14 | // 1) the number of qubits N in the input register for the function f 15 | // 2) a quantum operation which implements the phase-flipping oracle |x⟩ -> (-1)ᶠ⁽ˣ⁾ |x⟩, 16 | // where x is an N-qubit input register, and f is a Boolean function 17 | // You are guaranteed that the function f implemented by the oracle is either 18 | // constant (returns 0 on all inputs or 1 on all inputs) or 19 | // balanced (returns 0 on exactly one half of the input domain and 1 on the other half). 20 | // Return: 21 | // true if the function f is constant 22 | // false if the function f is balanced 23 | operation DeutschJozsaAlgorithm (N : Int, oracle : (Qubit[] => Unit)) : Bool { 24 | 25 | // Create a boolean variable for storing the return value. 26 | // You'll need to update it later, so it has to be declared as mutable. 27 | mutable isConstant = true; 28 | 29 | // Allocate an array of N qubits for the input register x. 30 | using (x = Qubit[N]) { 31 | // Newly allocated qubits start in the |0⟩ state. 32 | // The first step is to prepare the qubits in the required state before calling the oracle. 33 | // Each qubit of the input register has to be in the |+⟩ state. 34 | // A qubit can be transformed from the |0⟩ state to the |+⟩ state by applying a Hadamard gate H. 35 | // You can use the library function ApplyToEach to apply a gate to each qubit of a register; 36 | // the first argument is the name of the gate to be applied, and the second argument is the name of the register. 37 | 38 | 39 | // Apply the oracle to the input register. 40 | // The syntax is the same as for applying any function or operation. 41 | 42 | 43 | // Apply a Hadamard gate to each qubit of the input register again. 44 | 45 | 46 | // Measure each qubit of the input register in the computational basis using the M operation. 47 | // You can use a for loop to iterate over the range of indexes 0..N-1. 48 | // If any of the measurement results is One, the function implemented by the oracle is balanced. 49 | // Note that you can't return the answer in the middle of a loop, 50 | // you have to update the variable isConstant using the "set" keyword. 51 | 52 | 53 | // Before releasing the qubits make sure they are all in the |0⟩ state 54 | // (otherwise you'll get a ReleasedQubitsAreNotInZeroState exception). 55 | // You can use the library operation Reset which measures a qubit and applies a correction if necessary. 56 | // The library operation ResetAll does the same for a register of qubits. 57 | 58 | } 59 | 60 | return isConstant; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /DeutschJozsaAlgorithm/OracleCounterSimulator.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | ///////////////////////////////////////////////////////////////////////////////////////////////// 5 | // This file contains parts of the testing harness. 6 | // You do not need to modify anything in this file. 7 | // The algorithm on which you'll be working can be found in Algorithms.qs file. 8 | ///////////////////////////////////////////////////////////////////////////////////////////////// 9 | 10 | using System; 11 | using System.Diagnostics; 12 | using System.Collections.Generic; 13 | using Microsoft.Quantum.Simulation.Core; 14 | using Microsoft.Quantum.Simulation.Simulators; 15 | 16 | namespace Quantum.DeutschJozsaAlgorithm 17 | { 18 | /// 19 | /// This custom quantum simulator keeps track of the number of times 20 | /// each operation is executed, by providing a custom native operation: 21 | /// `AssertOracleCallsCount` which asserts the number of times 22 | /// the given oracle (operation) has been called. 23 | /// 24 | public class OracleCounterSimulator : QuantumSimulator 25 | { 26 | private Dictionary _operationsCount = new Dictionary(); 27 | 28 | public OracleCounterSimulator( 29 | bool throwOnReleasingQubitsNotInZeroState = true, 30 | uint? randomNumberGeneratorSeed = null, 31 | bool disableBorrowing = false) : 32 | base(throwOnReleasingQubitsNotInZeroState, randomNumberGeneratorSeed, disableBorrowing) 33 | { 34 | this.OnOperationStart += CountOperationCalls; 35 | } 36 | 37 | /// 38 | /// Callback method for the OnOperationStart event. 39 | /// 40 | public void CountOperationCalls(ICallable op, IApplyData data) 41 | { 42 | if (_operationsCount.ContainsKey(op)) 43 | { 44 | _operationsCount[op]++; 45 | } 46 | else 47 | { 48 | _operationsCount[op] = 1; 49 | } 50 | } 51 | 52 | // Custom Native operation to reset the oracle counts back to 0. 53 | public class ResetOracleCallsImpl : ResetOracleCallsCount 54 | { 55 | OracleCounterSimulator _sim; 56 | 57 | public ResetOracleCallsImpl(OracleCounterSimulator m) : base(m) 58 | { 59 | _sim = m; 60 | } 61 | 62 | public override Func Body => (__in) => 63 | { 64 | _sim._operationsCount.Clear(); 65 | return QVoid.Instance; 66 | }; 67 | } 68 | 69 | // Custom Native operation to Assert the number of calls for an Operation. 70 | public class AssertOracleCallsImpl : AssertOracleCallsCount 71 | { 72 | OracleCounterSimulator _sim; 73 | 74 | public AssertOracleCallsImpl(OracleCounterSimulator m) : base(m) 75 | { 76 | _sim = m; 77 | } 78 | 79 | public override Func<(Int64, T), QVoid> Body => (__in) => 80 | { 81 | var (expected, oracle) = __in; 82 | 83 | var op = oracle as ICallable; 84 | Debug.Assert(op != null); 85 | 86 | var actual = _sim._operationsCount.ContainsKey(op) ? _sim._operationsCount[op] : 0; 87 | Debug.Assert(expected >= actual, $" Oracle should be called at most {expected} time(s), and your solution called it {actual} time(s)."); 88 | 89 | return QVoid.Instance; 90 | }; 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /DeutschJozsaAlgorithm/Tests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | ///////////////////////////////////////////////////////////////////////////////////////////////// 5 | // This file contains the Q# tests that verify the correctness of your implementation. 6 | // You do not need to modify anything in this file. 7 | // The algorithm on which you'll be working can be found in Algorithms.qs file. 8 | ///////////////////////////////////////////////////////////////////////////////////////////////// 9 | 10 | namespace Quantum.DeutschJozsaAlgorithm { 11 | 12 | open Microsoft.Quantum.Primitive; 13 | open Microsoft.Quantum.Canon; 14 | 15 | // ------------------------------------------------------------------------------------------ 16 | function AssertOracleCallsCount<'T> (count : Int, oracle : 'T) : Unit { } 17 | 18 | // ------------------------------------------------------------------------------------------ 19 | function ResetOracleCallsCount () : Unit { } 20 | 21 | // ------------------------------------------------------------------------------------------ 22 | function ConstantOrBalanced (value : Bool) : String { 23 | return (value ? "constant" | "balanced"); 24 | } 25 | 26 | // ------------------------------------------------------------------------------------------ 27 | operation CheckAlgorithmOnOneTest (N : Int, markingOracle : ((Qubit[], Qubit) => Unit), expected : Bool, extraInfo : String) : Bool { 28 | 29 | ResetOracleCallsCount(); 30 | 31 | // convert marking oracle to phase oracle 32 | let phaseOracle = MarkingToPhaseOracle(markingOracle); 33 | 34 | let actual = DeutschJozsaAlgorithm(N, phaseOracle); 35 | 36 | // check that the return value is correct 37 | if (actual != expected) { 38 | let actualStr = ConstantOrBalanced(actual); 39 | let expectedStr = ConstantOrBalanced(expected); 40 | Message($" {extraInfo}identified as {actualStr} but it is {expectedStr}."); 41 | return false; 42 | } 43 | 44 | // check that the oracle has been called at most once 45 | AssertOracleCallsCount(1, phaseOracle); 46 | return true; 47 | } 48 | 49 | // ------------------------------------------------------------------------------------------ 50 | operation RunAlgorithmOnTests () : Bool { 51 | 52 | // constant functions 53 | Message("Testing f(x) = 0 ..."); 54 | if (not CheckAlgorithmOnOneTest(4, Oracle_Zero, true, "")) { 55 | return false; 56 | } 57 | Message(" Correct!"); 58 | 59 | Message("Testing f(x) = 1 ..."); 60 | if (not CheckAlgorithmOnOneTest(4, Oracle_One, true, "")) { 61 | return false; 62 | } 63 | Message(" Correct!"); 64 | 65 | // balanced functions 66 | Message("Testing f(x) = x_k ..."); 67 | for (k in 0 .. 3) { 68 | if (not CheckAlgorithmOnOneTest(4, Oracle_Kth_Qubit(_, _, k), false, $"f(x) = x_{k} on 4 qubits ")) { 69 | return false; 70 | } 71 | } 72 | Message(" Correct!"); 73 | 74 | Message("Testing f(x) = (1 if x has odd number of 1s, and 0 otherwise) ..."); 75 | for (n in 1 .. 4) { 76 | if (not CheckAlgorithmOnOneTest(n, Oracle_OddNumberOfOnes, false, $"f(x) = (1 if x has odd number of 1s, and 0 otherwise) on {n} qubits ")) { 77 | return false; 78 | } 79 | } 80 | Message(" Correct!"); 81 | 82 | Message("Testing f(x) = scalar product function ..."); 83 | if (not CheckAlgorithmOnOneTest(3, Oracle_ProductFunction(_, _, [1, 0, 1]), false, "f(x) = scalar product function for r = [1, 0, 1] ")) { 84 | return false; 85 | } 86 | if (not CheckAlgorithmOnOneTest(4, Oracle_ProductFunction(_, _, [0, 1, 1, 0]), false, "f(x) = scalar product function for r = [0, 1, 1, 0] ")) { 87 | return false; 88 | } 89 | Message(" Correct!"); 90 | 91 | Message("Testing f(x) = majority function ..."); 92 | if (not CheckAlgorithmOnOneTest(3, Oracle_MajorityFunction, false, "")) { 93 | return false; 94 | } 95 | Message(" Correct!"); 96 | 97 | return true; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /DeutschJozsaAlgorithm/Oracles.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | ///////////////////////////////////////////////////////////////////////////////////////////////// 5 | // This file contains the implementations of the quantum oracles used by Deutsch-Jozsa algorithm. 6 | // You can read more about quantum oracles which implement classical functions 7 | // at https://docs.microsoft.com/en-us/quantum/concepts/oracles. 8 | // 9 | // You do not need to modify anything in this file. 10 | // The algorithm on which you'll be working can be found in Algorithms.qs file. 11 | ///////////////////////////////////////////////////////////////////////////////////////////////// 12 | 13 | namespace Quantum.DeutschJozsaAlgorithm { 14 | 15 | open Microsoft.Quantum.Primitive; 16 | open Microsoft.Quantum.Canon; 17 | 18 | 19 | // ------------------------------------------------------------------------------------------ 20 | // Oracle 1. f(x) = 0 (constant) 21 | operation Oracle_Zero (x : Qubit[], y : Qubit) : Unit { 22 | 23 | body (...) { 24 | // Since f(x) = 0 for all values of x, |y ⊕ f(x)⟩ = |y⟩. 25 | // This means that the operation doesn't need to do any transformation to the inputs. 26 | // Build the project and run the tests to see that T01_Oracle_Zero_Test test passes. 27 | } 28 | 29 | adjoint invert; 30 | } 31 | 32 | 33 | // ------------------------------------------------------------------------------------------ 34 | // Oracle 2. f(x) = 1 (constant) 35 | operation Oracle_One (x : Qubit[], y : Qubit) : Unit { 36 | 37 | body (...) { 38 | // Since f(x) = 1 for all values of x, |y ⊕ f(x)⟩ = |y ⊕ 1⟩ = |NOT y⟩. 39 | // This means that the operation needs to flip qubit y (i.e. transform |0⟩ to |1⟩ and vice versa). 40 | X(y); 41 | } 42 | 43 | adjoint invert; 44 | } 45 | 46 | 47 | // ------------------------------------------------------------------------------------------ 48 | // Oracle 3. f(x) = xₖ (i.e., the value of k-th qubit) (balanced) 49 | operation Oracle_Kth_Qubit (x : Qubit[], y : Qubit, k : Int) : Unit { 50 | 51 | body (...) { 52 | AssertBoolEqual(0 <= k && k < Length(x), true, "k should be between 0 and (number of qubits - 1), inclusive"); 53 | CNOT(x[k], y); 54 | } 55 | 56 | adjoint invert; 57 | } 58 | 59 | 60 | // ------------------------------------------------------------------------------------------ 61 | // Oracle 4. f(x) = 1 if x has odd number of 1s, and 0 otherwise (balanced) 62 | operation Oracle_OddNumberOfOnes (x : Qubit[], y : Qubit) : Unit { 63 | 64 | body (...) { 65 | // f(x) can be represented as x_0 ⊕ x_1 ⊕ ... ⊕ x_(N-1) 66 | for (i in 0 .. Length(x) - 1) { 67 | CNOT(x[i], y); 68 | } 69 | } 70 | 71 | adjoint invert; 72 | } 73 | 74 | 75 | // ------------------------------------------------------------------------------------------ 76 | // Oracle 5. f(x) = Σᵢ 𝑟ᵢ 𝑥ᵢ modulo 2 for a given bit vector r (scalar product function) (balanced) 77 | // Note: oracles 3 and 4 are special cases of this oracle. 78 | operation Oracle_ProductFunction (x : Qubit[], y : Qubit, r : Int[]) : Unit { 79 | 80 | body (...) { 81 | AssertIntEqual(Length(x), Length(r), "Arrays x and r should have the same length"); 82 | 83 | for (i in 0 .. Length(x) - 1) { 84 | if (r[i] == 1) { 85 | CNOT(x[i], y); 86 | } 87 | } 88 | } 89 | 90 | adjoint invert; 91 | } 92 | 93 | 94 | // ------------------------------------------------------------------------------------------ 95 | // Oracle 6. f(x) = 1 if x has two or three bits (out of three) set to 1, and 0 otherwise (majority function) (balanced) 96 | operation Oracle_MajorityFunction (x : Qubit[], y : Qubit) : Unit { 97 | 98 | body (...) { 99 | AssertBoolEqual(3 == Length(x), true, "x should have exactly 3 qubits"); 100 | 101 | // f(x) = (x_0 AND x_1) ⊕ (x_0 AND x_2) ⊕ (x_1 AND x_2) 102 | CCNOT(x[0], x[1], y); 103 | CCNOT(x[0], x[2], y); 104 | CCNOT(x[1], x[2], y); 105 | } 106 | 107 | adjoint invert; 108 | } 109 | 110 | 111 | // ------------------------------------------------------------------------------------------ 112 | // helper functions to convert a marking oracle, as defined above, to a phase oracle, as used in the algorithm 113 | operation MarkingToPhaseOracleImpl (markingOracle : ((Qubit[], Qubit) => Unit), register : Qubit[]) : Unit { 114 | 115 | body (...) { 116 | using (target = Qubit()) { 117 | // Put the target into the |-⟩ state 118 | X(target); 119 | H(target); 120 | 121 | // Apply the marking oracle; since the target is in the |-⟩ state, 122 | // flipping the target if the register satisfies the oracle condition will apply a -1 factor to the state 123 | markingOracle(register, target); 124 | 125 | // Put the target back into |0⟩ so we can return it 126 | H(target); 127 | X(target); 128 | } 129 | } 130 | } 131 | 132 | 133 | function MarkingToPhaseOracle (markingOracle : ((Qubit[], Qubit) => Unit)) : (Qubit[] => Unit) { 134 | return MarkingToPhaseOracleImpl(markingOracle, _); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | _**This tutorial is superseded by [this tutorial on Deutsch-Jozsa algorithm](https://github.com/microsoft/QuantumKatas/tree/master/tutorials/ExploringDeutschJozsaAlgorithm), available online as Jupyter Notebook. We recommend you to use it instead of this tutorial.**_ 4 | 5 | _This repository contains materials for the "Introduction to Quantum Computing" workshop. The first version of the workshop was presented at 2018 Grace Hopper Celebration, the second, improved and updated - at Hopper x1 Seattle. You can also use the materials for self-paced learning, using [the slides from the workshop](./Hopper_Seattle-IntroToQuantumComputing.pptx) and the theory covered in the "Useful Links" section._ 6 | 7 | Quantum computing harnesses the laws of nature to enable new types of algorithms, impossible on traditional computers. They are expected to lead to breakthroughs in crucial areas like material and drug discovery. 8 | 9 | In this workshop the participants will learn where the power of quantum computing comes from in a hands-on quantum programming tutorial. The participants will implement a quantum algorithm in Q# programming language that is exponentially faster than any deterministic classical algorithm for that problem - Deutsch-Jozsa algorithm. 10 | 11 | # Installing and Getting Started 12 | 13 | To work on this tutorial, you'll need to install the [Quantum Development Kit](https://docs.microsoft.com/quantum), available for Windows 10, macOS, and for Linux. 14 | Please see the [install guide for the Quantum Development Kit](https://docs.microsoft.com/quantum/install-guide/) for the detailed instructions. We recommend that you use Visual Studio 2017 or Visual Studio Code to work on the tutorial. 15 | 16 | You can also use [Try It Online](https://tio.run/#qs-core) to work on this tutorial without a local Q# setup, but it has a much worse developer experience (no syntax highlight). The pre-populated project can be accessed at https://aka.ms/GHC18-IntroToQuantumComputing (note that this link works only in Firefox and Chrome). The algorithm template is in the Code section; you can collapse Driver, Header and Footer sections which contain the testing harness for convenience. 17 | 18 | ### Downloading the Tutorial 19 | 20 | If you have Git installed, go on and clone the Microsoft/GHC18-IntroToQuantumComputing repository. From your favorite command line: 21 | 22 | ```bash 23 | git clone https://github.com/Microsoft/GHC18-IntroToQuantumComputing.git 24 | ``` 25 | 26 | > **TIP**: Both Visual Studio 2017 and Visual Studio Code make it easy to clone repositories from within your development environment. 27 | > See the [Visual Studio 2017](https://docs.microsoft.com/en-us/vsts/git/tutorial/clone?view=vsts&tabs=visual-studio#clone-from-another-git-provider) and [Visual Studio Code](https://code.visualstudio.com/docs/editor/versioncontrol#_cloning-a-repository) documentation for details. 28 | 29 | Alternatively, if you don't have Git installed, you can manually download a [standalone copy of the tutorials](https://github.com/Microsoft/GHC18-IntroToQuantumComputing/archive/master.zip). 30 | 31 | # Opening the Tutorial 32 | 33 | The tutorial contains the template of the algorithm which you will work on and the testing harness used for verifying your code. The project is laid out as below. 34 | 35 | ``` 36 | README.md # Tutorial instructions and useful links. 37 | DeutschJozsaAlgorithm/ 38 | DeutschJozsaAlgorithm.sln # Visual Studio 2017 solution file. 39 | DeutschJozsaAlgorithm.csproj # Project file used to build both classical and quantum code. 40 | 41 | Algorithm.qs # Q# source code containing the template of the algorithm. 42 | Oracles.qs # Q# source code containing implementations of quantum oracles used for testing your implementation of the algorithm. 43 | Tests.qs # Q# tests that verify your implementation of the algorithm. 44 | Driver.cs # C# source code used to invoke the Q# tests. 45 | OracleCounterSimulator.cs # C# source code used to verify that your implementation of the algorithm calls the oracle exactly once. 46 | ``` 47 | 48 | To open the tutorial in Visual Studio 2017, open the `DeutschJozsaAlgorithm.sln` solution file. 49 | 50 | To open the tutorial in Visual Studio Code, open the `DeutschJozsaAlgorithm/` folder. 51 | Press Ctrl + Shift + P / ⌘ + Shift + P to open the Command Palette and type "Open Folder" on Windows 10 or Linux or "Open" on macOS. 52 | 53 | > **TIP**: Almost all commands available in Visual Studio Code can be found in the Command Palette. 54 | > If you ever get stuck, press Ctrl + Shfit + P / ⌘ + Shift + P and type some letters to search through all available commands. 55 | 56 | > **TIP**: You can also launch Visual Studio Code from the command line if you prefer: 57 | > ```bash 58 | > code DeutschJozsaAlgorithm/ 59 | > ``` 60 | 61 | 62 | # Working on the Tutorial 63 | 64 | Once you have the project open, you can try building it and running it. The test harness calls your implementation of the algorithm on a set of function. Initially the algorithm always classifies the function as constant, so the first two tests will pass and the third one will fail. You will see something like this: 65 | 66 | Testing f(x) = 0 ... 67 | Correct! 68 | Testing f(x) = 1 ... 69 | Correct! 70 | Testing f(x) = x_k ... 71 | f(x) = x_0 on 4 qubits identified as constant but it is balanced. 72 | 73 | Deutsch-Jozsa algorithm is incorrect :-( 74 | 75 | Once you fill in the correct code in `Algorithm.qs`, the tests should pass. You can rebuild and rerun the tests as often as you wish. 76 | 77 | ### Visual Studio 2017 78 | 79 | 1. Build and run the project (Ctrl + F5). 80 | 2. Work on the code in the `Algorithms.qs` file. 81 | 3. To test your implementation, rebuild the project and run it again. 82 | 83 | ### Visual Studio Code 84 | 85 | 1. Press Ctrl + \` / ⌘ + \` to open the integrated terminal. 86 | The terminal should already start in the project directory, but if not, use `cd` to navigate to the folder containing the `DeutschJozsaAlgorithm.csproj` file. 87 | 2. Run `dotnet run` in the integrated terminal. 88 | This should automatically build the project and run it. 89 | 3. Work on the code in the `Algorithms.qs` file. 90 | 4. To test your implementation, run `dotnet run` again. 91 | 92 | ### Try It Online 93 | 94 | 1. Press Ctrl + Enter to build and run the project. The spinning gear on the top of the window indicates that the project is in the process of building. 95 | 2. Work on the code in the Code section. 96 | 3. To test your implementation, rebuild the project again. 97 | 98 | # Useful Information 99 | 100 | ### Deutsch-Jozsa Algorithm 101 | 102 | This algorithm solves the following problem: you are given a black box (an oracle) that implements a function f: {0, 1}n -> {0, 1} (i.e. a function that takes n-bit binary string as input and produces 0 or 1 as output). You are guaranteed that the function is either constant (i.e. returns 0 on all inputs or 1 on all inputs) or balanced (i.e. returns 0 for exactly half of all inputs and 1 for the other half of the inputs). You have to determine whether the function is constant or balanced. 103 | 104 | A deterministic classical algorithm for this problem requires 2n-1 + 1 evaluations of function f in the worst case. The Deutsch-Jozsa quantum algorithm always produces the correct answer using a single evaluation of f. 105 | 106 | This algorithm not only demonstrates a profound separation between quantum and classical computing but also illustrates the fundamental properties of quantum algorithms: 107 | * Quantum parallelism allows a quantum computer to evaluate a function f(x) for multiple different values of x simultaneously. 108 | * Due to the properties of measurement this evaluation is not immediately useful, because there is no way to read all the values f(x) at once. 109 | * Quantum interference combines the calculated values of f(x) in a clever way to determine some global property of function f without measuring all individual values. 110 | 111 | We will describe the Deutsch-Jozsa algorithm in the first part of the workshop, so we are not giving the full description here. If you want to study this topic in a self-paced manner, here are several nice descriptions of the algorithm: 112 | 113 | * [Wikipedia article](https://en.wikipedia.org/wiki/Deutsch%E2%80%93Jozsa_algorithm). 114 | * Nielsen, M. A. & Chuang, I. L. (2010). Quantum Computation and Quantum Information. pp. 34-36. 115 | * [Lecture 5: A simple searching algorithm; the Deutsch-Jozsa algorithm](https://cs.uwaterloo.ca/%7Ewatrous/CPSC519/LectureNotes/05.pdf). 116 | 117 | 118 | ### Q# 119 | 120 | * A quick reference sheet for Q# programming language is available [here](./quickref/qsharp-quick-reference.pdf). 121 | * Full Q# documentation is available [here](https://docs.microsoft.com/en-us/quantum/). 122 | 123 | 124 | ### FAQ 125 | 126 | Here are several common mistakes that people do when going through this tutorial. 127 | 128 | `Q.` What does `ReleasedQubitsAreNotInZeroState` exception mean? 129 | 130 | `A.` The compiler requires that all qubits are in the |0⟩ state immediately before deallocation, so that they can be reused and offered to other `using` blocks for allocation. Remember to reset qubits you've allocated to the |0⟩ state in the end of the algorithm; you can use the library function `ResetAll` for doing this. 131 | 132 | `Q.` What does `ReturnStatement in a statement that cannot have a return value` compilation error mean? 133 | 134 | `A.` The compiler doesn't allow a `return` statement inside a loop. You have to define a variable outside of the loop which holds your return value and update it in the loop. 135 | 136 | ### Further Reading 137 | 138 | We hope you found this tutorial interesting and educational! If you want to learn more about quantum computing and Q# programming, check out [the Quantum Katas](https://github.com/Microsoft/QuantumKatas) project, which contains more tutorials of similar structure. 139 | 140 | # Contributing 141 | 142 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 143 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 144 | the rights to use your contribution. For details, visit https://cla.microsoft.com. 145 | 146 | When you submit a pull request, a CLA-bot will automatically determine whether you need to provide 147 | a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions 148 | provided by the bot. You will only need to do this once across all repos using our CLA. 149 | 150 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 151 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 152 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 153 | --------------------------------------------------------------------------------