Quantum Algorithms: Code and Mathematical Implementation

 Quantum Algorithms: Code and Mathematical Implementation

Author
Quantum Algorithms Research Society

Date: September 14, 2025


Abstract

Quantum computing, as an emerging computational paradigm, leverages the principles of quantum mechanics such as superposition, entanglement, and interference to offer potential advantages beyond classical computing. This paper systematically explores the core mathematical foundations and code implementations of quantum algorithms, including qubit state representation, basic quantum gates, Grover's search algorithm, Shor's factoring algorithm, quantum superposition and entanglement demonstrations, the Variational Quantum Eigensolver (VQE), and Quantum Fourier Transform (QFT). The complexity analysis is also provided to demonstrate quantum advantage. All mathematical expressions are presented using Unicode plaintext symbols for readability and ease of copying, with Python code implementation provided using the Qiskit framework. Through these examples, we show how quantum algorithms achieve exponential speedup in search, factoring, and optimization problems, laying the foundation for future quantum computing applications.

Keywords: Quantum Computing, Grover's Algorithm, Shor's Algorithm, Variational Quantum Eigensolver, Quantum Fourier Transform


Introduction

Since Richard Feynman proposed the concept of quantum computing in 1982, quantum algorithms have become a central field in quantum information science. Classical computing relies on deterministic bit states, while quantum computing uses qubits' superposition and entanglement to process vast computational spaces in parallel, overcoming certain complexity bottlenecks. For example, Grover's algorithm reduces the complexity of unstructured search from O(N) to O(√N), while Shor's algorithm threatens the security of current RSA encryption.

This paper is structured as follows: Section 2 introduces the mathematical representation of quantum fundamentals; Section 3 details the mathematical principles and implementation of Grover's algorithm; Section 4 explores the core of Shor's algorithm; Section 5 demonstrates quantum superposition and entanglement; Section 6 introduces the Variational Quantum Eigensolver; Section 7 presents the Quantum Fourier Transform; Section 8 provides mathematical proof of quantum advantage; and finally, the conclusion summarizes and looks forward to the future. All code examples are based on the Qiskit framework, with mathematical expressions in Unicode plaintext for ease of reading and copying.


1. Quantum Fundamental Mathematical Representations

1.1 Qubit State

The state of a qubit can be represented as a linear combination:

ψ=α0+β1|\psi\rangle = \alpha|0\rangle + \beta|1\rangle

where α2+β2=1|\alpha|^2 + |\beta|^2 = 1, and α\alpha and β\beta are complex amplitudes that satisfy the normalization condition. This reflects the quantum superposition principle: a qubit can be in a superposition of 0|0\rangle and 1|1\rangle until measured, at which point it collapses to a classical bit.

1.2 Quantum Gate Operations

Quantum gates are the building blocks of quantum circuits, similar to classical logic gates, but they are unitary transformations.

  • Hadamard Gate (H):

H=12[1111]H = \frac{1}{\sqrt{2}} \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix}

Its action is:

H0=12(0+1)H|0\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle) H1=12(01)H|1\rangle = \frac{1}{\sqrt{2}}(|0\rangle - |1\rangle)

The Hadamard gate creates a uniform superposition state.

  • Pauli-X Gate (NOT):

X=[0110]X = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}

Its action is:

X0=1X|0\rangle = |1\rangle X1=0X|1\rangle = |0\rangle

This gate flips the state of a qubit, similar to a classical NOT gate.

These basic operations serve as the foundation for subsequent algorithms.


2. Grover’s Algorithm Implementation

2.1 Mathematical Principles

Grover's algorithm solves the unstructured database search problem: given NN items, find a specific target ww. Classical methods require O(N)O(N) queries, whereas Grover only requires O(N)O(\sqrt{N}).

  • Oracle Function:

Ufxy=xyf(x)U_f |x\rangle |y\rangle = |x\rangle |y \oplus f(x)\rangle

