|
| 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_ModLinEquationSolver |
| 22 | +#endif |
| 23 | + |
| 24 | +#ifndef FUNC_ModLinEquationSolver |
| 25 | +#define FUNC_ModLinEquationSolver |
| 26 | + |
| 27 | +#include "utils.h" |
| 28 | + |
| 29 | +#include "Euclid.cpp" |
| 30 | + |
| 31 | +template <typename T> |
| 32 | +void ModularLinearEquationSolver(T a, T b, T n, std::vector<T>& ans) { |
| 33 | + T x, y; |
| 34 | + T d = ExtendedEuclid(a, n, x, y); |
| 35 | + if (b % d == 0) { |
| 36 | + T x0 = x * (b / d) % n; |
| 37 | + ans.reserve(d); |
| 38 | + for (T i = 0; i < d; i++) |
| 39 | + ans.push_back(((x0 + i * (n / d)) % n + n) % n); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +#endif |
| 44 | + |
| 45 | +#ifdef MAIN_ModLinEquationSolver |
| 46 | +int main(int argc, char *argv[]) { |
| 47 | + const size_t nn = get_argv(argc, argv, 1, 4); |
| 48 | + using T = long long int; |
| 49 | + std::random_device rd; |
| 50 | + std::uniform_int_distribution<T> dis(0, 1 << nn); |
| 51 | + T a = get_argv(argc, argv, 2, dis(rd)); |
| 52 | + T b = get_argv(argc, argv, 3, dis(rd)); |
| 53 | + T n = get_argv(argc, argv, 4, dis(rd)); |
| 54 | + std::vector<T> ans; |
| 55 | + ModularLinearEquationSolver(a, b, n, ans); |
| 56 | + std::cout << a << " * x === " << b << " (mod " << n << ")" << std::endl; |
| 57 | + if (ans.size()) { |
| 58 | + std::cout << "x = "; |
| 59 | + output_integers(ans); |
| 60 | + } else |
| 61 | + std::cout << "no solutions" << std::endl; |
| 62 | + return 0; |
| 63 | +} |
| 64 | +#endif |
| 65 | + |
0 commit comments