-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
[package] | ||
name = "divisors" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[dependencies] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
trait Divisors { | ||
fn divisors(self) -> impl Iterator<Item = Self>; | ||
} | ||
|
||
macro_rules! impl_uint { | ||
( $($ty:ty)* ) => { $( | ||
impl Divisors for $ty { | ||
fn divisors(self) -> impl Iterator<Item = Self> { | ||
let n = self; | ||
std::iter::successors( | ||
(n >= 1).then_some((1, true)), | ||
move |&(i, asc)| { | ||
if asc { | ||
if let Some(j) = (i + 1..) | ||
.take_while(|j| j * j <= n) | ||
.find(|j| n % j == 0) | ||
{ | ||
return Some((j, true)); | ||
} else if n / i != i { | ||
return Some((i, false)); | ||
} | ||
} | ||
let j = (1..i).rev().find(|&j| n % j == 0)?; | ||
Some((j, false)) | ||
}, | ||
) | ||
.map(move |(i, asc)| if asc { i } else { n / i }) | ||
} | ||
} | ||
)* }; | ||
} | ||
|
||
impl_uint! { u8 u16 u32 u64 u128 usize } | ||
|
||
#[test] | ||
fn sanity_check() { | ||
assert!(0_u32.divisors().eq(None)); | ||
|
||
for n in 1_u32..=10000 { | ||
let expected = (1..=n).filter(|i| n % i == 0); | ||
let actual = n.divisors(); | ||
assert!(actual.eq(expected)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
use inner::doc_inline_reexport; | ||
|
||
doc_inline_reexport! { | ||
divisors, | ||
linear_sieve, | ||
modint, | ||
} |