snippets 0.1.0
Loading...
Searching...
No Matches
modular_arithmetic.hpp
Go to the documentation of this file.
1#ifndef MODULAR_ARITHMETIC_H
2#define MODULAR_ARITHMETIC_H
3
4#include <cstdint>
5#include <array>
6
7namespace hsc_snippets
8{
9
10 static constexpr int MODULO = static_cast<int>(1e9 + 7);
11
12 constexpr int modular_add(int x, int y)
13 {
14 auto a = static_cast<std::int64_t>(x);
15 auto b = static_cast<std::int64_t>(y);
16 auto c = (a + b) % MODULO;
17 return static_cast<int>(c);
18 }
19
20 constexpr int additive_inverse(int x)
21 {
22 x = x % MODULO; // x might be negative
23 x = (x + MODULO) % MODULO;
24 return MODULO - x;
25 }
26
27 constexpr int modular_subtract(int x, int y)
28 {
29 auto a = static_cast<std::int64_t>(x);
30 auto b = static_cast<std::int64_t>(y);
31 auto c = (a - b);
32 c = c % MODULO;
33 c = (c + MODULO) % MODULO;
34 return static_cast<int>(c);
35 }
36
37 constexpr int modular_multiply(int x, int y)
38 {
39 auto a = static_cast<std::int64_t>(x);
40 auto b = static_cast<std::int64_t>(y);
41 auto c = (a * b) % MODULO;
42 return static_cast<int>(c);
43 }
44
45 constexpr int modular_square(int x)
46 {
47 auto a = static_cast<int64_t>(x);
48 auto b = (a * a) % MODULO;
49 return static_cast<int>(b);
50 }
51
52 constexpr int modular_cube(int x)
53 {
54 auto a = static_cast<int64_t>(x);
55 auto b = (a * a) % MODULO;
56 auto c = (b * a) % MODULO;
57 return static_cast<int>(c);
58 }
59
60 // Base 2 exponentiation % MODULO
61 static int modular_pow2(size_t exponent)
62 {
63 constexpr size_t N = 25;
64 constexpr auto lookup{[]() constexpr
65 {
66 std::array<int, N> a{};
67 a[0] = 1;
68 for (size_t i = 1; i < N; i++)
69 {
70 a[i] = a[i - 1] << 1;
71 }
72 return a;
73 }()};
74 if (exponent < N)
75 {
76 return lookup[exponent] % MODULO;
77 }
78 auto half_e = exponent >> 1;
79 auto tmp = static_cast<std::int64_t>(modular_pow2(half_e));
80 auto m = (exponent & 1);
81 return ((tmp * tmp) << m) % MODULO;
82 }
83
84}
85
86#endif
Definition big_integer.hpp:14
constexpr int modular_subtract(int x, int y)
Definition modular_arithmetic.hpp:27
static constexpr int MODULO
Definition modular_arithmetic.hpp:10
constexpr int modular_multiply(int x, int y)
Definition modular_arithmetic.hpp:37
constexpr int modular_cube(int x)
Definition modular_arithmetic.hpp:52
constexpr int additive_inverse(int x)
Definition modular_arithmetic.hpp:20
constexpr int modular_add(int x, int y)
Definition modular_arithmetic.hpp:12
static int modular_pow2(size_t exponent)
Definition modular_arithmetic.hpp:61
constexpr int modular_square(int x)
Definition modular_arithmetic.hpp:45