|
| 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_PollardRho |
| 22 | +#endif |
| 23 | + |
| 24 | +#ifndef FUNC_PollardRho |
| 25 | +#define FUNC_PollardRho |
| 26 | + |
| 27 | +#include "utils.h" |
| 28 | + |
| 29 | +#include "Euclid.cpp" |
| 30 | + |
| 31 | +template <typename T> |
| 32 | +T abs(T x) { |
| 33 | + if (x < 0) |
| 34 | + return -x; |
| 35 | + else |
| 36 | + return x; |
| 37 | +} |
| 38 | + |
| 39 | +template <typename T> |
| 40 | +T PollardRho(T n) { |
| 41 | + size_t i = 1, k = 2; |
| 42 | + std::random_device rd; |
| 43 | + std::uniform_int_distribution<T> dis(0, n - 1); |
| 44 | + T x = dis(rd), y = x; |
| 45 | + while (i < 1048576) { |
| 46 | + i++; |
| 47 | + x = (x * x - 1) % n; |
| 48 | + T d = Euclid(abs<T>(y - x), n); |
| 49 | + if (d != 1 && d != n) |
| 50 | + return d; |
| 51 | + if (i == k) { |
| 52 | + y = x; |
| 53 | + k *= 2; |
| 54 | + } |
| 55 | + } |
| 56 | + return 0; |
| 57 | +} |
| 58 | +#endif |
| 59 | + |
| 60 | +#ifdef MAIN_PollardRho |
| 61 | +int main(int argc, char *argv[]) { |
| 62 | + const size_t nn = get_argv(argc, argv, 1, 30); |
| 63 | + const size_t tries = get_argv(argc, argv, 2, 1); |
| 64 | + using T = long long int; |
| 65 | + std::random_device rd; |
| 66 | + std::uniform_int_distribution<T> dis(1 << (nn - 1), 1 << nn); |
| 67 | + for (size_t i = 0; i < tries; i++) { |
| 68 | + T n = get_argv(argc, argv, 3 + i, dis(rd) << 1 | 1); |
| 69 | + std::cout << n << "\t" << std::flush << PollardRho(n) << std::endl; |
| 70 | + } |
| 71 | + return 0; |
| 72 | +} |
| 73 | +#endif |
| 74 | + |
0 commit comments