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

Commit 92354d1

Browse files
committed
PollardRho.cpp
1 parent 561c1bb commit 92354d1

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

PollardRho.cpp

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

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@
204204
| 31 | Pseudoprime.cpp | Pseudoprime | 967 |
205205
| 31 | MillerRabin.cpp | Witness | 969 |
206206
| 31 | MillerRabin.cpp | Miller Rabin | 970 |
207+
| 31 | PollardRho.cpp | Pollard Rho | 977 |
207208

208209
# Supplementary Files
209210
* `utils.h`: Utils

0 commit comments

Comments
 (0)