Skip to content

Commit

Permalink
möbius(0) is well defined, so just take a u64 instead of a NonZeroU64
Browse files Browse the repository at this point in the history
  • Loading branch information
JSorngard committed Oct 13, 2023
1 parent 22f755b commit 7c2ffc3
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 11 deletions.
4 changes: 1 addition & 3 deletions benches/prime_benches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ fn benchmarks(c: &mut Criterion) {
b.iter(|| black_box(are_prime::<10_000>()))
});

let ints: Vec<_> = (1..1_000_000)
.map(|n| core::num::NonZeroU64::new(n).unwrap())
.collect();
let ints: Vec<_> = (1..1_000_000).map(|n| n).collect();
c.bench_function("möbius of first 1e6 integers", |b| {
b.iter(|| {
for &i in &ints {
Expand Down
13 changes: 5 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,13 +347,11 @@ pub const fn are_prime<const N: usize>() -> [bool; N] {
/// # Example
/// ```
/// # use const_primes::moebius;
/// use core::num::NonZeroU64;
/// const N: NonZeroU64 = match NonZeroU64::new(1001) {Some(i) => i, None => panic!()};
/// const N: u64 = 1001;
/// const MÖBIUS1001: i8 = moebius(N);
/// assert_eq!(MÖBIUS1001, -1);
/// ```
pub const fn moebius(x: core::num::NonZeroU64) -> i8 {
let mut x = x.get();
pub const fn moebius(mut x: u64) -> i8 {
let mut prime_count: u64 = 0;

// We avoid code repetition with the use of this macro.
Expand Down Expand Up @@ -531,16 +529,15 @@ mod test {

#[test]
fn check_möbius() {
use core::num::NonZeroU64;
#[rustfmt::skip]
const TEST_CASES: [i8; 50] = [1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, 0, 1, 1, -1, 0, 0, 1, 0, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 0, 1, -1, 0, 0, 0];
const TEST_CASES: [i8; 51] = [0, 1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, 0, 1, 1, -1, 0, 0, 1, 0, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 0, 1, -1, 0, 0, 0];
for (n, ans) in TEST_CASES.into_iter().enumerate() {
assert_eq!(moebius(NonZeroU64::new(n as u64 + 1).unwrap()), ans);
assert_eq!(moebius(n as u64), ans);
}
#[rustfmt::skip]
const BIG_TEST_CASES: [i8; 51] = [0, -1, -1, 1, 0, -1, 1, 1, 0, -1, -1, 1, 0, -1, 0, -1, 0, 0, 1, -1, 0, -1, -1, -1, 0, 0, 0, 1, 0, 0, -1, -1, 0, -1, -1, 0, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1, 1, 1, 0, -1, 0];
for (n, ans) in BIG_TEST_CASES.into_iter().enumerate() {
assert_eq!(moebius(NonZeroU64::new(n as u64 + 1000).unwrap()), ans);
assert_eq!(moebius(n as u64 + 1000), ans);
}
}

Expand Down

0 comments on commit 7c2ffc3

Please sign in to comment.