# cirq.ArithmeticGate

A helper gate for implementing reversible classical arithmetic.

Inherits From: `Gate`

### Used in the notebooks

Used in the tutorials

Child classes must override the `registers`, `with_registers`, and `apply` methods.

This class handles the details of ensuring that the scaling of implementing the gate is O(2^n) instead of O(4^n) where n is the number of qubits being acted on, by implementing an `_apply_unitary_` function in terms of the registers and the apply function of the child class.

#### Examples:

````class Add(cirq.ArithmeticGate):`
`    def __init__(`
`        self,`
`        target_register: '[int, Sequence[int]]',`
`        input_register: 'Union[int, Sequence[int]]',`
`    ):`
`        self.target_register = target_register`
`        self.input_register = input_register`

`    def registers(self) -> 'Sequence[Union[int, Sequence[int]]]':`
`        return self.target_register, self.input_register`

`    def with_registers(`
`        self, *new_registers: 'Union[int, Sequence[int]]'`
`    ) -> 'Add':`
`        return Add(*new_registers)`

`    def apply(self, *register_values: int) -> 'Union[int, Iterable[int]]':`
`        return sum(register_values)`
`cirq.unitary(`
`    Add(target_register=[2, 2],`
`        input_register=1).on(*cirq.LineQubit.range(2))`
`).astype(np.int32)`
`array([[0, 0, 0, 1],`
`       [1, 0, 0, 0],`
`       [0, 1, 0, 0],`
`       [0, 0, 1, 0]], dtype=int32)`
`c = cirq.Circuit(`
`   cirq.X(cirq.LineQubit(3)),`
`   cirq.X(cirq.LineQubit(2)),`
`   cirq.X(cirq.LineQubit(6)),`
`   cirq.measure(*cirq.LineQubit.range(4, 8), key='before_in'),`
`   cirq.measure(*cirq.LineQubit.range(4), key='before_out'),`

`   Add(target_register= * 4,`
`       input_register= * 4).on(*cirq.LineQubit.range(8)),`

`   cirq.measure(*cirq.LineQubit.range(4, 8), key='after_in'),`
`   cirq.measure(*cirq.LineQubit.range(4), key='after_out'),`
`)`
`cirq.sample(c).data`
`   before_in  before_out  after_in  after_out`
`0          2           3         2          5`
```

## Methods

### `apply`

View source

Returns the result of the gate operating on classical values.

For example, an addition takes two values (the target and the source), adds the source into the target, then returns the target and source as the new register values.

The `apply` method is permitted to be sloppy in three ways:

1. The `apply` method is permitted to return values that have more bits than the registers they will be stored into. The extra bits are simply dropped. For example, if the value 5 is returned for a 2 qubit register then 5 % 22 = 1 will be used instead. Negative values are also permitted. For example, for a 3 qubit register the value -2 becomes -2 % 23 = 6.
2. When the value of the last `k` registers is not changed by the gate, the `apply` method is permitted to omit these values from the result. That is to say, when the length of the output is less than the length of the input, it is padded up to the intended length by copying from the same position in the input.
3. When only the first register's value changes, the `apply` method is permitted to return an `int` instead of a sequence of ints.

The `apply` method must be reversible. Otherwise the gate will not be unitary, and incorrect behavior will result.

Examples

``````def apply(self, target, offset):
return (target + offset) % 2**len(self.target_register), offset
``````

The same adder, with less boilerplate due to the details being handled by the `ArithmeticGate` class:

``````def apply(self, target, offset):
return target + offset
``````

### `controlled`

View source

Returns a controlled version of this gate. If no arguments are specified, defaults to a single qubit control.

Args
`num_controls` Total number of control qubits.
`control_values` Which control computational basis state to apply the sub gate. A sequence of length `num_controls` where each entry is an integer (or set of integers) corresponding to the computational basis state (or set of possible values) where that control is enabled. When all controls are enabled, the sub gate is applied. If unspecified, control values default to 1.
`control_qid_shape` The qid shape of the controls. A tuple of the expected dimension of each control qid. Defaults to `(2,) * num_controls`. Specify this argument when using qudits.

Returns
A `cirq.Gate` representing `self` controlled by the given control values and qubits. This is a `cirq.ControlledGate` in the base implementation, but subclasses may return a different gate type.

### `num_qubits`

View source

The number of qubits this gate acts on.

### `on`

View source

Returns an application of this gate to the given qubits.

Args
`*qubits` The collection of qubits to potentially apply the gate to.

Returns: a `cirq.Operation` which is this gate applied to the given qubits.

### `on_each`

View source

Returns a list of operations applying the gate to all targets.

Args
`*targets` The qubits to apply this gate to. For single-qubit gates this can be provided as varargs or a combination of nested iterables. For multi-qubit gates this must be provided as an `Iterable[Sequence[Qid]]`, where each sequence has `num_qubits` qubits.

Returns
Operations applying this gate to the target qubits.

Raises
`ValueError` If targets are not instances of Qid or Iterable[Qid]. If the gate qubit number is incompatible.
`TypeError` If a single target is supplied and it is not iterable.

### `registers`

View source

The data acted upon by the arithmetic gate.

Each register in the list can either be a classical constant (an `int`), or else a list of qubit/qudit dimensions. Registers that are set to a classical constant must not be mutated by the arithmetic gate (their value must remain fixed when passed to `apply`).

Registers are big endian. The first qubit is the most significant, the last qubit is the 1s qubit, the before last qubit is the 2s qubit, etc.

Returns
A list of constants and qubit groups that the gate will act upon.

### `validate_args`

View source

Checks if this gate can be applied to the given qubits.

By default checks that:

• inputs are of type `Qid`
• len(qubits) == num_qubits()
• qubit_i.dimension == qid_shape[i] for all qubits

Child classes can override. The child implementation should call `super().validate_args(qubits)` then do custom checks.

Args
`qubits` The sequence of qubits to potentially apply the gate to.

Raises
`ValueError` The gate can't be applied to the qubits.

### `with_probability`

View source

Creates a probabilistic channel with this gate.

Args
`probability` floating point value between 0 and 1, giving the probability this gate is applied.

Returns
`cirq.RandomGateChannel` that applies `self` with probability `probability` and the identity with probability `1-p`.

### `with_registers`

View source

Returns the same fate targeting different registers.

Args
`*new_registers` The new values that should be returned by the `registers` method.

Returns
An instance of the same kind of gate, but acting on different registers.

### `wrap_in_linear_combination`

View source

Returns a LinearCombinationOfGates with this gate.

Args
`coefficient` number coefficient to use in the resulting `cirq.LinearCombinationOfGates` object.

Returns
`cirq.LinearCombinationOfGates` containing self with a coefficient of `coefficient`.

View source

### `__call__`

View source

Call self as a function.

View source

View source

View source

View source

View source

### `__truediv__`

View source

[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }]
[{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]