Skip to content

Commit 0c66176

Browse files
committed
Pre-compute reciprocals for sieving
1 parent f2d0556 commit 0c66176

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

src/hazmat/precomputed.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1+
use crypto_bigint::{Limb, Reciprocal, Word};
2+
13
/// The type that fits any small prime from the table.
24
pub(crate) type SmallPrime = u16;
35

6+
const SMALL_PRIMES_SIZE: usize = 2047;
7+
48
/// The list of 2nd to 2048th primes (The 1st one, 2, is not included).
5-
pub(crate) const SMALL_PRIMES: [SmallPrime; 2047] = [
9+
pub(crate) const SMALL_PRIMES: [SmallPrime; SMALL_PRIMES_SIZE] = [
610
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
711
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
812
197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307,
@@ -142,3 +146,15 @@ pub(crate) const SMALL_PRIMES: [SmallPrime; 2047] = [
142146
17599, 17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, 17707, 17713, 17729, 17737,
143147
17747, 17749, 17761, 17783, 17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863,
144148
];
149+
150+
const fn create_reciprocals() -> [Reciprocal; SMALL_PRIMES_SIZE] {
151+
let mut arr = [Reciprocal::default(); SMALL_PRIMES_SIZE];
152+
let mut i = 0;
153+
while i < SMALL_PRIMES_SIZE {
154+
arr[i] = Reciprocal::ct_new(Limb(SMALL_PRIMES[i] as Word)).0;
155+
i += 1;
156+
}
157+
arr
158+
}
159+
160+
pub(crate) const RECIPROCALS: [Reciprocal; SMALL_PRIMES_SIZE] = create_reciprocals();

src/hazmat/sieve.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crypto_bigint::{Integer, Limb, NonZero, Random, Uint, Zero};
77
use rand_core::CryptoRngCore;
88

99
use crate::hazmat::{
10-
precomputed::{SmallPrime, SMALL_PRIMES},
10+
precomputed::{SmallPrime, RECIPROCALS, SMALL_PRIMES},
1111
Primality,
1212
};
1313

@@ -151,10 +151,8 @@ impl<const L: usize> Sieve<L> {
151151
self.incr = 0;
152152

153153
// Re-calculate residues.
154-
for (i, small_prime) in SMALL_PRIMES.iter().enumerate().take(self.residues.len()) {
155-
let (_quo, rem) = self
156-
.base
157-
.div_rem_limb(NonZero::new(Limb::from(*small_prime)).unwrap());
154+
for (i, rec) in RECIPROCALS.iter().enumerate().take(self.residues.len()) {
155+
let (_quo, rem) = self.base.ct_div_rem_limb_with_reciprocal(rec);
158156
self.residues[i] = rem.0 as SmallPrime;
159157
}
160158

0 commit comments

Comments
 (0)