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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//! Contains some helper functions that can be useful.

use crate::Rational;

/// Convenience method for constructing a simple `Rational`.
///
/// ## Example
/// ```rust
/// # use rational::{Rational, extras::*};
/// let one_half = r(1, 2);
/// assert_eq!(one_half, Rational::new(1, 2));
/// ```
pub fn r(n: i128, d: i128) -> Rational {
    Rational::new(n, d)
}

/// Calculate the greatest common divisor of two numbers.
///
/// ## Example
/// ```rust
/// # use rational::extras::*;
/// assert_eq!(gcd(9, 60), 3);
/// assert_eq!(gcd(899, 957), 29);
/// assert_eq!(gcd(-899, 957), 29);
/// ```
pub fn gcd(mut a: i128, mut b: i128) -> i128 {
    a = a.abs();
    b = b.abs();
    while b != 0 {
        let temp = b;
        b = a % b;
        a = temp;
    }
    a
}

/// Calculate the least common multiple of two numbers.
///
/// ## Panics
/// * If overflow occurred
///
/// ## Example
/// ```rust
/// # use rational::extras::*;
/// assert_eq!(lcm(6, 8), 24);
/// assert_eq!(lcm(-6, 8), 24);
/// ```
pub fn lcm(a: i128, b: i128) -> i128 {
    let g = gcd(a, b);
    a.abs() * (b.abs() / g)
}

/// Calculate the least common multiple of two numbers, raturning `None` if overflow occurred.
///
/// ## Example
/// ```rust
/// # use rational::extras::*;
/// assert_eq!(lcm_checked(6, 8), Some(24));
/// assert_eq!(lcm_checked(-6, 8), Some(24));
/// assert_eq!(lcm_checked(i128::MAX, i128::MAX - 1), None);
/// ```
pub fn lcm_checked(a: i128, b: i128) -> Option<i128> {
    let g = gcd(a, b);
    a.abs().checked_mul(b.abs().checked_div(g)?)
}

pub fn is_coprime(l: i128, r: i128) -> bool {
    gcd(l, r) == 1
}

/// Create a [continued fraction](https://en.wikipedia.org/wiki/Continued_fraction#Motivation_and_notation).
///
/// ## Notes
/// The size of the numerator and denominator can grow quite quickly with increased lengths of `cont`,
/// so be careful with integer overflow. If `cont` is empty, then the resulting `Rational` will be equal to `init`.
///
/// ## Example
/// ```rust
/// # use rational::extras::*;
/// // to create a rational number that estimates the mathematical constant `e` (~2.7182818...)
/// // we can use the continued fraction [2;1,2,1,1,4,1,1,6,1,1,8]
/// let e = continued_fraction(2, &[1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]);
/// assert!((e.decimal_value() - std::f64::consts::E).abs() < 0.0000001);
/// ```
pub fn continued_fraction(init: u64, cont: &[u64]) -> Rational {
    let mut r = Rational::new(0, 1);

    for &d in cont.iter().rev() {
        r = Rational::new(1, r + d);
    }

    r + init
}

pub fn continued_fraction_iter(init: u64, cont: &[u64]) -> ContinuedFractionIter {
    ContinuedFractionIter::new(Rational::new(init, 1), cont)
}

pub struct ContinuedFractionIter<'a> {
    init: Rational,
    fraction: Rational,
    idx: usize,
    cont: &'a [u64],
}

impl<'a> ContinuedFractionIter<'a> {
    fn new(init: Rational, cont: &'a [u64]) -> Self {
        Self {
            init,
            fraction: Rational::zero(),
            idx: 0,
            cont,
        }
    }

    pub fn decimals(self) -> impl Iterator<Item = f64> + 'a {
        self.map(|r| r.decimal_value())
    }
}

impl Iterator for ContinuedFractionIter<'_> {
    type Item = Rational;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cont.is_empty() {
            if self.idx == 0 {
                self.idx += 1;
                Some(self.init)
            } else {
                None
            }
        } else if self.idx > self.cont.len() {
            None
        } else if self.idx == self.cont.len() {
            self.idx += 1;
            Some(self.init + self.fraction)
        } else {
            let curr = self.init + self.fraction;
            self.fraction =
                Rational::new(1, self.fraction + self.cont[self.cont.len() - self.idx - 1]);
            self.idx += 1;
            Some(curr)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn gcd_test() {
        let eq = |a: i128, b: i128, g: i128| assert_eq!(gcd(a, b), g, "a: {}, b: {}", a, b);
        eq(1, 2, 1);
        eq(5, 4, 1);
        eq(12, 4, 4);
        eq(-74, 44, 2);
    }

    #[test]
    fn lcm_test() {
        assert_eq!(lcm(2, 6), 6);
        assert_eq!(lcm(1, 6), 6);
    }

    #[test]
    fn repeated_test() {
        use std::f64::consts::*;
        let assert = |init: u64, cont: &[u64], expected: f64| {
            let actual = continued_fraction(init, cont).decimal_value();
            assert!(
                (actual - expected).abs() < 0.000000001,
                "actual: {}, expected: {}",
                actual,
                expected
            );
        };

        assert(1, &[2; 15], 2.0_f64.sqrt());
        assert(1, &[1; 100], 1.6180339887498);
        assert(4, &[2, 1, 3, 1, 2, 8, 2, 1, 3, 1, 2, 8], 19.0_f64.sqrt());
        assert(1, &[], 1.0);
        assert(4, &[], 4.0);
        assert(2, &[1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10], E);
        assert(3, &[7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1], PI);
    }

    #[test]
    fn continued_fraction_iter_test() {
        let decimal_approx: Vec<_> = continued_fraction_iter(2, &[1, 2, 1, 1, 4, 1, 1, 6])
            .decimals()
            .collect();
        assert_eq!(
            decimal_approx,
            vec![
                2.0,
                2.1666666666666665,
                2.857142857142857,
                2.5384615384615383,
                2.2203389830508473,
                2.8194444444444446,
                2.549618320610687,
                2.3922155688622753,
                2.718279569892473,
            ]
        );
    }
}