SUNphi  1.0
Arithmetic.hpp
Go to the documentation of this file.
1 #ifndef _ARITHMETIC_HPP
2 #define _ARITHMETIC_HPP
3 
4 /// \file Arithmetic.hpp
5 ///
6 /// \brief Defines several template version of simple arithmetic operations
7 ///
8 
9 #include <debug/OptimizationDiagnostic.hpp>
10 
11 namespace SUNphi
12 {
13  /// Modulo operator, based on remainder operator %
14  ///
15  /// Valid on negative and positive numbers
16  ///
17  /// Example:
18  ///
19  /// \code
20  /// safeModulo(5,3); // 2
21  /// safeModulo(-2,3); // 1
22  /// safeModulo(-3,3); // 0
23  /// \endcode
24  ///
25  template <typename T>
26  T safeModulo(const T& val, ///< Value of which to take the modulo
27  const T& mod) ///< Modulo
28  {
29  ASM_BOOKMARK("BEGIN");
30 
31  /// Remainder
32  const T r=
33  val%mod;
34 
35  return
36  (val<0 and r!=0)
37  ?
38  r+mod
39  :
40  r;
41  }
42 
43  /// Square of a number
44  template <typename T>
45  T sqr(const T& x)
46  {
47  return
48  x*x;
49  }
50 
51  /// Sign of a number, +1 0 or -1
52  template <typename T>
53  T sign(const T& x)
54  {
55  // Positive case
56  if(x>0)
57  return +1;
58 
59  // Negative case
60  if(x<0)
61  return -1;
62 
63  // Null case
64  return
65  0;
66  }
67 
68  /// Return greatest common divisor between a and b
69  template <typename I1,
70  typename I2>
71  auto greatestCommonDivisor(const I1& _a,
72  const I2& _b)
73  {
74  /// Inner type to be used
75  using I=
76  decltype(_a/_b);
77 
78  /// Cast to I of \c _a
79  I a=
80  _a;
81 
82  /// Cast to I of \c _b
83  I b=
84  _b;
85 
86  while(a!=0)
87  {
88  /// Store temporarily a
89  const I c=
90  a;
91 
92  a=
93  b%a;
94 
95  b=
96  c;
97  }
98 
99  return
100  b;
101  }
102 
103  /// Return least common multiple between \c a and \c b
104  template <typename I1,
105  typename I2>
106  auto leastCommonMultiple(const I1& a,
107  const I2& b)
108  {
109  return
110  a/greatestCommonDivisor(a,b)*b;
111  }
112 }
113 
114 #endif
T sign(const T &x)
Sign of a number, +1 0 or -1.
Definition: Arithmetic.hpp:53
auto leastCommonMultiple(const I1 &a, const I2 &b)
Return least common multiple between a and b.
Definition: Arithmetic.hpp:106
#define ASM_BOOKMARK(COMMENT)
Include a comment in the assembler, recognizable in the compilation.
T safeModulo(const T &val, const T &mod)
Definition: Arithmetic.hpp:26
T sqr(const T &x)
Square of a number.
Definition: Arithmetic.hpp:45
auto greatestCommonDivisor(const I1 &_a, const I2 &_b)
Return greatest common divisor between a and b.
Definition: Arithmetic.hpp:71