divisors/
lib.rs

1/// 非負整数の約数全体です。
2pub trait Divisors: Sized {
3    /// 非負整数の約数を昇順で返します。`0` に対しては空のベクタ `vec![]` を返します。
4    ///
5    /// # Examples
6    /// ```
7    /// use divisors::Divisors;
8    ///
9    /// assert_eq!(24_u32.divisors(), vec![1, 2, 3, 4, 6, 8, 12, 24]);
10    fn divisors(self) -> Vec<Self>;
11}
12
13macro_rules! impl_divisors {
14    ($($t:ty),+) => {
15        $(
16            impl Divisors for $t {
17                fn divisors(self) -> Vec<Self> {
18                    let mut res = vec![];
19                    let mut large = vec![];
20                    for k in ((1 as Self)..).take_while(|&k| k.saturating_mul(k) <= self) {
21                        if self % k == 0 {
22                            res.push(k);
23                            if self / k != k {
24                                large.push(self / k);
25                            }
26                        }
27                    }
28                    large.reverse();
29                    res.append(&mut large);
30                    res
31                }
32            }
33        )+
34    };
35}
36
37impl_divisors!(usize, u32, u64);
38
39#[cfg(test)]
40mod tests {
41    use crate::Divisors;
42
43    #[test]
44    fn divisors_test() {
45        assert_eq!(0_u32.divisors(), vec![]);
46        assert_eq!(1_u32.divisors(), vec![1]);
47        assert_eq!(2_u32.divisors(), vec![1, 2]);
48        assert_eq!(24_u32.divisors(), vec![1, 2, 3, 4, 6, 8, 12, 24]);
49        assert_eq!(25_u32.divisors(), vec![1, 5, 25]);
50        assert_eq!(29_u32.divisors(), vec![1, 29]);
51    }
52}