where f(x)=1f(x) = 1 if x=wx = w, otherwise f(x)=0f(x) = 0. This function marks the target state with a phase flip.

  • Diffusion Operator:

D=2ssID = 2 |s\rangle \langle s| - I

where s=1Nx|s\rangle = \frac{1}{\sqrt{N}} \sum |x\rangle is the uniform superposition state. The diffusion operator amplifies the target amplitude.

The algorithm iterates between the oracle and diffusion operator, with the optimal number of iterations being approximately π4N\frac{\pi}{4} \sqrt{N}.

2.2 Python Implementation (using Qiskit)

The following is a Qiskit implementation of Grover's algorithm:

from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import execute, Aer
import numpy as np

def grovers_algorithm(n_qubits, target_item):
    """ Grover's algorithm implementation """
    qreg = QuantumRegister(n_qubits, 'q')
    creg = ClassicalRegister(n_qubits, 'c')
    circuit = QuantumCircuit(qreg, creg)

    # Step 1: Initialization - Create uniform superposition
    for i in range(n_qubits):
        circuit.h(qreg[i])

    # Calculate optimal number of iterations
    N = 2**n_qubits
    optimal_iterations = int(np.pi * np.sqrt(N) / 4)

    # Step 2: Grover iterations
    for _ in range(optimal_iterations):
        oracle_circuit(circuit, qreg, target_item)
        diffusion_operator(circuit, qreg)

    # Measure
    circuit.measure(qreg, creg)
    return circuit

# Oracle function and Diffusion operator are defined here...

This implementation simulates a 3-qubit system with the target binary value "101". The circuit depth reflects the computational complexity.


3. Shor’s Algorithm Core

3.1 Mathematical Foundations

Shor’s algorithm solves the integer factorization problem: given N=p×qN = p \times q, find the nontrivial factors pp and qq. This problem is NP-intermediate in classical computing.

Key steps:

  1. Randomly choose aa (with 1<a<N1 < a < N, gcd(a,N)=1\text{gcd}(a, N) = 1).

  2. Find the period rr of the function f(x)=axmodNf(x) = a^x \mod N.

  3. If rr is even and ar/2≢1modNa^{r/2} \not\equiv -1 \mod N, then gcd(ar/21,N)\text{gcd}(a^{r/2} - 1, N) and gcd(ar/2+1,N)\text{gcd}(a^{r/2} + 1, N) are factors of NN.

The period-finding relies on quantum phase estimation (QPE).

3.2 Quantum Phase Estimation Core

Here is a simplified implementation of quantum period finding:

import numpy as np
from qiskit import QuantumCircuit, QuantumRegister

def quantum_period_finding(N, a, n_counting_qubits):
    """Quantum period finding algorithm"""
    n_work_qubits = int(np.ceil(np.log2(N)))

    # Create quantum registers
    counting_qreg = QuantumRegister(n_counting_qubits, 'counting')
    work_qreg = QuantumRegister(n_work_qubits, 'work')
    circuit = QuantumCircuit(counting_qreg, work_qreg)

    # Initialize work register to |1>
    circuit.x(work_qreg[0])

    # Create uniform superposition on counting register
    for i in range(n_counting_qubits):
        circuit.h(counting_qreg[i])

    # Controlled modular exponentiation
    repetitions = 1
    for counting_qubit in range(n_counting_qubits):
        controlled_modular_exponentiation(circuit, counting_qreg[counting_qubit], work_qreg, a, repetitions, N)
        repetitions *= 2

    # Inverse quantum Fourier transform
    inverse_qft(circuit, counting_qreg)

    return circuit

def controlled_modular_exponentiation(circuit, control_qubit, target_qubits, a, power, N):
    """Controlled modular exponentiation"""
    value = pow(a, power, N)
    # (This part needs to be implemented with a modular multiplication quantum circuit)
    pass

