TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
modular_exponentiation.cpp
Go to the documentation of this file.
1
19#include <cassert>
20#include <cstdint>
21#include <iostream>
26namespace math {
35uint64_t power(uint64_t a, uint64_t b, uint64_t c) {
36 uint64_t ans = 1;
37 a = a % c;
38 if (a == 0) {
39 return 0;
40 }
41 while (b > 0) {
43 if (b & 1) {
44 ans = ((ans % c) * (a % c)) % c;
45 }
47 b = b >> 1;
48 a = ((a % c) * (a % c)) % c;
49 }
50 return ans;
51}
52
53} // namespace math
54
60static void test() {
61 uint32_t test_case_1 = math::power(2, 5, 13);
62 assert(test_case_1 == 6);
63 std::cout << "Test 1 Passed!" << std::endl;
64
65 uint32_t test_case_2 = math::power(14, 7, 15);
66 assert(test_case_2 == 14);
67 std::cout << "Test 2 Passed!" << std::endl;
68
69 uint64_t test_case_3 = math::power(8, 15, 41);
70 assert(test_case_3 == 32);
71 std::cout << "Test 3 Passed!" << std::endl;
72
73 uint64_t test_case_4 = math::power(27, 2, 5);
74 assert(test_case_4 == 4);
75 std::cout << "Test 4 Passed!" << std::endl;
76
77 uint16_t test_case_5 = math::power(7, 3, 6);
78 assert(test_case_5 == 1);
79 std::cout << "Test 5 Passed!" << std::endl;
80}
81
86int main() {
87 test(); // execute the tests
88 return 0;
89}
static void test()
int main()
Main function.
for assert
uint64_t power(uint64_t a, uint64_t b, uint64_t c)
This function calculates a raised to exponent b under modulo c using modular exponentiation.