I've always believed that getting the inverse of some integer n this way takes O(log(p)) time:
long long inv(long long n, long long p) {
if (n == 1) return 1;
return inv(p%n, p) * (p - p/n) % p;
}
But recently someone told me that it might be O(sqrt(p)).
So what is the correct time complexity?
It's the same as calculating gcd.
I don't see, why does this hold.
gcd
swaps arguments, while in this functionp
is just parameter, it doesn't change during the recursion.True, I'm not familiar with this code. I only know how to do this with the extended euclidean algorithm.
Apparently this algorithm is attributed to Gauss. You can make it guaranteed $$$O(\log n)$$$ by noticing that $$$p = nq + r = n(q+1) - (n-r)$$$ and $$$\min(r, n - r) \le \frac n2$$$.
But no one usually analyses your simpler one-liner version.
Its time complexity seems to be an open problem.
A common mistake is to consider it to be $$$O(\log(P))$$$ without thinking twice like above.
A problem discussed in this link is actually your problem.
And it gives an upper bound of $$$O(n^{1/3})$$$ and a lower bound of $$$\Omega(\dfrac{\log n}{\log\log n})$$$.
However it's not difficult to optimize it to $$$O(\log(n))$$$ as mmaxio shown above.