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