TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
modular_division.cpp
Go to the documentation of this file.
1
27#include <cassert>
28#include <cstdint>
29#include <iostream>
30
35namespace math {
41namespace modular_division {
50uint64_t power(uint64_t a, uint64_t b, uint64_t c) {
51 uint64_t ans = 1;
52 a = a % c;
53 if (a == 0) {
54 return 0;
55 }
56 while (b > 0) {
58 if (b & 1) {
59 ans = ((ans % c) * (a % c)) % c;
60 }
62 b = b >> 1;
63 a = ((a % c) * (a % c)) % c;
64 }
65 return ans;
66}
67
75uint64_t mod_division(uint64_t a, uint64_t b, uint64_t p) {
76 uint64_t inverse = power(b, p - 2, p) % p;
77 uint64_t result =
78 ((a % p) * (inverse % p)) % p;
79 return result;
80}
81} // namespace modular_division
82} // namespace math
83
89static void test() {
90 uint64_t test_case_1 = math::modular_division::mod_division(8, 2, 2);
91 assert(test_case_1 == 0);
92 std::cout << "Test 1 Passed!" << std::endl;
93 uint64_t test_case_2 = math::modular_division::mod_division(15, 3, 7);
94 assert(test_case_2 == 5);
95 std::cout << "Test 2 Passed!" << std::endl;
96 uint64_t test_case_3 = math::modular_division::mod_division(10, 5, 2);
97 assert(test_case_3 == 0);
98 std::cout << "Test 3 Passed!" << std::endl;
99 uint64_t test_case_4 = math::modular_division::mod_division(81, 3, 5);
100 assert(test_case_4 == 2);
101 std::cout << "Test 4 Passed!" << std::endl;
102 uint64_t test_case_5 = math::modular_division::mod_division(12848, 73, 29);
103 assert(test_case_5 == 2);
104 std::cout << "Test 5 Passed!" << std::endl;
105}
106
113int main(int argc, char *argv[]) {
114 test(); // execute the tests
115 return 0;
116}
int main()
Main function.
uint64_t mod_division(uint64_t a, uint64_t b, uint64_t p)
This function calculates modular division.
static void test()
for assert
Functions for Modular Division implementation.