|
| 1 | +// |
| 2 | +// algorithm - some algorithms in "Introduction to Algorithms", third edition |
| 3 | +// Copyright (C) 2018 lxylxy123456 |
| 4 | +// |
| 5 | +// This program is free software: you can redistribute it and/or modify |
| 6 | +// it under the terms of the GNU Affero General Public License as |
| 7 | +// published by the Free Software Foundation, either version 3 of the |
| 8 | +// License, or (at your option) any later version. |
| 9 | +// |
| 10 | +// This program is distributed in the hope that it will be useful, |
| 11 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +// GNU Affero General Public License for more details. |
| 14 | +// |
| 15 | +// You should have received a copy of the GNU Affero General Public License |
| 16 | +// along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | +// |
| 18 | + |
| 19 | +#ifndef MAIN |
| 20 | +#define MAIN |
| 21 | +#define MAIN_ModularExponentiation |
| 22 | +#endif |
| 23 | + |
| 24 | +#ifndef FUNC_ModularExponentiation |
| 25 | +#define FUNC_ModularExponentiation |
| 26 | + |
| 27 | +#include "utils.h" |
| 28 | + |
| 29 | +#include "Euclid.cpp" |
| 30 | + |
| 31 | +template <typename T> |
| 32 | +T ModularExponentiation(T a, T b, T n) { |
| 33 | + T c = 0; |
| 34 | + T d = 1; |
| 35 | + for (T i = log2(b); i >= 0; i--) { |
| 36 | + c *= 2; |
| 37 | + d = d * d % n; |
| 38 | + if (b & 1 << i) { |
| 39 | + c++; |
| 40 | + d = d * a % n; |
| 41 | + } |
| 42 | + } |
| 43 | + assert(c == b); |
| 44 | + return d; |
| 45 | +} |
| 46 | +#endif |
| 47 | + |
| 48 | +#ifdef MAIN_ModularExponentiation |
| 49 | +int main(int argc, char *argv[]) { |
| 50 | + const size_t nn = get_argv(argc, argv, 1, 4); |
| 51 | + using T = long long int; |
| 52 | + std::random_device rd; |
| 53 | + std::uniform_int_distribution<T> dis(0, 1 << nn); |
| 54 | + std::uniform_int_distribution<T> disn(1, 1 << nn); |
| 55 | + T a = get_argv(argc, argv, 2, dis(rd)); |
| 56 | + T b = get_argv(argc, argv, 3, dis(rd)); |
| 57 | + T n = get_argv(argc, argv, 4, disn(rd)); |
| 58 | + T ans = ModularExponentiation(a, b, n); |
| 59 | + std::cout << a << " ** " << b << " % " << n << " = " << ans << std::endl; |
| 60 | + return 0; |
| 61 | +} |
| 62 | +#endif |
| 63 | + |
0 commit comments