Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя MohammadParsaElahimanesh

Автор MohammadParsaElahimanesh, история, 3 года назад, По-английски

Hello, many times you need to calculate lg2(n) and usually you need just to calculate floor of that. may these functions help you.

/// there are in O(1) and they work for int and long long numbers that is greater than 0
int lg2(const int &x){return 31 - __builtin_clz(x);}
long long int lg2(const long long int &x){return 63 - __builtin_clzll(x);}
  • Проголосовать: нравится
  • +7
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится +19 Проголосовать: не нравится

You do not need const& for primitives. I'm not sure if the reference gets ignored or optimized out, but either way it's a code smell.

»
3 года назад, # |
  Проголосовать: нравится +28 Проголосовать: не нравится

C++ (at least C++17) already offers the function __lg() that does exactly this.

  • »
    »
    3 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Ctrl+F through C++20 standard not found any __lg() function. Maybe it's just gcc implementation?

    • »
      »
      »
      3 года назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      Yes, I think it's only for gcc. Anyways, why would you choose another compiler instead of GCC? Official competitions (like ICPC/IOI) use GCC, and also you have some things in GCC that are not available in other compilers.

      • »
        »
        »
        »
        3 года назад, # ^ |
          Проголосовать: нравится 0 Проголосовать: не нравится
        1. My remark just to avoid misleading that __lg() is C++ function.
        2. I just don't like any platform/compiler-dependent code. I think it's too bad to be used to rely on gcc-specific code and be surprised when same code not/slow work in other compilers. For same reason I always use whole header list instead of bits/stdc++.
        3. Maybe it's main reason — I write in Visual Studio :)