Compile-time integer arithmetic without using templates

J

Juha Nieminen

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top