Skip to content

Commit 2c4e5c9

Browse files
Merge pull request #277 from bad-eastwind/master
pollardrho_eastwind.cpp
2 parents a68bc45 + 2e33795 commit 2c4e5c9

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

pollardrho.cpp

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/* C++ program to find a prime factor of composite using
2+
Pollard's Rho algorithm */
3+
#include<bits/stdc++.h>
4+
using namespace std;
5+
6+
/* Function to calculate (base^exponent)%modulus */
7+
long long int modular_pow(long long int base, int exponent,
8+
long long int modulus)
9+
{
10+
/* initialize result */
11+
long long int result = 1;
12+
13+
while (exponent > 0)
14+
{
15+
/* if y is odd, multiply base with result */
16+
if (exponent & 1)
17+
result = (result * base) % modulus;
18+
19+
/* exponent = exponent/2 */
20+
exponent = exponent >> 1;
21+
22+
/* base = base * base */
23+
base = (base * base) % modulus;
24+
}
25+
return result;
26+
}
27+
28+
/* method to return prime divisor for n */
29+
long long int PollardRho(long long int n)
30+
{
31+
/* initialize random seed */
32+
srand (time(NULL));
33+
34+
/* no prime divisor for 1 */
35+
if (n==1) return n;
36+
37+
/* even number means one of the divisors is 2 */
38+
if (n % 2 == 0) return 2;
39+
40+
/* we will pick from the range [2, N) */
41+
long long int x = (rand()%(n-2))+2;
42+
long long int y = x;
43+
44+
/* the constant in f(x).
45+
* Algorithm can be re-run with a different c
46+
* if it throws failure for a composite. */
47+
long long int c = (rand()%(n-1))+1;
48+
49+
/* Initialize candidate divisor (or result) */
50+
long long int d = 1;
51+
52+
/* until the prime factor isn't obtained.
53+
If n is prime, return n */
54+
while (d==1)
55+
{
56+
/* Tortoise Move: x(i+1) = f(x(i)) */
57+
x = (modular_pow(x, 2, n) + c + n)%n;
58+
59+
/* Hare Move: y(i+1) = f(f(y(i))) */
60+
y = (modular_pow(y, 2, n) + c + n)%n;
61+
y = (modular_pow(y, 2, n) + c + n)%n;
62+
63+
/* check gcd of |x-y| and n */
64+
d = __gcd(abs(x-y), n);
65+
66+
/* retry if the algorithm fails to find prime factor
67+
* with chosen x and c */
68+
if (d==n) return PollardRho(n);
69+
}
70+
71+
return d;
72+
}
73+
74+
/* driver function */
75+
int main()
76+
{
77+
long long int n = 10967535067;
78+
printf("One of the divisors for %lld is %lld.",
79+
n, PollardRho(n));
80+
return 0;
81+
}

0 commit comments

Comments
 (0)