Why GCD operation’s complexity is O(1)
1 min readApr 19, 2021
Lots of posts mentioned that GCD caculation is O(1). Why?
I’d like to share a detail analysis from a lecture note. Also this lecture note is a good one if you want to understand more about number thoery required for a CS student.
- First, GCD caculation is related to The Euclidean algorithm
“gcd(a0,a1) = gcd(a1,a2) = … = gcd(ak−1,ak) “ (check the lecture notes 2. The Euclidean algorithm to get details) - Second, GCD caculation:
“a_i is always an upper bound on some Fibonacci number “
“This shows that the number of steps in the Euclidean algorithm is logarithmic in a0, which means linear in the number of bits required to represent a0. “
(check the lecture notes 3 Why not brute force? to get details) - Third, we have the constraints that 1 <= nums[i] ≤ 10⁹, as math.log(10⁹ , 2)=29.897352853986263, we will have time complexity of GCD as O(30) in the worst case. This explains why the time complexity of GCD is O(1)
As far as I know, the following post gave a similar analysis, please also give credits to this post if you feel it is helpful.
https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/419329/O(n)-solution/378434
Reference
Lecture notes:
http://www.cs.hunter.cuny.edu/~saad/courses/dm/notes/note7.pdf