Skip to content

Commit 92284a1

Browse files
williamfisetclaude
andauthored
Refactor PrimeFactorization: replace trial-division isPrime with Miller-Rabin, add tests (#1312)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 4cbda50 commit 92284a1

File tree

3 files changed

+210
-39
lines changed

3 files changed

+210
-39
lines changed
Lines changed: 109 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,136 @@
1+
/**
2+
* Prime factorization using Pollard's rho algorithm with Miller-Rabin primality testing.
3+
*
4+
* <p>Miller-Rabin with the deterministic witness set {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}
5+
* is guaranteed correct for all n < 3.317 × 10^24, which covers the full range of Java's long.
6+
*
7+
* <p>Time: O(n^(1/4)) expected per factor found
8+
*
9+
* @author William Fiset, william.alexandre.fiset@gmail.com
10+
*/
111
package com.williamfiset.algorithms.math;
212

313
import java.util.ArrayList;
4-
import java.util.PriorityQueue;
14+
import java.util.List;
515

616
public class PrimeFactorization {
717

8-
public static ArrayList<Long> primeFactorization(long n) {
9-
ArrayList<Long> factors = new ArrayList<>();
10-
if (n <= 0) throw new IllegalArgumentException();
11-
else if (n == 1) return factors;
12-
PriorityQueue<Long> divisorQueue = new PriorityQueue<>();
13-
divisorQueue.add(n);
14-
while (!divisorQueue.isEmpty()) {
15-
long divisor = divisorQueue.remove();
16-
if (isPrime(divisor)) {
17-
factors.add(divisor);
18-
continue;
19-
}
20-
long next_divisor = pollardRho(divisor);
21-
if (next_divisor == divisor) {
22-
divisorQueue.add(divisor);
23-
} else {
24-
divisorQueue.add(next_divisor);
25-
divisorQueue.add(divisor / next_divisor);
26-
}
27-
}
18+
/**
19+
* Returns the prime factorization of n. The returned factors are not necessarily sorted.
20+
*
21+
* @throws IllegalArgumentException if n <= 0.
22+
*/
23+
public static List<Long> primeFactorization(long n) {
24+
if (n <= 0)
25+
throw new IllegalArgumentException();
26+
27+
List<Long> factors = new ArrayList<>();
28+
factor(n, factors);
2829
return factors;
2930
}
3031

32+
private static void factor(long n, List<Long> factors) {
33+
if (n == 1)
34+
return;
35+
if (isPrime(n)) {
36+
factors.add(n);
37+
return;
38+
}
39+
long d = pollardRho(n);
40+
factor(d, factors);
41+
factor(n / d, factors);
42+
}
43+
3144
private static long pollardRho(long n) {
32-
if (n % 2 == 0) return 2;
45+
if (n % 2 == 0)
46+
return 2;
3347
long x = 2 + (long) (999999 * Math.random());
3448
long c = 2 + (long) (999999 * Math.random());
3549
long y = x;
3650
long d = 1;
3751
while (d == 1) {
38-
x = (x * x + c) % n;
39-
y = (y * y + c) % n;
40-
y = (y * y + c) % n;
52+
x = mulMod(x, x, n) + c;
53+
if (x >= n)
54+
x -= n;
55+
y = mulMod(y, y, n) + c;
56+
if (y >= n)
57+
y -= n;
58+
y = mulMod(y, y, n) + c;
59+
if (y >= n)
60+
y -= n;
4161
d = gcd(Math.abs(x - y), n);
42-
if (d == n) break;
62+
if (d == n)
63+
break;
4364
}
4465
return d;
4566
}
4667

47-
private static long gcd(long a, long b) {
48-
return b == 0 ? a : gcd(b, a % b);
49-
}
68+
/**
69+
* Deterministic Miller-Rabin primality test, correct for all long values. Uses 12 witnesses that
70+
* guarantee correctness for n < 3.317 × 10^24.
71+
*/
72+
private static boolean isPrime(long n) {
73+
if (n < 2)
74+
return false;
75+
if (n < 4)
76+
return true;
77+
if (n % 2 == 0 || n % 3 == 0)
78+
return false;
79+
80+
// Write n-1 as 2^r * d
81+
long d = n - 1;
82+
int r = Long.numberOfTrailingZeros(d);
83+
d >>= r;
5084

51-
private static boolean isPrime(final long n) {
52-
if (n < 2) return false;
53-
if (n == 2 || n == 3) return true;
54-
if (n % 2 == 0 || n % 3 == 0) return false;
55-
long limit = (long) Math.sqrt(n);
56-
for (long i = 5; i <= limit; i += 6) if (n % i == 0 || n % (i + 2) == 0) return false;
85+
for (long a : new long[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
86+
if (a >= n)
87+
continue;
88+
long x = powMod(a, d, n);
89+
if (x == 1 || x == n - 1)
90+
continue;
91+
boolean composite = true;
92+
for (int i = 0; i < r - 1; i++) {
93+
x = mulMod(x, x, n);
94+
if (x == n - 1) {
95+
composite = false;
96+
break;
97+
}
98+
}
99+
if (composite)
100+
return false;
101+
}
57102
return true;
58103
}
59104

105+
/** Modular exponentiation: (base^exp) % mod, using mulMod to avoid overflow. */
106+
private static long powMod(long base, long exp, long mod) {
107+
long result = 1;
108+
base %= mod;
109+
while (exp > 0) {
110+
if ((exp & 1) == 1)
111+
result = mulMod(result, base, mod);
112+
exp >>= 1;
113+
base = mulMod(base, base, mod);
114+
}
115+
return result;
116+
}
117+
118+
/** Overflow-safe modular multiplication: (a * b) % mod. */
119+
private static long mulMod(long a, long b, long mod) {
120+
return java.math.BigInteger.valueOf(a)
121+
.multiply(java.math.BigInteger.valueOf(b))
122+
.mod(java.math.BigInteger.valueOf(mod))
123+
.longValue();
124+
}
125+
126+
private static long gcd(long a, long b) {
127+
return b == 0 ? a : gcd(b, a % b);
128+
}
129+
60130
public static void main(String[] args) {
61-
System.out.println(primeFactorization(7)); // [7]
62-
System.out.println(primeFactorization(100)); // [2,2,5,5]
63-
System.out.println(primeFactorization(666)); // [2,3,3,37]
64-
System.out.println(primeFactorization(872342345)); // [5, 7, 7, 67, 19, 2797]
131+
System.out.println(primeFactorization(7)); // [7]
132+
System.out.println(primeFactorization(100)); // [2, 2, 5, 5]
133+
System.out.println(primeFactorization(666)); // [2, 3, 3, 37]
134+
System.out.println(primeFactorization(872342345)); // [5, 7, 7, 19, 67, 2797]
65135
}
66136
}

src/test/java/com/williamfiset/algorithms/math/BUILD

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,17 @@ java_test(
2626
deps = TEST_DEPS,
2727
)
2828

29+
# bazel test //src/test/java/com/williamfiset/algorithms/math:PrimeFactorizationTest
30+
java_test(
31+
name = "PrimeFactorizationTest",
32+
srcs = ["PrimeFactorizationTest.java"],
33+
main_class = "org.junit.platform.console.ConsoleLauncher",
34+
use_testrunner = False,
35+
args = ["--select-class=com.williamfiset.algorithms.math.PrimeFactorizationTest"],
36+
runtime_deps = JUNIT5_RUNTIME_DEPS,
37+
deps = TEST_DEPS,
38+
)
39+
2940
# bazel test //src/test/java/com/williamfiset/algorithms/math:EulerTotientFunctionTest
3041
java_test(
3142
name = "EulerTotientFunctionTest",
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package com.williamfiset.algorithms.math;
2+
3+
import static com.google.common.truth.Truth.assertThat;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import java.util.*;
7+
import org.junit.jupiter.api.*;
8+
9+
public class PrimeFactorizationTest {
10+
11+
private static void assertFactors(long n, Long... expected) {
12+
List<Long> factors = PrimeFactorization.primeFactorization(n);
13+
Collections.sort(factors);
14+
assertThat(factors).containsExactlyElementsIn(Arrays.asList(expected)).inOrder();
15+
}
16+
17+
@Test
18+
public void testOne() {
19+
assertFactors(1);
20+
}
21+
22+
@Test
23+
public void testSmallPrimes() {
24+
assertFactors(2, 2L);
25+
assertFactors(3, 3L);
26+
assertFactors(5, 5L);
27+
assertFactors(7, 7L);
28+
assertFactors(11, 11L);
29+
assertFactors(13, 13L);
30+
}
31+
32+
@Test
33+
public void testPowersOfTwo() {
34+
assertFactors(4, 2L, 2L);
35+
assertFactors(8, 2L, 2L, 2L);
36+
assertFactors(1024, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L);
37+
}
38+
39+
@Test
40+
public void testPrimePowers() {
41+
assertFactors(27, 3L, 3L, 3L);
42+
assertFactors(125, 5L, 5L, 5L);
43+
assertFactors(49, 7L, 7L);
44+
}
45+
46+
@Test
47+
public void testComposites() {
48+
assertFactors(100, 2L, 2L, 5L, 5L);
49+
assertFactors(666, 2L, 3L, 3L, 37L);
50+
assertFactors(872342345, 5L, 7L, 7L, 19L, 67L, 2797L);
51+
}
52+
53+
@Test
54+
public void testProductEqualsOriginal() {
55+
long[] values = {12, 360, 872342345, 1000000007, 239821585064027L};
56+
for (long n : values) {
57+
List<Long> factors = PrimeFactorization.primeFactorization(n);
58+
long product = 1;
59+
for (long f : factors)
60+
product *= f;
61+
assertThat(product).isEqualTo(n);
62+
}
63+
}
64+
65+
@Test
66+
public void testLargePrime() {
67+
assertFactors(8763857775536878331L, 8763857775536878331L);
68+
}
69+
70+
@Test
71+
public void testLargeSemiprime() {
72+
// 15485867 and 15486481 are both prime
73+
assertFactors(239821585064027L, 15485867L, 15486481L);
74+
}
75+
76+
@Test
77+
public void testLargeComposite() {
78+
assertFactors(1000000007L * 999999937L, 999999937L, 1000000007L);
79+
}
80+
81+
@Test
82+
public void testZeroThrows() {
83+
assertThrows(IllegalArgumentException.class, () -> PrimeFactorization.primeFactorization(0));
84+
}
85+
86+
@Test
87+
public void testNegativeThrows() {
88+
assertThrows(IllegalArgumentException.class, () -> PrimeFactorization.primeFactorization(-5));
89+
}
90+
}

0 commit comments

Comments
 (0)