├── .devcontainer └── devcontainer.json ├── .github └── workflows │ └── Build.yml ├── .gitignore ├── AlgorithmZoo.sln ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── environment.yml └── src └── qsharp ├── bernstein-vazirani ├── bernstein-vazirani.csproj └── bernstein-vazirani.qs ├── factoring ├── factoring.csproj └── factoring.qs └── searching ├── searching.csproj └── searching.qs /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "dockerFile": "../Dockerfile", 3 | "extensions": [ 4 | "quantum.quantum-devkit-vscode", 5 | "ms-vscode.csharp", 6 | "editorconfig.editorconfig", 7 | "ms-python.python", 8 | "ms-dotnettools.csharp" 9 | ], 10 | "remoteEnv": { 11 | "IQSHARP_HOSTING_ENV": "QAZOO_DEVCONTAINER" 12 | } 13 | } -------------------------------------------------------------------------------- /.github/workflows/Build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: 3 | workflow_dispatch: 4 | pull_request: 5 | branches: [ master ] 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: .NET build 12 | run: dotnet build 13 | working-directory: . 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python temporary files 2 | .ipynb_checkpoints 3 | .pytest_cache 4 | 5 | # Git ignore file for the Solid project 6 | 7 | # Build artifacts 8 | *.g.cs 9 | bin/ 10 | obj/ 11 | Documentation/Help/ 12 | packages/ 13 | *.obj 14 | *.dll 15 | *.pdb 16 | *.exe 17 | *.chm 18 | 19 | # test outputs 20 | TestResults/ 21 | *.qxe 22 | 23 | # Random VS files 24 | *.suo 25 | *.vssscc 26 | *.vspscc 27 | UpgradeLog.htm 28 | 29 | # Random non-solution files 30 | ~$Solid.docx 31 | 32 | ## Ignore Visual Studio temporary files, build results, and 33 | ## files generated by popular Visual Studio add-ons. 34 | ## 35 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 36 | 37 | # User-specific files 38 | *.suo 39 | *.user 40 | *.userosscache 41 | *.sln.docstates 42 | 43 | # User-specific files (MonoDevelop/Xamarin Studio) 44 | *.userprefs 45 | 46 | # Build results 47 | [Dd]ebug/ 48 | [Dd]ebugPublic/ 49 | [Rr]elease/ 50 | [Rr]eleases/ 51 | x64/ 52 | x86/ 53 | bld/ 54 | [Bb]in/ 55 | [Oo]bj/ 56 | [Ll]og/ 57 | 58 | # Visual Studio 2015 cache/options directory 59 | .vs/ 60 | # Uncomment if you have tasks that create the project's static files in wwwroot 61 | #wwwroot/ 62 | 63 | # MSTest test Results 64 | [Tt]est[Rr]esult*/ 65 | [Bb]uild[Ll]og.* 66 | 67 | # NUNIT 68 | *.VisualState.xml 69 | TestResult.xml 70 | 71 | # Build Results of an ATL Project 72 | [Dd]ebugPS/ 73 | [Rr]eleasePS/ 74 | dlldata.c 75 | 76 | # Benchmark Results 77 | BenchmarkDotNet.Artifacts/ 78 | 79 | # .NET Core 80 | project.lock.json 81 | project.fragment.lock.json 82 | artifacts/ 83 | **/Properties/launchSettings.json 84 | 85 | *_i.c 86 | *_p.c 87 | *_i.h 88 | *.ilk 89 | *.meta 90 | *.obj 91 | *.pch 92 | *.pdb 93 | *.pgc 94 | *.pgd 95 | *.rsp 96 | *.sbr 97 | *.tlb 98 | *.tli 99 | *.tlh 100 | *.tmp 101 | *.tmp_proj 102 | *.log 103 | *.vspscc 104 | *.vssscc 105 | .builds 106 | *.pidb 107 | *.svclog 108 | *.scc 109 | 110 | # Chutzpah Test files 111 | _Chutzpah* 112 | 113 | # Visual C++ cache files 114 | ipch/ 115 | *.aps 116 | *.ncb 117 | *.opendb 118 | *.opensdf 119 | *.sdf 120 | *.cachefile 121 | *.VC.db 122 | *.VC.VC.opendb 123 | 124 | # Visual Studio profiler 125 | *.psess 126 | *.vsp 127 | *.vspx 128 | *.sap 129 | 130 | # TFS 2012 Local Workspace 131 | $tf/ 132 | 133 | # Guidance Automation Toolkit 134 | *.gpState 135 | 136 | # ReSharper is a .NET coding add-in 137 | _ReSharper*/ 138 | *.[Rr]e[Ss]harper 139 | *.DotSettings.user 140 | 141 | # JustCode is a .NET coding add-in 142 | .JustCode 143 | 144 | # TeamCity is a build add-in 145 | _TeamCity* 146 | 147 | # DotCover is a Code Coverage Tool 148 | *.dotCover 149 | 150 | # AxoCover is a Code Coverage Tool 151 | .axoCover/* 152 | !.axoCover/settings.json 153 | 154 | # Visual Studio code coverage results 155 | *.coverage 156 | *.coveragexml 157 | 158 | # NCrunch 159 | _NCrunch_* 160 | .*crunch*.local.xml 161 | nCrunchTemp_* 162 | 163 | # MightyMoose 164 | *.mm.* 165 | AutoTest.Net/ 166 | 167 | # Web workbench (sass) 168 | .sass-cache/ 169 | 170 | # Installshield output folder 171 | [Ee]xpress/ 172 | 173 | # DocProject is a documentation generator add-in 174 | DocProject/buildhelp/ 175 | DocProject/Help/*.HxT 176 | DocProject/Help/*.HxC 177 | DocProject/Help/*.hhc 178 | DocProject/Help/*.hhk 179 | DocProject/Help/*.hhp 180 | DocProject/Help/Html2 181 | DocProject/Help/html 182 | 183 | # Click-Once directory 184 | publish/ 185 | 186 | # Publish Web Output 187 | *.[Pp]ublish.xml 188 | *.azurePubxml 189 | # Note: Comment the next line if you want to checkin your web deploy settings, 190 | # but database connection strings (with potential passwords) will be unencrypted 191 | *.pubxml 192 | *.publishproj 193 | 194 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 195 | # checkin your Azure Web App publish settings, but sensitive information contained 196 | # in these scripts will be unencrypted 197 | PublishScripts/ 198 | 199 | # NuGet Packages 200 | *.nupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/packages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/packages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/packages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Since there are multiple workflows, uncomment next line to ignore bower_components 244 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 245 | #bower_components/ 246 | 247 | # RIA/Silverlight projects 248 | Generated_Code/ 249 | 250 | # Backup & report files from converting an old project file 251 | # to a newer Visual Studio version. Backup files are not needed, 252 | # because we have git ;-) 253 | _UpgradeReport_Files/ 254 | Backup*/ 255 | UpgradeLog*.XML 256 | UpgradeLog*.htm 257 | 258 | # SQL Server files 259 | *.mdf 260 | *.ldf 261 | *.ndf 262 | 263 | # Business Intelligence projects 264 | *.rdl.data 265 | *.bim.layout 266 | *.bim_*.settings 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Typescript v1 declaration files 279 | typings/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # JetBrains Rider 306 | .idea/ 307 | *.sln.iml 308 | 309 | # CodeRush 310 | .cr/ 311 | 312 | # Python Tools for Visual Studio (PTVS) 313 | __pycache__/ 314 | *.pyc 315 | 316 | # Cake - Uncomment if you are using it 317 | # tools/** 318 | # !tools/packages.config 319 | 320 | # Tabs Studio 321 | *.tss 322 | 323 | # Telerik's JustMock configuration file 324 | *.jmconfig 325 | 326 | # BizTalk build output 327 | *.btp.cs 328 | *.btm.cs 329 | *.odx.cs 330 | *.xsd.cs 331 | 332 | # Really random 333 | *.ionide 334 | 335 | ## Core latex/pdflatex auxiliary files: 336 | *.aux 337 | *.lof 338 | *.log 339 | *.lot 340 | *.fls 341 | *.out 342 | *.toc 343 | *.fmt 344 | *.fot 345 | *.cb 346 | *.cb2 347 | .*.lb 348 | 349 | ## Build tool auxiliary files: 350 | *.fdb_latexmk 351 | *.synctex 352 | *.synctex(busy) 353 | *.synctex.gz 354 | *.synctex.gz(busy) 355 | *.pdfsync 356 | 357 | ## Intermediate documents: 358 | *.dvi 359 | *.xdv 360 | *-converted-to.* 361 | # these rules might exclude image files for figures etc. 362 | # *.ps 363 | # *.eps 364 | # Allow PDFs in fig/. 365 | !fig/*.pdf 366 | 367 | ## Bibliography auxiliary files (bibtex/biblatex/biber): 368 | *.bbl 369 | *.bcf 370 | *.blg 371 | *-blx.aux 372 | *-blx.bib 373 | *.run.xml 374 | *Notes.bib 375 | 376 | ## Images 377 | *.png 378 | *.svg 379 | -------------------------------------------------------------------------------- /AlgorithmZoo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31521.260 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bernstein-vazirani", "src\qsharp\bernstein-vazirani\bernstein-vazirani.csproj", "{11C7B1CB-EE4F-44E7-B37A-4C30057C0C20}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "factoring", "src\qsharp\factoring\factoring.csproj", "{E0DF621D-27EF-4611-BAA8-4DF0BDC64144}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "searching", "src\qsharp\searching\searching.csproj", "{E1B97B73-E2B1-4E5A-8065-F93599EA6754}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D9631C98-007F-4A0C-8B2D-180F349F8D40}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {11C7B1CB-EE4F-44E7-B37A-4C30057C0C20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {11C7B1CB-EE4F-44E7-B37A-4C30057C0C20}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {11C7B1CB-EE4F-44E7-B37A-4C30057C0C20}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {11C7B1CB-EE4F-44E7-B37A-4C30057C0C20}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {E0DF621D-27EF-4611-BAA8-4DF0BDC64144}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {E0DF621D-27EF-4611-BAA8-4DF0BDC64144}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {E0DF621D-27EF-4611-BAA8-4DF0BDC64144}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {E0DF621D-27EF-4611-BAA8-4DF0BDC64144}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {E1B97B73-E2B1-4E5A-8065-F93599EA6754}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {E1B97B73-E2B1-4E5A-8065-F93599EA6754}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {E1B97B73-E2B1-4E5A-8065-F93599EA6754}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {E1B97B73-E2B1-4E5A-8065-F93599EA6754}.Release|Any CPU.Build.0 = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(SolutionProperties) = preSolution 34 | HideSolutionNode = FALSE 35 | EndGlobalSection 36 | GlobalSection(NestedProjects) = preSolution 37 | {11C7B1CB-EE4F-44E7-B37A-4C30057C0C20} = {D9631C98-007F-4A0C-8B2D-180F349F8D40} 38 | {E0DF621D-27EF-4611-BAA8-4DF0BDC64144} = {D9631C98-007F-4A0C-8B2D-180F349F8D40} 39 | {E1B97B73-E2B1-4E5A-8065-F93599EA6754} = {D9631C98-007F-4A0C-8B2D-180F349F8D40} 40 | EndGlobalSection 41 | GlobalSection(ExtensibilityGlobals) = postSolution 42 | SolutionGuid = {F86B2E51-3C9A-43FA-A8B2-AD115487FC0B} 43 | EndGlobalSection 44 | EndGlobal 45 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at sckaiser@sckaiser.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a [code of conduct](CODE_OF_CONDUCT.md), please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a build. 11 | 2. Update the README.md with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters. 12 | 3. Increase the version numbers in any examples files and the README.md to the new version that this 13 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 14 | 4. You may merge the Pull Request in once you have the sign-off of at least one other developers, or if you do not have permission to do that, you may request the reviewer to merge it for you. 15 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/quantum/iqsharp-base:0.12.20092803 2 | 3 | ENV IQSHARP_HOSTING_ENV=QAZOO_DOCKER 4 | USER root 5 | RUN pip install RISE 6 | 7 | # Make sure the contents of our repo are in ${HOME}. 8 | # These steps are required for use on mybinder.org. 9 | COPY . ${HOME} 10 | RUN chown -R ${USER} ${HOME} 11 | 12 | # Drop back down to user permissions for things that don't need it. 13 | USER ${USER} 14 | 15 | RUN pip install numpy matplotlib 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Q# Community 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # algorithm-zoo 2 | Implementations of algorithms from http://quantumalgorithmzoo.org/ 3 | 4 | ## Index 5 | 6 | | Algorithm | Speedup | Implementations | | 7 | |--------------------|--------------------------------------------------|--------------------------------------|--| 8 | | Factoring | Superpolynomial | [Q#](/src/qsharp/factoring) | | 9 | | Bernstein-Vazirani | Polynomial Directly, Superpolynomial Recursively | [Q#](/src/qsharp/bernstein-vazirani) | | 10 | | Searching | Polynomial | [Q#](/src/qsharp/searching) | | 11 | | | | | | 12 | 13 | 14 | ## TODOs: 15 | - [ ] Add doc strings -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: qsharpcommunity-zoo 2 | channels: 3 | - conda-forge 4 | - quantum-engineering 5 | dependencies: 6 | - notebook 7 | - numpy 8 | - ipykernel 9 | - qsharp==0.12.20092803 10 | - pip 11 | - matplotlib 12 | - pip: 13 | - RISE -------------------------------------------------------------------------------- /src/qsharp/bernstein-vazirani/bernstein-vazirani.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/qsharp/bernstein-vazirani/bernstein-vazirani.qs: -------------------------------------------------------------------------------- 1 | namespace BernsteinVazirani { 2 | open Microsoft.Quantum.Convert; 3 | open Microsoft.Quantum.Math; 4 | open Microsoft.Quantum.Intrinsic; 5 | open Microsoft.Quantum.Canon; 6 | open Microsoft.Quantum.Diagnostics; 7 | open Microsoft.Quantum.Arithmetic; 8 | open Microsoft.Quantum.Arrays; 9 | 10 | 11 | @EntryPoint() 12 | operation RunBernsteinVazirani(secret : Int, nQubits : Int) 13 | : Int { 14 | let oracle = DotProductOracle(secret); 15 | return ApplyBernsteinVazirani(oracle, nQubits); 16 | } 17 | 18 | operation ApplyBernsteinVazirani( 19 | oracle : ((Qubit[],Qubit) => Unit is Adj + Ctl), 20 | n : Int 21 | ) : Int { 22 | use queryRegister = Qubit[n]; 23 | use target = Qubit(); 24 | within { 25 | ApplyToEachCA(H, queryRegister); 26 | X(target); 27 | H(target); 28 | //After these steps the registers are: |+++++..++>|-> 29 | } apply { 30 | oracle(queryRegister, target); 31 | } 32 | return MeasureInteger(LittleEndian(queryRegister)); 33 | } 34 | 35 | operation ApplyDotProductOracle(s : Int, x : Qubit[], target : Qubit) 36 | : Unit is Adj + Ctl { 37 | Fact(Length(x)>=BitSizeI(s), "The query register is not big enough to hold the secret."); 38 | 39 | let secretString = IntAsBoolArray(s, Length(x)); 40 | ApplyToEachCA(CControlledCA(CNOT(_,target)), Zipped(secretString, x)); 41 | } 42 | 43 | function DotProductOracle(s : Int) : ((Qubit[],Qubit) => Unit is Adj + Ctl) { 44 | return ApplyDotProductOracle(s, _, _); 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/qsharp/factoring/factoring.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/qsharp/factoring/factoring.qs: -------------------------------------------------------------------------------- 1 | namespace Factoring { 2 | open Microsoft.Quantum.Intrinsic; 3 | open Microsoft.Quantum.Canon; 4 | open Microsoft.Quantum.Math; 5 | open Microsoft.Quantum.Convert; 6 | open Microsoft.Quantum.Arithmetic; 7 | open Microsoft.Quantum.Arrays; 8 | open Microsoft.Quantum.Random; 9 | open Microsoft.Quantum.Characterization; 10 | open Microsoft.Quantum.Oracles; 11 | open Microsoft.Quantum.Diagnostics; 12 | 13 | @EntryPoint() 14 | operation FactorSemiprimeInteger(number : Int) : (Int, Int) 15 | { 16 | if (number % 2 == 0) { 17 | Message("An even number has been provided, 2 is a factor."); 18 | return (number/2, 2); 19 | } 20 | 21 | mutable factors = (1, 1); 22 | mutable foundFactors = false; 23 | 24 | repeat { 25 | let a = DrawRandomInt(3, number-1); 26 | if (IsCoprimeI(a, number)){ 27 | let r = EstimatePeriod(a, number); 28 | set (foundFactors, factors) = MaybeFactorsFromPeriod(a, r, number); 29 | } else { 30 | let gcd = GreatestCommonDivisorI(a, number); 31 | Message($"We did it by accident, {gcd} is a factor of {number}."); 32 | set foundFactors = true; 33 | set factors = (gcd, number/gcd); 34 | } 35 | } until (foundFactors) 36 | fixup { 37 | Message("Current guess failed, trying again."); 38 | } 39 | 40 | return factors; 41 | } 42 | 43 | // 3. Use iterative phase estimation to find the frequency of the classical 44 | // function f(x) = ax mod N. The frequency tells you about how quickly f 45 | // returns to the same value as x increases. 46 | // 4. Use a classical algorithm known as the continued fractions expansion to 47 | // convert the frequency from the previous step into a period (r). 48 | // The period r should then have the property that f(x) = f(x + r) for all inputs x. 49 | 50 | operation EstimatePeriod(a : Int, number : Int) : Int { 51 | let bitSize = BitSizeI(number); 52 | let nBitsPrecision = 2 * bitSize + 1; 53 | // Values selected below make sure that default conditions for the loop 54 | // are ok. 55 | mutable result = 1; 56 | mutable frequencyEstimate = 0; 57 | 58 | repeat{ 59 | // QUANTUM PART START 60 | set frequencyEstimate = EstimateFrequency(nBitsPrecision,bitSize, ApplyPeriodFindingOracle(a, _, number, _)); 61 | // QUANTUM PART END 62 | if (frequencyEstimate != 0){ 63 | set result = PeriodFromFrequency(frequencyEstimate,nBitsPrecision, number, result); 64 | } else { 65 | Message("Estimated 0 as the frequency, trying again."); 66 | } 67 | 68 | } until (ExpModI(a, result, number) == 1) 69 | fixup{ 70 | Message("So sorry eh, trying period estimation again."); 71 | } 72 | return result; 73 | } 74 | 75 | function PeriodFromFrequency( 76 | frequencyEstimate : Int, 77 | nBitsPrecision : Int, 78 | number : Int, 79 | result : Int 80 | ) : Int { 81 | let continuedFraction = ContinuedFractionConvergentI( 82 | Fraction(frequencyEstimate, 2^nBitsPrecision), 2^nBitsPrecision 83 | ); 84 | let denominator = AbsI(continuedFraction::Denominator); 85 | return ((denominator * result) / GreatestCommonDivisorI(result, denominator)); 86 | } 87 | 88 | operation EstimateFrequency( 89 | nBitsPrecision : Int, 90 | bitSize : Int, 91 | oracle : ((Int, Qubit[]) => Unit is Adj+Ctl) 92 | ) : Int { 93 | use register = Qubit[bitSize]; 94 | 95 | let registerLE = LittleEndian(register); 96 | ApplyXorInPlace(1, registerLE); 97 | 98 | let phase = RobustPhaseEstimation( 99 | nBitsPrecision, 100 | DiscreteOracle(oracle), 101 | registerLE! 102 | ); 103 | ResetAll(register); 104 | 105 | return Round((phase * IntAsDouble(2 ^ nBitsPrecision))/(2.0 * PI())); 106 | } 107 | 108 | operation ApplyPeriodFindingOracle( 109 | a : Int, x : Int, number :Int, register : Qubit[] 110 | ) : Unit is Adj + Ctl { 111 | Fact(IsCoprimeI(a, number), "Must be co-prime to modulus."); 112 | MultiplyByModularInteger( 113 | ExpModI(a, x, number), 114 | number, 115 | LittleEndian(register) 116 | ); 117 | } 118 | 119 | function MaybeFactorsFromPeriod(a : Int, r : Int, number : Int 120 | ) : (Bool, (Int, Int)) { 121 | if (r % 2 == 0) { 122 | 123 | let halfPower = ExpModI(a, r/2, number); 124 | if (halfPower != number - 1){ 125 | let factor = MaxI( 126 | GreatestCommonDivisorI(halfPower + 1, number), 127 | GreatestCommonDivisorI(halfPower - 1, number) 128 | ); 129 | return (true, (factor, number/factor)); 130 | 131 | } else { 132 | return (false, (1, 1)); 133 | } 134 | 135 | } else { 136 | return (false, (1, 1)); 137 | } 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /src/qsharp/searching/searching.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/qsharp/searching/searching.qs: -------------------------------------------------------------------------------- 1 | namespace Searching { 2 | open Microsoft.Quantum.Intrinsic; 3 | open Microsoft.Quantum.Canon; 4 | open Microsoft.Quantum.Math; 5 | open Microsoft.Quantum.Convert; 6 | open Microsoft.Quantum.Arithmetic; 7 | open Microsoft.Quantum.Arrays; 8 | 9 | // Note: this is Grover's algorithm 10 | 11 | @EntryPoint() 12 | operation RunGroverSearch(nItem : Int, markedItem : Int) : Int { 13 | let markedOracle = ApplyOracle(markedItem, _, _); 14 | let foundItem = SearchForMarked(markedOracle, nItem); 15 | Message($"Marked : {markedItem}, Found : {foundItem}"); 16 | return foundItem; 17 | } 18 | 19 | operation ApplyOracle( 20 | markedItem : Int, 21 | inputRegister : Qubit[], 22 | outputRegister : Qubit 23 | ) : Unit is Adj + Ctl 24 | { 25 | (ControlledOnInt(markedItem, X))(inputRegister, outputRegister); 26 | } 27 | 28 | operation SearchForMarked( 29 | oracle : ((Qubit[], Qubit) => Unit is Adj), 30 | nItems : Int 31 | ) : Int { 32 | use inputRegister = Qubit[BitSizeI(nItems)]; 33 | ApplyToEach(H, inputRegister); 34 | for n in 0..nIterations(BitSizeI(nItems)) - 1 { 35 | ReflectAboutMarked(oracle, inputRegister); 36 | ReflectAboutUniform(inputRegister); 37 | } 38 | return MeasureInteger(LittleEndian(inputRegister)); 39 | } 40 | 41 | operation PrepareAllOnes(register : Qubit[]) : Unit 42 | is Adj + Ctl { 43 | ApplyToEachCA(X, register); 44 | } 45 | 46 | operation ReflectAboutAllOnes(register : Qubit[]) : Unit 47 | is Adj + Ctl { 48 | Controlled Z(Most(register), Tail(register)); 49 | } 50 | 51 | operation ReflectAboutUniform(register : Qubit[]) : Unit 52 | is Adj + Ctl { 53 | within { 54 | Adjoint ApplyToEachCA(H, register); 55 | PrepareAllOnes(register); 56 | } apply { 57 | ReflectAboutAllOnes(register); 58 | } 59 | } 60 | 61 | operation ReflectAboutMarked( 62 | oracle : ((Qubit[], Qubit) => Unit is Adj), 63 | register : Qubit[] 64 | ) : Unit is Adj { 65 | use output = Qubit(); 66 | within { 67 | X(output); 68 | H(output); 69 | } apply { 70 | oracle(register, output); 71 | } 72 | } 73 | 74 | function nIterations(nQubits : Int) : Int { 75 | let nItems = 1 <<< nQubits; 76 | let angle = ArcSin(1. / Sqrt(IntAsDouble(nItems))); 77 | let total = Round(0.25 * PI() / angle - 0.5); 78 | return total; 79 | } 80 | } 81 | --------------------------------------------------------------------------------