C++ Utilities  4.12.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 
11 namespace MathUtilities {
12 
17 int random(int lowerbounds, int upperbounds)
18 {
19  assert(upperbounds - lowerbounds < RAND_MAX);
20  return lowerbounds + std::rand() % (upperbounds - lowerbounds + 1);
21 }
22 
26 int digitsum(int number, int base)
27 {
28  int res = 0;
29  while (number > 0) {
30  res += number % base;
31  number /= base;
32  }
33  return res;
34 }
35 
39 int factorial(int number)
40 {
41  int res = 1;
42  for (int i = 1; i <= number; ++i) {
43  res *= i;
44  }
45  return res;
46 }
47 
51 uint64 powerModulo(const uint64 base, const uint64 exponent, const uint64 module)
52 {
53  uint64 res = 1;
54  for (uint64 mask = 0x8000000000000000; mask; mask >>= 1) {
55  if (mask & exponent) {
56  res *= base;
57  }
58  if (mask != 1) {
59  res *= res;
60  }
61  res %= module;
62  }
63  return res;
64 }
65 
69 int64 inverseModulo(int64 number, int64 module)
70 {
71  int64 y1 = 0, y2 = 1, tmp;
72  while (number != 1) {
73  tmp = y1 - (module / number) * y2;
74  y1 = y2;
75  y2 = tmp;
76  tmp = module % number;
77  module = number;
78  number = tmp;
79  }
80  return y2;
81 }
82 
86 uint64 orderModulo(const uint64 number, const uint64 module)
87 {
88  uint64 order = 1;
89  for (; powerModulo(number, order, module) != 1 && order != module; ++order)
90  ;
91  return order != module ? order : 0;
92 }
93 } // namespace MathUtilities
CPP_UTILITIES_EXPORT int factorial(int number)
Returns the factorial of the given number.
Definition: math.cpp:39
CPP_UTILITIES_EXPORT uint64 orderModulo(uint64 number, uint64 module)
Computes the order of number modulo module.
Definition: math.cpp:86
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:69
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:17
CPP_UTILITIES_EXPORT int digitsum(int number, int base=10)
Returns the digitsum of the given number using the specified base.
Definition: math.cpp:26
CPP_UTILITIES_EXPORT uint64 powerModulo(uint64 base, uint64 expontent, uint64 module)
Computes base power exponent modulo module.
Definition: math.cpp:51