26
26
/**
27
27
* Brents's improvement of Pollard's Rho algorithm, following [Richard P. Brent: An improved Monte Carlo Factorization Algorithm, 1980].
28
28
*
29
+ * Improvement by Dave McGuigan:
30
+ * Use squareAddModN() instead of nested addModN(squareModN())
31
+ *
29
32
* @author Tilman Neumann
30
33
*/
31
34
public class PollardRhoBrent extends FactorAlgorithm {
@@ -60,14 +63,14 @@ public BigInteger findSingleFactor(BigInteger N) {
60
63
do {
61
64
x = y ;
62
65
for (int i =1 ; i <=r ; i ++) {
63
- y = addModN ( y . multiply ( y ). mod ( N ) , c );
66
+ y = squareAddModN ( y , c );
64
67
}
65
68
int k = 0 ;
66
69
do {
67
70
ys = y ;
68
71
final int iMax = Math .min (m , r -k );
69
72
for (int i =1 ; i <=iMax ; i ++) {
70
- y = addModN ( y . multiply ( y ). mod ( N ) , c );
73
+ y = squareAddModN ( y , c );
71
74
final BigInteger diff = x .compareTo (y ) < 0 ? y .subtract (x ) : x .subtract (y );
72
75
q = diff .multiply (q ).mod (N );
73
76
}
@@ -81,7 +84,7 @@ public BigInteger findSingleFactor(BigInteger N) {
81
84
} while (G .equals (I_1 ));
82
85
if (G .equals (N )) {
83
86
do {
84
- ys = addModN (ys . multiply ( ys ). mod ( N ) , c );
87
+ ys = squareAddModN (ys , c );
85
88
final BigInteger diff = x .compareTo (ys ) < 0 ? ys .subtract (x ) : x .subtract (ys );
86
89
G = diff .gcd (N );
87
90
} while (G .equals (I_1 ));
@@ -91,15 +94,14 @@ public BigInteger findSingleFactor(BigInteger N) {
91
94
if (DEBUG ) LOG .debug ("Found factor of " + N + " = " + G );
92
95
return G ;
93
96
}
94
-
97
+
95
98
/**
96
- * Addition modulo N, with <code>a, b < N</code>.
97
- * @param a
98
- * @param b
99
- * @return (a+b ) mod N
99
+ * Square and add modulo N, with <code>a, b < N</code>.
100
+ * @param y
101
+ * @param c
102
+ * @return () mod N
100
103
*/
101
- private BigInteger addModN (BigInteger a , BigInteger b ) {
102
- BigInteger sum = a .add (b );
103
- return sum .compareTo (N )<0 ? sum : sum .subtract (N );
104
+ private BigInteger squareAddModN (BigInteger y , BigInteger c ) {
105
+ return y .multiply (y ).add (c ).mod (N );
104
106
}
105
107
}
0 commit comments