Skip to content

Commit c0bad7d

Browse files
committed
improve factor() performance
1 parent dad878d commit c0bad7d

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

src/main/java/de/tilman_neumann/jml/factor/tdiv/TDiv31Barrett.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,13 @@ public void factor(BigInteger Nbig, int Nexp, SortedMultiset<BigInteger> primeFa
8585
int q;
8686
for (int i=1; ; i++) {
8787
final int p = primes[i];
88+
int exp = 0;
8889
while ((q = (1 + (int) ((N*pinv[i])>>32))) * p == N) {
89-
primeFactors.add(BigInteger.valueOf(p), Nexp);
90-
N = q;
90+
exp++;
91+
N = q; // avoiding a division here by storing q benefits the int version but not the long version
92+
}
93+
if (exp > 0) {
94+
primeFactors.add(BigInteger.valueOf(p), exp*Nexp);
9195
}
9296
// for random composite N, it is much much faster to check the termination condition after each p;
9397
// for semiprime N, it would be ~40% faster to do it only after sucessful divisions

src/main/java/de/tilman_neumann/jml/factor/tdiv/TDiv31Inverse.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,14 @@ public void factor(BigInteger Nbig, int Nexp, SortedMultiset<BigInteger> primeFa
7676
int q;
7777
for (int i=0; ; i++) {
7878
final int p = primes[i];
79+
int exp = 0;
7980
while ((q = (int) (N*reciprocals[i] + DISCRIMINATOR)) * p == N) {
80-
primeFactors.add(BigInteger.valueOf(p), Nexp);
81+
exp++;
8182
N = q; // avoiding a division here by storing q benefits the int version but not the long version
8283
}
84+
if (exp > 0) {
85+
primeFactors.add(BigInteger.valueOf(p), exp*Nexp);
86+
}
8387
// for random composite N, it is much much faster to check the termination condition after each p;
8488
// for semiprime N, it would be ~40% faster to do it only after sucessful divisions
8589
if (((long)p) * p > N) { // move p as long into registers makes a performance difference

0 commit comments

Comments
 (0)