Compile-time integer arithmetic without using templates

Discussion in 'C++' started by Juha Nieminen, Oct 3, 2012.

  1. I think the new 'constexpr' keyword is actually quite cool. For example
    this calculates the integral square root of an integer, rounded up, at
    compile time.

    //------------------------------------------------------------------------
    #include <cstdint>

    constexpr std::uint64_t isqrtIter(std::uint64_t value,
    std::uint64_t low,
    std::uint64_t high)
    {
    return (low < high ? (((low+high)/2) * ((low+high)/2) < value ?
    isqrtIter(value, (low+high)/2 + 1, high) :
    isqrtIter(value, low, (low+high)/2))
    : low);
    }

    constexpr std::uint64_t isqrt(std::uint64_t value)
    {
    return isqrtIter(value, 1, UINT32_MAX);
    }
    //------------------------------------------------------------------------

    This can actually have practical use, for example to create static arrays
    that have the size of sqrt(constant), which might be useful for some
    algorithms.
     
    Juha Nieminen, Oct 3, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JKop
    Replies:
    3
    Views:
    484
  2. joshc
    Replies:
    5
    Views:
    564
    Keith Thompson
    Mar 31, 2005
  3. Replies:
    5
    Views:
    457
    mlimber
    Oct 12, 2005
  4. recover
    Replies:
    2
    Views:
    822
    recover
    Jul 25, 2006
  5. Carter
    Replies:
    2
    Views:
    514
    Carter
    Mar 4, 2009
Loading...

Share This Page