ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
int_pow.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2010-2022 The ESPResSo project
3 * Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010
4 * Max-Planck-Institute for Polymer Research, Theory Group
5 *
6 * This file is part of ESPResSo.
7 *
8 * ESPResSo is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * ESPResSo is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#ifndef UTILS_MATH_INT_POW_HPP
23#define UTILS_MATH_INT_POW_HPP
24
26
27#include <type_traits>
28
29namespace Utils {
30namespace detail {
31template <class T, unsigned n, class = void> struct int_pow_impl {
32 DEVICE_QUALIFIER constexpr T operator()(T x) const {
33 return x * int_pow_impl<T, (n - 1) / 2>{}(x * x);
34 }
35};
36
37/* Specialization for n even */
38template <class T, unsigned n>
39struct int_pow_impl<T, n, std::enable_if_t<n % 2 == 0>> {
40 DEVICE_QUALIFIER constexpr T operator()(T x) const {
41 return int_pow_impl<T, n / 2>{}(x * x);
42 }
43};
44
45template <class T> struct int_pow_impl<T, 1> {
46 DEVICE_QUALIFIER constexpr T operator()(T x) const { return x; }
47};
48
49template <class T> struct int_pow_impl<T, 0> {
50 DEVICE_QUALIFIER constexpr T operator()(T) const { return T{1}; }
51};
52} // namespace detail
53
54/**
55 * \brief Calculate integer powers.
56 * This functions calculates x^n, where
57 * n is a positive integer that is known
58 * at compile time. It uses exponentiation by
59 * squaring to construct an efficient function.
60 */
61template <unsigned n, typename T> DEVICE_QUALIFIER constexpr T int_pow(T x) {
62 return detail::int_pow_impl<T, n>{}(x);
63}
64} // namespace Utils
65
66#endif
#define DEVICE_QUALIFIER
DEVICE_QUALIFIER constexpr T int_pow(T x)
Calculate integer powers.
Definition int_pow.hpp:61