pyqpanda_alg.QLuoShu.VarModAdd

Module Contents

Functions

VarModAdd(qvec1, qvec2, auxadd, aux, N)

Quantum Circuit for Variant Modular Addition.

pyqpanda_alg.QLuoShu.VarModAdd.VarModAdd(qvec1, qvec2, auxadd, aux, N)

Quantum Circuit for Variant Modular Addition.

The circuit computes a modular addition of two integers \(x\) and \(y\) modulo the constant integer modulos \(N\), i.e., \(|x+y \mod N \rangle\).

Parameters:

\(a\) : int

the integer to be added

\(N\) : int

the constant modulo

qvec1 & qvec2 : qlist

the qubits list, holds the integer \(x\) & \(y\)

auxadd & aux : qubit

an auxiliary qubit for the operation of QAdder and control constant modulo addition

Return:

circuit: pq.QCircuit

It performs the operation in place \(|x \rangle|y \rangle \rightarrow |(x+y) \mod N \rangle|y \rangle\) and replaces the first input with the result. It uses quantum circuits for plain integer addition and constant addition and subtraction of the modulus \(N\). It uses two auxiliary qubits, one of which is used as an ancilla qubit in the constant addition and subtraction and can be in an unknown state to which it will be returned at the end of the circuit. The circuit needs \(2n+2\) qubits with \(n=\lceil \log_{2}N \rceil\). The circuit is inverse that can be used to compute \(|x \rangle|y \rangle \rightarrow |(x-y) \mod N \rangle|y \rangle\).

Example:

If \(x =7, y=9, N=11\), putting \(x\) held in \(|qvec1 \rangle\) and \(y\) held in \(|qvec2 \rangle\). By the circuit, the result \(|0101 \rangle\) will be held in the \(|qvec1 \rangle\), i.e., \(7+9 \mod 11=5\). If by the inverse of the circuit (by the operator: VarModAdd.dagger()), we can get \(7-9 \mod 11=9\), the result \(|1001 \rangle\) will be held in the \(|qvec1 \rangle\).

from pyqpanda import *
import math
from pyqpanda_alg.QLuoShu import VarModAdd

if __name__ == "__main__":
    N = 11
    x = 7
    y = 9
    n = math.ceil(math.log(N, 2))
    qvm = init_quantum_machine(QMachineType.CPU)
    prog = QProg()

    qvec1 = qvm.qAlloc_many(n)
    qvec2 = qvm.qAlloc_many(n)
    aux = qvm.qAlloc_many(1)
    auxadd = qvm.qAlloc()

    prog << bind_nonnegative_data(x, qvec1) \
         << bind_nonnegative_data(y, qvec2) \
         << VarModAdd.VarModAdd(qvec1, qvec2, auxadd, aux, N)
    result = prob_run_dict(prog, qvec1, 1)

    for key in result:
        print(key + ":" + str(result[key]))
        c = int(key, 2)
    print("%d+%d mod %d=%d" % (x, y, N, c))
0101:1.000000000000029
7+9 mod 11=5

Note that: if \(N\) is a power of 2, we need to let \(n=\lceil \log_{2}N \rceil+1\) in the Example.