In this article we will write a Q# program, Hello world level.
I don't know much about quantum theory. Colleagues don't know much about Q# either. So this article won't study how the program works, just look at the results, showing the capabilities of Q#.
Open VS 2017 which has extended Q# capabilities. Create a new project and select Q# Application under C#. Call it Bell.
VS will help us create an Operation.cs file and a Driver.qs file.
Operation, operation, is similar to static methods in C# and java.
Right-click the qs file and rename it Bell.qs.
Open Bell.qs and change the operation name Operation to Set. And add two parameters: desired: Result, q1: Qubit.
namespace Quantum.Bell { open Microsoft.Quantum.Primitive; operation Set (desired: Result, q1: Qubit) : () { body { } } }
Write the following code in the operator body
let current = M(q1); if (desired != current) { X(q1); }
The input and output of Q# are tuples, which are zero or more parameters enclosed in parentheses. Its parameter types and method return values are postfix, similar to some other languages.
In addition to the body block, the operation can also have an adjoint block, a controlled block, and a controlled adjoint block. Useless here.
Next, add another operation to the level of Set:
operation BellTest (count : Int, initial: Result) : (Int,Int) { body { mutable numOnes = 0; using (qubits = Qubit[1]) { for (test in 1..count) { Set (initial, qubits[0]); let res = M (qubits[0]); // Count the number of ones we saw: if (res == One) { set numOnes = numOnes + 1; } } Set(Zero, qubits[0]); } // Return number of times we saw a |0> and number of times we saw a |1> return (count-numOnes, numOnes); } }
In this way, the code of Q# is written.
Then go to write C# driver.
Open Driver.cs and write in the Main method
using (var sim = new QuantumSimulator()) { // Try initial values Result[] initials = new Result[] { Result.Zero, Result.One }; foreach (Result initial in initials) { var res = BellTest.Run(sim, 1000, initial).Result; var (numZeros, numOnes) = res; System.Console.WriteLine( $"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4}"); } } System.Console.WriteLine("Press any key to continue..."); System.Console.ReadKey();
Now you can build, just hit F5.
If the output is as follows
Init:Zero 0s=1000 1s=0
Init:One 0s=0 1s=1000
Press any key to continue...
If you add the X method before the M method in the BellTest operation, the result will be the opposite:
X(qubits[0]); let res = M (qubits[0]);
If the X method is changed to the H method (Hadma Gate), the result will be different
Init:Zero 0s=484 1s=516 Init:One 0s=522 1s=478
This is the legendary quantum superposition!
For more information on quantum gate operations, you can simply Baidu: https://baike.baidu.com/item/%E9%87%8F%E5%AD%90%E9%97%A8/12646873?fr=aladdin