|
2 | 2 | import random |
3 | 3 | import string |
4 | 4 | import time |
| 5 | +from math import ceil, log |
5 | 6 | from configparser import RawConfigParser |
6 | | -from qiskit import qiskit, Aer, IBMQ |
| 7 | +from qiskit import qiskit, Aer, IBMQ, QuantumCircuit |
7 | 8 |
|
8 | | -def generate(n): |
| 9 | +def random_letters(n): |
9 | 10 | # Generate an array of random letters. |
10 | 11 | letters = [] |
11 | 12 | for i in range(n): |
12 | 13 | letters.append(random.choice(string.ascii_letters)) |
13 | 14 | return letters |
14 | 15 |
|
| 16 | +def random_number(minimum, maximum): |
| 17 | + # Uses a quantum circuit to generate a random number from minimum (inclusive) to maximum (exclusive). |
| 18 | + # Determine the number of qubits required. |
| 19 | + n = num_qubits(maximum-1) |
| 20 | + |
| 21 | + # Create a quantum circuit with enough qubits for the max value. |
| 22 | + qc = QuantumCircuit(n) |
| 23 | + |
| 24 | + # Place all qubits into superposition. |
| 25 | + qc.h(range(n)) |
| 26 | + |
| 27 | + # Measure the result. |
| 28 | + qc.measure_all() |
| 29 | + |
| 30 | + # Continue executing the circuit until we obtain a value within range. |
| 31 | + r = -1 |
| 32 | + count = 0 |
| 33 | + max_count = 10 |
| 34 | + while (r < minimum or r >= maximum) and count < max_count: |
| 35 | + # Execute the circuit. |
| 36 | + result = execute(qc) |
| 37 | + |
| 38 | + # Get the resulting hit counts. |
| 39 | + counts = result.get_counts() |
| 40 | + |
| 41 | + # Find the most frequent hit count. |
| 42 | + key = max(counts, key=counts.get) |
| 43 | + |
| 44 | + # Since the quantum computer returns a binary string (one bit for each qubit), we need to convert it to an integer. |
| 45 | + r = int(key, 2) |
| 46 | + |
| 47 | + # Increment the count before we break. |
| 48 | + count = count + 1 |
| 49 | + |
| 50 | + return r |
| 51 | + |
| 52 | +def num_qubits(i): |
| 53 | + # Returns the number of qubits needed to represent the value i. |
| 54 | + return ceil(log(i, 2)) |
| 55 | + |
15 | 56 | def execute(qc): |
16 | 57 | # Setup the API key for the real quantum computer. |
17 | 58 | parser = RawConfigParser() |
|
0 commit comments