C++ Utilities  4.9.0
Common C++ classes and routines used by my applications such as argument parser, IO and conversion utilities
math.cpp
Go to the documentation of this file.
1 #include "./math.h"
2 
3 #include <cassert>
4 #include <cstdlib>
5 
15 int MathUtilities::random(int lowerbounds, int upperbounds)
16 {
17  assert(upperbounds - lowerbounds < RAND_MAX);
18  return lowerbounds + std::rand() % (upperbounds - lowerbounds + 1);
19 }
20 
24 int MathUtilities::digitsum(int number, int base)
25 {
26  int res = 0;
27  while (number > 0) {
28  res += number % base;
29  number /= base;
30  }
31  return res;
32 }
33 
37 int MathUtilities::factorial(int number)
38 {
39  int res = 1;
40  for (int i = 1; i <= number; ++i) {
41  res *= i;
42  }
43  return res;
44 }
45 
49 uint64 powerModulo(const uint64 base, const uint64 exponent, const uint64 module)
50 {
51  uint64 res = 1;
52  for (uint64 mask = 0x8000000000000000; mask; mask >>= 1) {
53  if (mask & exponent) {
54  res *= base;
55  }
56  if (mask != 1) {
57  res *= res;
58  }
59  res %= module;
60  }
61  return res;
62 }
63 
67 int64 inverseModulo(int64 number, int64 module)
68 {
69  int64 y1 = 0, y2 = 1, tmp;
70  while (number != 1) {
71  tmp = y1 - (module / number) * y2;
72  y1 = y2;
73  y2 = tmp;
74  tmp = module % number;
75  module = number;
76  number = tmp;
77  }
78  return y2;
79 }
80 
84 uint64 orderModulo(const uint64 number, const uint64 module)
85 {
86  uint64 order = 1;
87  for (; powerModulo(number, order, module) != 1; ++order)
88  ;
89  return order;
90 }
CPP_UTILITIES_EXPORT int factorial(int number)
Returns the factorial of the given number.
Definition: math.cpp:37
int64 inverseModulo(int64 number, int64 module)
Computes the inverse of number modulo module.
Definition: math.cpp:67
std::int64_t int64
signed 64-bit integer
Definition: types.h:29
std::uint64_t uint64
unsigned 64-bit integer
Definition: types.h:49
CPP_UTILITIES_EXPORT int random(int lowerbounds, int upperbounds)
Returns a pseudo random number between lowerbounds and upperbounds.
Definition: math.cpp:15
uint64 orderModulo(const uint64 number, const uint64 module)
Computes the order of number modulo module.
Definition: math.cpp:84
uint64 powerModulo(const uint64 base, const uint64 exponent, const uint64 module)
Computes base power exponent modulo module.
Definition: math.cpp:49
CPP_UTILITIES_EXPORT int digitsum(int number, int base=10)
Returns the digitsum of the given number using the specified base.
Definition: math.cpp:24