首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >计算该算法的时间复杂度

计算该算法的时间复杂度
EN

Stack Overflow用户
提问于 2016-04-08 20:31:01
回答 2查看 83关注 0票数 2

我正在计算这个算法的时间复杂度,这个算法决定了一个正整数N是否可以表示为x^y。这个算法的作者是Vaibhav Gupta

代码语言:javascript
运行
复制
// 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;
}

作者说,这个算法是第一个算法的优化版本,即:

代码语言:javascript
运行
复制
// 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;
}

第一个是不是有不同的时间复杂度,因为他使用了pow函数?

EN

回答 2

Stack Overflow用户

发布于 2016-04-08 21:22:39

当返回false时,算法会尝试增加所有整数x的幂,直到它们超过n为止。尝试使用x = √n后,搜索将停止。

为了进行粗略的评估,计算幂,直到x^d = n约为log n/log x乘法,并从x=2重复到x=√n

因此复杂性是这样的

代码语言:javascript
运行
复制
log n.Sum(x=2 to √n)1/log x

这不容易估计,但是O(log n.√n)Ω(√n)

pow版本采用log d乘法而不是1来计算幂,前提是它通过重复平方来执行此操作。作为d = log n/log x,其复杂性类似于

代码语言:javascript
运行
复制
log n.Sum(x=2 to √n)(log log n - log log x)/log x

更难估计,但O(log n.log log n.√n)Ω(√n)

对于int类型所涵盖的n范围,您可以预期pow版本会慢一倍到五倍(除非pow函数有很大的开销)。

票数 2
EN

Stack Overflow用户

发布于 2016-04-08 20:38:38

在我看来,外部循环是n的平方根,内部循环的顺序是log n(因为数字呈指数级增长),所以您的复杂度应该在

代码语言:javascript
运行
复制
  O(sqrt(n)*log n)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36499633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档