complexity of this algorithm is T(n)= 2T(n-1)+5 is that correct?
No, it is not. You only have one recursive call and don't split the problem into 2 smaller problems, as your formula implies.
You can't use the Master Theorem, when you have something like T(n)=aT(n-1)+f(n)
, you need T(n)=aT(n/b)+f(n)
instead. So you have to divide the problem size by the same value every recursive call.
For this version the time complexity is O(n)
, where n = max(a,b)
or n=a+b
. You worst case is when you input gcd(n,n+1)
or gcd(1,n)
then you just subtract 1
n-1
times.
In the best case (where inputs are not the same) you input two successive fibonacci numbers, then you get logarithmic complexity.
This best case for subtraction version is the same case as the worst case for modulus version of euclids algorithm. In fact, in this case there is no difference between them.
The Time complexity of Euclids algorithm with modulo is O(log(n))
, where n = max(a,b)
or n=a+b
.
You can get this complexity, when you have a look at the fibonacci numbers. They are the worst case for this algorithm and they grow exponentially. Euclids algoritm goes (backwards, direction does not matter) over this numbers, so the complexity is the inverse of the exponential function, so log(n) (base does not matter)