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. Advertisements

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:
    667
  2. Amit
    Replies:
    1
    Views:
    417
    Srini
    May 6, 2005
  3. joshc
    Replies:
    5
    Views:
    752
    Keith Thompson
    Mar 31, 2005
  4. Replies:
    5
    Views:
    565
    mlimber
    Oct 12, 2005
  5. Dave Rahardja
    Replies:
    4
    Views:
    729
    Dave Rahardja
    Nov 21, 2005
  6. recover
    Replies:
    2
    Views:
    1,054
    recover
    Jul 25, 2006
  7. Nagaraj
    Replies:
    1
    Views:
    1,164
    Lionel B
    Mar 1, 2007
  8. Carter
    Replies:
    2
    Views:
    666
    Carter
    Mar 4, 2009
Loading...