TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
modular_inverse_fermat_little_theorem.cpp
Go to the documentation of this file.
1
46#include <cassert>
47#include <cstdint>
48#include <iostream>
49
54namespace math {
59namespace modular_inverse_fermat {
67std::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}
86bool 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}
103std::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
122static 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
137int main() {
138 test(); // run self-test implementation
139 return 0;
140}
int binExpo(int a, int b)
static void test()
Self-test implementation.
bool isPrime(std::int64_t m)
Check if an integer is a prime number in time.
int main()
Main function.
std::int64_t modular_inverse(std::int64_t a, std::int64_t m)
calculates the modular inverse.
for assert
Calculate modular inverse using Fermat's Little Theorem.