Skip to content
This repository was archived by the owner on Nov 29, 2020. It is now read-only.

Commit 29c2741

Browse files
committed
ModLinEquationSolver.cpp
1 parent fb6cdf9 commit 29c2741

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

ModLinEquationSolver.cpp

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@
199199
| 30 | IterativeFFT.cpp | Bit Reversal Copy | 918 |
200200
| 31 | Euclid.cpp | Euclid | 935 |
201201
| 31 | Euclid.cpp | Extended Euclid | 937 |
202+
| 31 | ModLinEquationSolver.cpp | Modular Linear Equation Solver | 949 |
202203

203204
# Supplementary Files
204205
* `utils.h`: Utils

0 commit comments

Comments
 (0)