TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
modular_inverse_fermat_little_theorem.cpp
Go to the documentation of this file.
1
45
46
#include <cassert>
47
#include <cstdint>
48
#include <iostream>
49
54
namespace
math
{
59
namespace
modular_inverse_fermat
{
67
std::int64_t
binExpo
(std::int64_t a, std::int64_t b, std::int64_t m) {
68
a %= m;
69
std::int64_t res = 1;
70
while
(b > 0) {
71
if
(b % 2 != 0) {
72
res = res * a % m;
73
}
74
a = a * a % m;
75
// Dividing b by 2 is similar to right shift by 1 bit
76
b >>= 1;
77
}
78
return
res;
79
}
80
86
bool
isPrime
(std::int64_t m) {
87
if
(m <= 1) {
88
return
false
;
89
}
90
for
(std::int64_t i = 2; i * i <= m; i++) {
91
if
(m % i == 0) {
92
return
false
;
93
}
94
}
95
return
true
;
96
}
97
103
std::int64_t
modular_inverse
(std::int64_t a, std::int64_t m) {
104
while
(a < 0) {
105
a += m;
106
}
107
108
// Check for invalid cases
109
if
(!
isPrime
(m) || a == 0) {
110
return
-1;
// Invalid input
111
}
112
113
return
binExpo
(a, m - 2, m);
// Fermat's Little Theorem
114
}
115
}
// namespace modular_inverse_fermat
116
}
// namespace math
117
122
static
void
test
() {
123
assert(
math::modular_inverse_fermat::modular_inverse
(0, 97) == -1);
124
assert(
math::modular_inverse_fermat::modular_inverse
(15, -2) == -1);
125
assert(
math::modular_inverse_fermat::modular_inverse
(3, 10) == -1);
126
assert(
math::modular_inverse_fermat::modular_inverse
(3, 7) == 5);
127
assert(
math::modular_inverse_fermat::modular_inverse
(1, 101) == 1);
128
assert(
math::modular_inverse_fermat::modular_inverse
(-1337, 285179) == 165519);
129
assert(
math::modular_inverse_fermat::modular_inverse
(123456789, 998244353) == 25170271);
130
assert(
math::modular_inverse_fermat::modular_inverse
(-9876543210, 1000000007) == 784794281);
131
}
132
137
int
main
() {
138
test
();
// run self-test implementation
139
return
0;
140
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
math::modular_inverse_fermat::binExpo
std::int64_t binExpo(std::int64_t a, std::int64_t b, std::int64_t m)
Calculate exponent with modulo using binary exponentiation in time.
Definition
modular_inverse_fermat_little_theorem.cpp:67
math::modular_inverse_fermat::isPrime
bool isPrime(std::int64_t m)
Check if an integer is a prime number in time.
Definition
modular_inverse_fermat_little_theorem.cpp:86
math::modular_inverse_fermat::modular_inverse
std::int64_t modular_inverse(std::int64_t a, std::int64_t m)
calculates the modular inverse.
Definition
modular_inverse_fermat_little_theorem.cpp:103
math
for assert
modular_inverse_fermat
Calculate modular inverse using Fermat's Little Theorem.
math
modular_inverse_fermat_little_theorem.cpp
Generated by
1.18.0