A formula that guarantees that f(ULLONG_MAX) * f(ULLONG_MAX) is not more than ULLONG_MAX

Viewed 84

I'm making a container class and I want to specify that its maximum size, if multiplied by itself, should not be more than the maximum value of unsigned long long (specifically, std::numeric_limits<unsigned long long>::max()).

Assuming that ULLONG_MAX is 264-1, how safe is this calculation and how can I improve it if necessary?

typedef unsigned long long size_type;
size_type max_size = size_type(std::sqrt(ULLONG_MAX)) - 1;
1 Answers

232 squared is 264, too big.

232 - 1 squared is 264-233+1.

So just use 232-1.

In general (static_cast<T>(1) << static_cast<T>(sizeof(T)*4)) - 1 gets you the largest squarable unsigned value of type T, if T is an unsigned integral type.

Related