【问题标题】:How to get power of x which is smaller or equal than a given number n?如何获得小于或等于给定数 n 的 x 的幂?
【发布时间】:2021-11-04 00:55:30
【问题描述】:

我有两个数字给定 x 和 n 的问题,任务是找到 x 的幂,它恰好等于或小于 n 。我知道我可以通过启动一个循环来做到这一点,但它似乎不是那么有效的解决方案,我想知道在 o(1) 中的任何解决方案或其他有效的解决方案。

【问题讨论】:

  • 你想要最大的这样的权力吗?这只是 x ^ floor(log_base_x (n) ),假设 x > 1
  • 是的。谢谢你
  • 我不建议将logfloor 一起使用。可能会有一些令人惊讶的舍入错误。循环解决方案只需要 log n / log x 迭代,如果 n 最多为 64 位整数,则不会很多。

标签: algorithm c++11 math


【解决方案1】:

也许沿着这条线:

int foo (int x, int n) {  
    int counter = x;
    int pow = 1;
    while(counter < n) {
        pow =+ pow
        counter =* counter ;
    }
    if(counter == n)
        return pow;
    while(x > n) {
        counter = counter/x;
        pow--;
    }
    return pow;
}

我认为总体而言,在最坏的情况下,它仍然是 O(log(n)),但在某些情况下它应该表现更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2016-09-30
    • 2021-01-08
    相关资源
    最近更新 更多