def inverse_qft(circuit, qreg):
    """Inverse Quantum Fourier Transform"""
    n = len(qreg)
    for i in range(n // 2):
        circuit.swap(qreg[i], qreg[n - 1 - i])

    for i in range(n):
        circuit.h(qreg[i])
        for j in range(i + 1, n):
            circuit.cp(-np.pi / (2**(j - i)), qreg[j], qreg[i])

Here’s the English translation of your text, keeping the technical details intact and clear:


This circuit uses a counting register to estimate the phase and extract the period. Modular exponentiation is the bottleneck, so optimizing the modular multiplication circuit is necessary.


4. Demonstration of Quantum Superposition and Entanglement

4.1 Creation of Superposition

Superposition is at the core of quantum computing. The following creates a uniform superposition of two qubits:

def create_superposition():
    """Create a two-qubit superposition state"""

    circuit = QuantumCircuit(2)

    # |00⟩ → 1/2(|00⟩ + |01⟩ + |10⟩ + |11⟩)
    circuit.h(0)
    circuit.h(1)

    return circuit

Mathematical representation:

ψ=HH00=12(0+1)(0+1)=12(00+01+10+11)|\psi⟩ = H \otimes H |00⟩ = \tfrac{1}{2} (|0⟩ + |1⟩) \otimes (|0⟩ + |1⟩) = \tfrac{1}{2} (|00⟩ + |01⟩ + |10⟩ + |11⟩)

Upon measurement, each state appears with probability 1/4.


4.2 Bell State (Maximal Entanglement State)

Entangled states exhibit non-locality:

def create_bell_state():
    """Create the Bell state |Φ⁺⟩"""

    circuit = QuantumCircuit(2)

    # |00⟩ → |Φ⁺⟩ = 1/√2(|00⟩ + |11⟩)
    circuit.h(0)      # Create superposition
    circuit.cx(0, 1)  # Create entanglement

    return circuit

Mathematical representation:

Φ+=CNOT(HI)00=CNOT12(00+10)=12(00+11)|Φ^+⟩ = \text{CNOT} \cdot (H \otimes I)|00⟩ = \text{CNOT} \cdot \tfrac{1}{\sqrt{2}} (|00⟩ + |10⟩) = \tfrac{1}{\sqrt{2}} (|00⟩ + |11⟩)

Measurement results are correlated: if one particle is measured as 0|0⟩, the other must also be 0|0⟩.


5. Variational Quantum Eigensolver (VQE)

5.1 Mathematical Framework

VQE is suitable for the NISQ (Noisy Intermediate-Scale Quantum) era, aiming to find the ground-state energy of a Hamiltonian HH:

E0=minθψ(θ)Hψ(θ)E_0 = \min_{\theta} \langle \psi(\theta) | H | \psi(\theta) \rangle

Here, ψ(θ)|\psi(\theta)⟩ is a parameterized trial wavefunction, with parameters θ\theta adjusted by a classical optimizer.


5.2 Python Implementation

from scipy.optimize import minimize
import numpy as np

def vqe_algorithm(hamiltonian, ansatz_circuit, initial_params):
    """
    Variational Quantum Eigensolver

    hamiltonian: Hamiltonian matrix
    ansatz_circuit: parameterized quantum circuit
    initial_params: initial parameter values
    """

    def cost_function(params):
        # Build parameterized circuit
        circuit = ansatz_circuit(params)

        # Compute expectation value ⟨ψ(θ)|H|ψ(θ)⟩
        expectation_value = compute_expectation(circuit, hamiltonian)
        return expectation_value

    # Classical optimization
    result = minimize(cost_function, initial_params, method='COBYLA')
    return result


def ansatz_circuit(params):
    """Parameterized quantum circuit"""
    circuit = QuantumCircuit(2)

    # RY rotations
    circuit.ry(params[0], 0)
    circuit.ry(params[1], 1)

    # Entangling layer
    circuit.cx(0, 1)

    # More parameterized layers
    circuit.ry(params[2], 0)
    circuit.ry(params[3], 1)

    return circuit


def compute_expectation(circuit, hamiltonian):
    """Compute expectation value"""
    # Run circuit and evaluate ⟨H⟩
    # (Actual implementation requires a quantum backend)
    pass

VQE combines quantum circuits with classical optimization, making it suitable for problems such as molecular simulations in quantum chemistry.



6. Quantum Fourier Transform

6.1 Mathematical Definition

Quantum Fourier Transform (QFT) is a key subroutine in Shor’s algorithm:

QFTx=1Nk=0N1e2πixkNkQFT |x⟩ = \frac{1}{\sqrt{N}} \sum_{k=0}^{N-1} e^{2\pi i \frac{x k}{N}} |k⟩

This transformation maps the time domain to the frequency domain, efficiently extracting periodicity information.

6.2 Circuit Implementation

def quantum_fourier_transform(circuit, qreg):
    """Quantum Fourier Transform Implementation"""
    n = len(qreg)
    
    for i in range(n):
        # Apply Hadamard gate
        circuit.h(qreg[i])

        # Apply controlled phase gates
        for j in range(i + 1, n):
            angle = np.pi / (2**(j - i))
            circuit.cp(angle, qreg[j], qreg[i])

    # Reverse the order of qubits
    for i in range(n // 2):
        circuit.swap(qreg[i], qreg[n - 1 - i])

Usage Example:

n_qubits = 3
qreg = QuantumRegister(n_qubits)
circuit = QuantumCircuit(qreg)

# Prepare initial state
circuit.x(qreg[0])  # |001⟩

# Apply QFT
quantum_fourier_transform(circuit, qreg)

The depth of a QFT circuit is O(n2)O(n^2), but it provides an O(nlogn)O(n \log n) speedup compared to classical FFT.

7. Mathematical Proof of Quantum Advantage

7.1 Grover’s Algorithm Complexity Analysis

Classical Search:
O(N)O(N) queries

Grover’s Algorithm:
O(N)O(\sqrt{N}) queries

For N=220N = 2^{20} items:

  • Classical: ~1,048,576 queries

  • Quantum: ~1,024 queries

Speedup: N1024\sqrt{N} \approx 1024

This quadratic speedup is universal for unstructured problems.

7.2 Shor’s Algorithm Complexity

Classical Factorization (best known):

O(exp((logN)1/3(loglogN)2/3))O(\exp((\log N)^{1/3} (\log \log N)^{2/3}))

Shor’s Algorithm:

O((logN)3)O((\log N)^3)

For a 1024-bit RSA key:

  • Classical: ~102910^{29} years (using the current best algorithms)

  • Quantum: A few hours (theoretically, requires fault-tolerant quantum computers)

Shor’s algorithm offers exponential speedup, threatening the security of public-key encryption.

Conclusion

This paper provides a comprehensive overview of the mathematical foundations and Qiskit implementations of quantum algorithms. From basic quantum states to advanced applications like Grover and Shor, it showcases the potential of quantum computing. Despite challenges in the NISQ era due to noise, hybrid approaches such as VQE have already shown practical value. As quantum hardware advances, these algorithms will revolutionize fields like chemistry, optimization, and cryptography. Researchers can build on the provided code to experiment further and explore the boundaries of quantum advantage.

References

  1. M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information, Cambridge University Press, 2010.

  2. L. K. Grover, “A fast quantum mechanical algorithm for database search,” Proceedings of the Twenty-Eighth Annual ACM Symposium on Theory of Computing, 1996.

  3. P. W. Shor, “Algorithms for quantum computation: discrete logarithms and factoring,” Proceedings of the 35th Annual Symposium on Foundations of Computer Science, 1994.

  4. Qiskit Development Team, “Qiskit: An open-source framework for quantum computing,” 2025.


コメント

このブログの人気の投稿

修仙を極めた僕が量子理論で世界を救うまでの恋愛記録

凡人修真の一念永恒(原典・呪文注釈付き)

Exploring Quantum Computing: Principles and Applications