I'm trying to calculate the time complexity of this algorithm that determines if a positive integer N can be expressed as x^y. The algorithm's author is Vaibhav Gupta .
// Returns true if n can be written as x^y
bool isPower(unsigned int n)
{
// Base case
if (n <= 1) return true;
// Try all numbers from 2 to sqrt(n) as base
for (int x=2; x<=sqrt(n); x++)
{
unsigned p = x;
// Keep multiplying p with x while is smaller
// than or equal to x
while (p <= n)
{
p *= x;
if (p == n)
return true;
}
}
return false;
}
The author says that this algorithm is an optimized version of the first one which is:
// Returns true if n can be written as x^y
bool isPower(unsigned n)
{
if (n==1) return true;
// Try all numbers from 2 to sqrt(n) as base
for (int x=2; x<=sqrt(n); x++)
{
unsigned y = 2;
unsigned p = pow(x, y);
// Keep increasing y while power 'p' is smaller
// than n.
while (p<=n && p>0)
{
if (p==n)
return true;
y++;
p = pow(x, y);
}
}
return false;
}
Does this first one has a different time complexity since he uses the pow function?
When it returns false, the algorithm tries increasing powers of all integers x
, until they exceed n
. The search stops after x = √n
has been tried.
So for a rough evaluation, evaluating the powers until x^d = n
takes about log n/log x
multiplies, and is repeated from x=2
to x=√n
.
Hence the complexity is like
log n.Sum(x=2 to √n)1/log x
which is uneasy to estimate, but O(log n.√n)
and Ω(√n)
.
The pow
version takes log d
multiplies instead of 1
to compute a power, provided it does so by repeated squarings. As d = log n/log x
, the complexity is like
log n.Sum(x=2 to √n)(log log n - log log x)/log x
even harder to estimate, but O(log n.log log n.√n)
and Ω(√n)
.
For the range of n
covered by the int type, you can expect the pow
version to be between one time and five times slower (unless the pow
function has a big overhead).
在我看来,外循环是n的平方根,而内循环按对数n的顺序排列(因为数字呈指数增长),因此您的复杂度应为
O(sqrt(n)*log n)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.