📜  求所有小于或等于给定数的2的幂

📅  最后修改于: 2021-06-25 23:41:32             🧑  作者: Mango

给定正数N ,任务是找出两个小于或等于给定数N的所有完美幂。

例子:

天真的方法:这个想法是将每个数字从N遍历到1,并检查它是否是2的完美幂。如果是,则打印该号码。

另一种方法:这个想法是找到2的所有幂,然后简单地打印小于或等于N的幂。

另一种方法:该思想基于二进制的所有2的幂均设置了所有位的概念。这种方法中使用了位集函数来解决上述问题。步骤如下:

  1. 找出2的最大幂(例如temp ),该最大幂用于评估小于或等于N的数字
  2. 初始化最大大小为64的位集数组arr [] ,以存储给定数字N的二进制表示形式。
  3. 使用reset()函数重置位集数组中的所有位。
  4. total迭代到0 ,然后依次使每个位为1 ,并找到该二进制表达式的值,然后重置该位。

下面是上述方法的实现:

// C++ program for the above approach
  
#include 
using namespace std;
const int MAX = 64;
  
// Function to return max exponent of
// 2 which evaluates a number less
// than or equal to N
int max_exponent(int n)
{
    return (int)(log2(n));
}
  
// Function to print all the powers
// of 2 less than or equal to N
void all_powers(int N)
{
    bitset<64> arr(N);
  
    // Reset all the bits
    arr.reset();
  
    int total = max_exponent(N);
  
    // Iterate from total to 0
    for (int i = total; i >= 0; i--) {
  
        // Reset the next bit
        arr.reset(i + 1);
  
        // Set the current bit
        arr.set(i);
  
        // Value of the binary expression
        cout << arr.to_ulong() << " ";
    }
}
  
// Driver Code
int main()
{
    // Given Number
    int N = 63;
  
    // Function Call
    all_powers(N);
    return 0;
}
输出:
32 16 8 4 2 1

时间复杂度: O(log N)
辅助空间: O(1)