page_type: sample languages:
- qsharp products:
- qdk description: "This sample uses Q# to factor integers with Shor's algorithm." urlFragment: integer-factorization
This sample contains Q# code implementing Shor's quantum algorithm for factoring integers. It uses the sparse simulator to simulate the algorithm for instances that require many qubits.
- The Microsoft Quantum Development Kit.
This sample can be run in a number of different ways, depending on your preferred environment.
At a terminal, run the following command:
dotnet run -- simulate
To provide a number to be factored, run the command:
dotnet run -- simulate -n 15
Open the folder containing this sample, right click on IntegerFactorization.csproj
and select "Open in Visual Studio 2022".
Once Visual Studio has opened, ensure the IntegerFactorization
sample is selected, and press Start in Visual Studio to run the sample.
- Shor.qs: Q# implementation of Shor's algorithm.
- Modular.qs: Q# implementation of modular arithmetic.
- Compare.qs: Q# implementation of comparison based on AND-gates.
- Utils.qs: Q# implementation of helper functions and operations for the AND-gate based arithmetic used in this sample.
- Program.cs: C# console application for running Shor's algorithm
- IntegerFactorization.csproj: Main C# project for the sample.
This sample also contains an adapter for the ResourcesEstimator allowing it to produce a resource utilization stack trace which can then be used to produce a flame graph. More details can be found in this article.
To generate a flame graph, follow these steps:
- Download the flamegraph.pl script
- Install Perl
- Run program with the
visualize
command by specifying the generator and the resource (more information in the help text) to be visualized. Save the output in a file. - Use flamegraph.pl with the above file to generate an svg of the flame graph.
Example usage:
dotnet run -- visualize -g 4 -r 0 > output.txt
perl flamegraph.pl output.txt > output.svg
- FlameGraphCounter.cs: Counter for the adapted resources estimator.
- FlameGraphResourcesEstimator.cs: The adapted resources estimator.
This sample also contains a custom ResourcesEstimator that generates JSON code to be used with quantum-viz.js. This contains both the hierarchy of the implementation as well as the resources with respect to the position in the call stack.
To generate the JSON output for quantum-viz.js, run, for example:
dotnet run -- visualize -g 4 -r 0 --quantum-viz
The output would be as follows:
- QuantumVizCounter.cs: Custom listener for quantum-viz.js code generation.
- QuantumVizEstimator.cs: Custom resources estimator that uses the custom listener.