Skip to content

Commit

Permalink
Update divide_ceil struct in reduction tutorial (#162)
Browse files Browse the repository at this point in the history
* Update divide_cell

---------

Co-authored-by: Mátyás Aradi <matyas@streamhpc.com>
  • Loading branch information
neon60 and matyas-streamhpc authored Sep 16, 2024
1 parent c07deb9 commit 63c7b92
Showing 1 changed file with 5 additions and 27 deletions.
32 changes: 5 additions & 27 deletions Tutorials/reduction/include/tmp_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,41 +142,19 @@ struct multiply
return I * J;
}
};
// Based on https://stackoverflow.com/a/63436491/1476661 by @jan-schultke

template<int J>
struct divide_ceil
{
template<int I>
FUNC_QUALIFIER constexpr int operator()()
{
using Dividend = decltype(I);
using Divisor = decltype(J);
static constexpr auto x = I;
static constexpr auto y = J;
if constexpr(std::is_unsigned_v<Dividend> && std::is_unsigned_v<Divisor>)
{
// quotient is always positive
return x / y + (x % y != 0); // uint / uint
}
else if constexpr(std::is_signed_v<Dividend> && std::is_unsigned_v<Divisor>)
{
auto sy = static_cast<std::make_signed_t<Divisor>>(y);
bool quotientPositive = x >= 0;
return x / sy + (x % sy != 0 && quotientPositive); // int / uint
}
else if constexpr(std::is_unsigned_v<Dividend> && std::is_signed_v<Divisor>)
{
auto sx = static_cast<std::make_signed_t<Dividend>>(x);
bool quotientPositive = y >= 0;
return sx / y + (sx % y != 0 && quotientPositive); // uint / int
}
else
{
bool quotientPositive = (y >= 0) == (x >= 0);
return x / y + (x % y != 0 && quotientPositive); // int / int
}
static_assert(std::is_signed_v<decltype(I)> && std::is_signed_v<decltype(J)>,
"Invalid type.");
return (I + J - 1) / J;
}
};

template<typename Pred, typename TruePath, typename FalsePath>
struct select
{
Expand Down

0 comments on commit 63c7b92

Please sign in to comment.