Skip to content

Instantly share code, notes, and snippets.

@isosphere
Created October 8, 2020 13:34
Show Gist options
  • Save isosphere/107176a57515ffbc0e210662a2dde2ff to your computer and use it in GitHub Desktop.
Save isosphere/107176a57515ffbc0e210662a2dde2ff to your computer and use it in GitHub Desktop.
Highly Composite Number Function in Rust (Not Optimized)
/// Returns the largest highly composite number less than or equal to the given number.
/// There is nothing clever about this algorithm, it is slow.
/// # Arguments
/// * `maximum` - A reference to a number that the highly composite number must not exceed
/// # Examples
/// ```
/// assert_eq!(highest_highly_composite_number(&842), 840)
/// ```
fn highest_highly_composite_number<'a, T: 'a>(maximum: &T) -> T
where
T: Copy + Sum + PartialOrd + PartialEq + Add<Output=T> + AddAssign + Rem<Output=T> + Div<Output=T> + Zero + One,
RangeInclusive<T>: Iterator<Item = T>
{
let two = T::one() + T::one();
let mut max_divisors = T::one();
let mut max_result = T::one();
let mut i = T::one();
while i <= *maximum {
let divisors = T::one() + (two ..=*maximum).map(|d| match i % d == T::zero() { true => T::one(), false => T::zero()} ).sum();
if divisors > max_divisors {
max_divisors = divisors;
max_result = i;
}
i += T::one();
}
max_result
}
#[test]
fn test_hcn() {
let known_hcn = vec![1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040];
for hcn in &known_hcn {
assert_eq!(*hcn, highest_highly_composite_number(hcn));
}
let known_not_hcn = vec![3, 5, 7, 13, 25, 37, 49, 55, 112, 145, 221, 350];
for hcn in &known_not_hcn {
assert_ne!(*hcn, highest_highly_composite_number(hcn));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment