C++ Utilities  4.17.0
Useful C++ classes and routines 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 
12 namespace MathUtilities {
13 
18 int random(int lowerbounds, int upperbounds)
19 {
20  assert(upperbounds - lowerbounds < RAND_MAX);
21  return lowerbounds + std::rand() % (upperbounds - lowerbounds + 1);
22 }
23 
28 int digitsum(int number, int base)
29 {
30  int res = 0;
31  while (number > 0) {
32  res += number % base;
33  number /= base;
34  }
35  return res;
36 }
37 
42 int factorial(int number)
43 {
44  int res = 1;
45  for (int i = 1; i <= number; ++i) {
46  res *= i;
47  }
48  return res;
49 }
50 
55 uint64 powerModulo(const uint64 base, const uint64 exponent, const uint64 module)
56 {
57  uint64 res = 1;
58  for (uint64 mask = 0x8000000000000000; mask; mask >>= 1) {
59  if (mask & exponent) {
60  res *= base;
61  }
62  if (mask != 1) {
63  res *= res;
64  }
65  res %= module;
66  }
67  return res;
68 }
69 
74 int64 inverseModulo(int64 number, int64 module)
75 {
76  int64 y1 = 0, y2 = 1, tmp;
77  while (number != 1) {
78  tmp = y1 - (module / number) * y2;
79  y1 = y2;
80  y2 = tmp;
81  tmp = module % number;
82  module = number;
83  number = tmp;
84  }
85  return y2;
86 }
87 
92 uint64 orderModulo(const uint64 number, const uint64 module)
93 {
94  uint64 order = 1;
95  for (; powerModulo(number, order, module) != 1 && order != module; ++order)
96  ;
97  return order != module ? order : 0;
98 }
99 } // namespace MathUtilities
CPP_UTILITIES_EXPORT int factorial(int number)
Returns the factorial of the given number.
Definition: math.cpp:42
CPP_UTILITIES_EXPORT uint64 orderModulo(uint64 number, uint64 module)
Computes the order of number modulo module.
Definition: math.cpp:92
std::int64_t int64
signed 64-bit integer
Definition: types.h:29
CPP_UTILITIES_EXPORT int64 inverseModulo(int64 number, int64 module)
Computes the inverse of number modulo module.
Definition: math.cpp:74
Contains various mathematical functions.
Definition: math.h:7
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:18
constexpr int i
CPP_UTILITIES_EXPORT int digitsum(int number, int base=10)
Returns the digitsum of the given number using the specified base.
Definition: math.cpp:28
CPP_UTILITIES_EXPORT uint64 powerModulo(uint64 base, uint64 expontent, uint64 module)
Computes base power exponent modulo module.
Definition: math.cpp:55