Skip to content

Commit 431666c

Browse files
committed
Simplify lucas::decompose() using the new trailing_ones() method
1 parent 2791151 commit 431666c

File tree

1 file changed

+7
-14
lines changed

1 file changed

+7
-14
lines changed

src/hazmat/lucas.rs

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -172,25 +172,17 @@ impl LucasBase for BruteForceBase {
172172
}
173173

174174
/// For the given odd `n`, finds `s` and odd `d` such that `n + 1 == 2^s * d`.
175-
fn decompose<const L: usize>(n: &Uint<L>) -> (u32, Uint<L>) {
175+
fn decompose<const L: usize>(n: &Uint<L>) -> (usize, Uint<L>) {
176176
debug_assert!(bool::from(n.is_odd()));
177177

178178
// Need to be careful here since `n + 1` can overflow.
179179
// Instead of adding 1 and counting trailing 0s, we count trailing ones on the original `n`.
180180

181-
let mut n = *n;
182-
let mut s = 0;
183-
184-
while n.is_odd().into() {
185-
n >>= 1;
186-
s += 1;
187-
}
188-
181+
let s = n.trailing_ones();
189182
// This won't overflow since the original `n` was odd, so we right-shifted at least once.
190-
(
191-
s,
192-
Option::from(n.checked_add(&Uint::<L>::ONE)).expect("Integer overflow"),
193-
)
183+
let d = Option::from((n >> s).checked_add(&Uint::<L>::ONE)).expect("Integer overflow");
184+
185+
(s, d)
194186
}
195187

196188
/// The checks to perform in the Lucas test.
@@ -317,7 +309,8 @@ pub fn lucas_test<const L: usize>(
317309
return Primality::Composite;
318310
}
319311

320-
// Find d and s, such that d is odd and d * 2^s = (n - (D/n)).
312+
// Find `d` and `s`, such that `d` is odd and `d * 2^s = n - (D/n)`.
313+
// Since `(D/n) == -1` by construction, we're looking for `d * 2^s = n + 1`.
321314
let (s, d) = decompose(candidate);
322315

323316
// Some constants in Montgomery form

0 commit comments

Comments
 (0)