-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvergents_of_e.rs
38 lines (34 loc) · 1.06 KB
/
convergents_of_e.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use crate::utils;
/// Find the continued fraction convergent of Euler's number at the specified
/// index.
///
/// * `idx_max` Index of the convergent.
///
/// Returns 0 if `idx_max` is 0. Returns the convergent otherwise.
fn generate_continued_fraction(idx_max: u32) -> utils::Fraction {
match idx_max {
..=0 => utils::Fraction::from(0, 1),
1 => utils::Fraction::from(2, 1),
_ => &generate_continued_fraction_(2, idx_max) + 2,
}
}
/// Helper to calculate the continued fraction convergent of Euler's number.
///
/// * `idx` Current index.
/// * `idx_max` Index of the convergent.
fn generate_continued_fraction_(idx: u32, idx_max: u32) -> utils::Fraction {
let addend = if idx % 3 == 0 { idx / 3 * 2 } else { 1 };
let mut fraction = if idx == idx_max {
utils::Fraction::from(0, 1)
} else {
generate_continued_fraction_(idx + 1, idx_max)
};
fraction += addend;
fraction.invert();
fraction
}
pub fn solve() -> i64 {
let sum = generate_continued_fraction(100).sum().0;
assert_eq!(sum, 272);
sum
}