Modify KaliskiModInverse to support zero #1486
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
By construction KaliskiModInverse assumes its inputs are valid (i.e. gcd(x, mod) = 1). The case of zero is interesting however since for the bloq to be unitary it has to send zero to itself. the default circuit either does that or sends it to$p$ depending on whether the opreation $p - r$ is implemented as $\mathcal{O}(2n)$ $p + 1$ ) $\mathcal{O}(n)$ toffoli (which is what we do).
ModNeg
toffoli or as ~r -> AddK(
Changing the final step to use ModNeg solves the problem (but increases the toffoli costs by$n$ ). it also prevents us from freeing the $u$ and $s$ registers so we will have to keep them around for uncomputation. This means we keep $6n$ junk qubits.
Alternatively we can do this at no additional cost and by keeping only$4n$ junk qubits. The condition $x=0$ or more precisely $v=0$ is checked at the beginning of each iteration. so I just keep the result of that check for uncomputation. The case where $x=0$ corresponds to having the first check yield 1. Also the first check is 1 if and ony if $x=0$ .