proconlib

This documentation is automatically generated by competitive-verifier/competitive-verifier

View the Project on GitHub anqooqie/proconlib

:heavy_check_mark: $\left\lceil \sqrt{x} \right\rceil$ (tools/ceil_sqrt.hpp)

template <typename T>
T ceil_sqrt(T x);

It returns $\left\lceil \sqrt{x} \right\rceil$.

Constraints

Time Complexity

License

Author

Depends on

Required by

Verified with

Code

#ifndef TOOLS_CEIL_SQRT_HPP
#define TOOLS_CEIL_SQRT_HPP

#include <cassert>
#include "tools/ceil.hpp"

namespace tools {

  template <typename T>
  T ceil_sqrt(const T n) {
    assert(n >= 0);

    if (n == 0) return 0;

    T ok = 1;
    T ng;
    for (ng = 2; ng - 1 < tools::ceil(n, ng - 1); ng *= 2);

    while (ng - ok > 1) {
      const T mid = ok + (ng - ok) / 2;
      if (mid - 1 < tools::ceil(n, mid - 1)) {
        ok = mid;
      } else {
        ng = mid;
      }
    }

    return ok;
  }
}

#endif
#line 1 "tools/ceil_sqrt.hpp"



#include <cassert>
#line 1 "tools/ceil.hpp"



#line 5 "tools/ceil.hpp"
#include <type_traits>
#line 1 "tools/is_integral.hpp"



#line 5 "tools/is_integral.hpp"

namespace tools {
  template <typename T>
  struct is_integral : ::std::is_integral<T> {};

  template <typename T>
  inline constexpr bool is_integral_v = ::tools::is_integral<T>::value;
}


#line 1 "tools/is_unsigned.hpp"



#line 5 "tools/is_unsigned.hpp"

namespace tools {
  template <typename T>
  struct is_unsigned : ::std::is_unsigned<T> {};

  template <typename T>
  inline constexpr bool is_unsigned_v = ::tools::is_unsigned<T>::value;
}


#line 8 "tools/ceil.hpp"

namespace tools {
  template <typename M, typename N> requires (
    ::tools::is_integral_v<M> && !::std::is_same_v<::std::remove_cv_t<M>, bool> &&
    ::tools::is_integral_v<N> && !::std::is_same_v<::std::remove_cv_t<N>, bool>)
  constexpr ::std::common_type_t<M, N> ceil(const M x, const N y) noexcept {
    assert(y != 0);
    if (y >= 0) {
      if (x > 0) {
        return (x - 1) / y + 1;
      } else {
        if constexpr (::tools::is_unsigned_v<::std::common_type_t<M, N>>) {
          return 0;
        } else {
          return x / y;
        }
      }
    } else {
      if (x >= 0) {
        if constexpr (::tools::is_unsigned_v<::std::common_type_t<M, N>>) {
          return 0;
        } else {
          return x / y;
        }
      } else {
        return (x + 1) / y + 1;
      }
    }
  }
}


#line 6 "tools/ceil_sqrt.hpp"

namespace tools {

  template <typename T>
  T ceil_sqrt(const T n) {
    assert(n >= 0);

    if (n == 0) return 0;

    T ok = 1;
    T ng;
    for (ng = 2; ng - 1 < tools::ceil(n, ng - 1); ng *= 2);

    while (ng - ok > 1) {
      const T mid = ok + (ng - ok) / 2;
      if (mid - 1 < tools::ceil(n, mid - 1)) {
        ok = mid;
      } else {
        ng = mid;
      }
    }

    return ok;
  }
}


Back to top page