MLIB
Loading...
Searching...
No Matches
ipow.h
Go to the documentation of this file.
1/*
2 Copyright (c) Mircea Neacsu (2014-2025) Licensed under MIT License.
3 This file is part of MLIB project. See LICENSE file for full license terms.
4*/
5
7
8#pragma once
9
10#if __has_include("defs.h")
11#include "defs.h"
12#endif
13#include <assert.h>
14
15namespace mlib {
16
18template <typename T>
19T ipow (T base, int exp)
20{
21 assert (exp >= 0);
22 T result = 1;
23 while (exp)
24 {
25 if (exp & 1)
26 result *= base;
27 exp >>= 1;
28 base *= base;
29 }
30 return result;
31}
32
34template <>
35inline double ipow (double base, int exp)
36{
37 if (exp < 0)
38 {
39 base = 1. / base;
40 exp = -exp;
41 }
42 double result = 1;
43 while (exp)
44 {
45 if (exp & 1)
46 result *= base;
47 exp >>= 1;
48 base *= base;
49 }
50 return result;
51}
52
54template <typename T>
55inline T squared (T base)
56{
57 return base * base;
58}
59
61template <typename T>
62inline T cubed (T base)
63{
64 return base * base * base;
65}
66
67
68} // namespace mlib
T ipow(T base, int exp)
Integer exponentiation function.
Definition ipow.h:19
T squared(T base)
Return squared value of argument: base²
Definition ipow.h:55
T cubed(T base)
Return the cubed value of argument: base³
Definition ipow.h:62