!pip install tabulate
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from tabulate import tabulate
import numpy as np
# Loading your IBM Q account(s)
provider = IBMQ.load_account()

def qft_dagger(n):
    """n-qubit QFTdagger the first n qubits in circ"""
    qc = QuantumCircuit(n)
    # Don't forget the Swaps!
    for qubit in range(n//2):
        qc.swap(qubit, n-qubit-1)
    for j in range(n):
        for m in range(j):
            qc.cu1(-np.pi/float(2**(j-m)), m, j)
        qc.h(j)
    qc.name = "QFT†"
    return qc

def __c_amod15(power):
    """Controlled multiplication by a mod 15"""
    U = QuantumCircuit(4)        
    for iteration in range(power):
        U.swap(2,3)
        U.swap(1,2)
        U.swap(0,1)
        for q in range(4):
            U.x(q)
    U = U.to_gate()
    U.name = "a^%i mod 15" % (power)
    c_U = U.control()
    return c_U


t=3
qc = QuantumCircuit(t+4,t)
for i in range(t):
    qc.h(i)      # The first t qubits are the first register (storing 'x')
qc.x(6) #The second register is in state |1>

# Oracle for the f(x) mentioned above
def Oracle(qc):
    for q in range(3):
        qc.append(__c_amod15(2**q), [q] + [i+3 for i in range(4)])

Oracle(qc)

qc.append(qft_dagger(t),range(t)) # inverse quantum fourier transform only of the register (first 4 qubits)
qc.measure(range(t), range(t))
def run_circuit(qc):
    backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
    result = execute(qc, backend, shots = 100000).result() # we run the simulation
    counts = result.get_counts() # we get the counts
    return counts

counts = run_circuit(qc)
print(counts)
plot_histogram(counts)

rows, eigenvalues = [], []
for output in counts:
    decimal = int(output, 2)
    eigenvalue = decimal/(2**t)
    eigenvalues.append(eigenvalue)
    rows.append(["%s(bin) = %i(dec)" % (output, decimal), "%i/%i = %.2f" % (decimal, 2**t, eigenvalue)])
print(tabulate(rows, headers=["Register Output", "Phase"]))

0.333333333.as_integer_ratio()

rows = []
for eigenvalue in eigenvalues:
    numerator, denominator = eigenvalue.as_integer_ratio()
    rows.append([eigenvalue, "%i/%i" % (numerator, denominator), denominator])
print(tabulate(rows, headers=["Phase", "Fraction", "Guess for r"], colalign=('right','right','right')))