[英]Calculating the time complexity of this algorithm
I'm trying to calculate the time complexity of this algorithm that determines if a positive integer N can be expressed as x^y. 我正在尝试计算此算法的时间复杂度,该算法确定是否可以将正整数N表示为x ^ y。 The algorithm's author is Vaibhav Gupta .
该算法的作者是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? 自从他使用pow函数以来,这第一个具有不同的时间复杂度吗?
When it returns false, the algorithm tries increasing powers of all integers x
, until they exceed n
. 当返回false时,该算法将尝试增加所有整数
x
,直到它们超过n
为止。 The search stops after x = √n
has been tried. 尝试
x = √n
后,搜索将停止。
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
. 因此,对于粗略评估,评估直到
x^d = n
的幂大约需要log n/log x
乘,然后从x=2
重复到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)
. 这很难估计,但是
O(log n.√n)
和Ω(√n)
。
The pow
version takes log d
multiplies instead of 1
to compute a power, provided it does so by repeated squarings. pow
版本采用log d
乘而不是1
来计算幂,但前提是要通过重复平方来计算。 As d = log n/log x
, the complexity is like 由于
d = log n/log x
,复杂度就像
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)
. 甚至更难估计,但是
O(log n.log log n.√n)
和Ω(√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). 对于int类型覆盖的
n
范围,可以预期pow
版本的速度要慢1到5倍(除非pow
函数的开销很大)。
在我看来,外循环是n的平方根,而内循环按对数n的顺序排列(因为数字呈指数增长),因此您的复杂度应为
O(sqrt(n)*log n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.