inf_add 0.2.0

Create, add, subtract, multiply, and display infinitely long numbers
Documentation
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! # Inf add
//!
//! `inf_add` desribes a struct and related functions which
//! allow you to infinitely add and subtract to/from a positive
//! number. The number is stored as a vector of u128 unsigned
//! integers, and converted to base 10 for displaying (as such,
//! larger numbers have larger computation cost, especially
//! for displaying).

use core::panic;
use std::{fmt, ops};

#[derive(Clone)]
pub struct InfInt(pub Vec<u128>);

impl InfInt {
    /// Creates a new InfInt object out of a u128 number
    ///
    /// # Example
    /// ```
    /// let new_infint = inf_add::InfInt::new(5);
    /// ```
    pub fn new(var: u128) -> Self {
        InfInt(vec![var])
    }

    /// Adds another InfInt object to the current one,
    /// replacing the current value.
    ///
    /// # Examples
    /// ```
    /// let mut result = inf_add::InfInt::new(1);
    /// result.add_destroy(&inf_add::InfInt::new(2));
    ///
    /// assert_eq!(result, inf_add::InfInt::new(3));
    /// ```
    ///
    /// ```
    /// let mut result = inf_add::InfInt::new(u128::MAX);
    /// result.add_destroy(&inf_add::InfInt::new(1));
    ///
    /// let mut answer = inf_add::InfInt::new(0);
    /// answer.0.push(1);
    ///
    /// assert_eq!(result, answer);
    /// ```
    pub fn add_destroy(&mut self, other: &InfInt) {
        if self.0.len() == 0 {
            panic!("Empty InfInt object should never exist.");
        }
        let mut carry = false;
        //loop through every item the other array
        let mut idx = 0;
        while idx < other.0.len() {
            if idx > self.0.len() - 1 {
                //if no matching item in self
                self.0.push(0);
            }
            //add actual values together
            let (res_temp, car_temp1) = u128::add_and_carry(self.0[idx], other.0[idx]);
            //add carry to result
            (self.0[idx], carry) = u128::add_and_carry(res_temp, carry as u128);
            //set carry (only one carry can be true at once)
            carry = car_temp1 || carry;
            idx += 1;
        }
        //propogate carry throughout rest of self
        while carry {
            if idx >= self.0.len() {
                //if no matching item in self, add new item
                self.0.push(1);
                break;
            }
            (self.0[idx], carry) = u128::add_and_carry(self.0[idx], 1);
            idx += 1;
        }
    }

    pub fn subtract_destroy(&mut self, other: &InfInt) {
        if other.0.len() > self.0.len() {
            // subtracting more than in number, return 0
            self.0 = vec![0];
        }
        //
        let mut carry = false;
        //loop through every item in other array
        let mut idx = 0;
        while idx < other.0.len() {
            //subtract main values
            let mut temp_carry = self.0[idx] < other.0[idx];
            self.0[idx] = self.0[idx].wrapping_sub(other.0[idx]);
            //subtract carry value
            temp_carry = temp_carry || (self.0[idx] == 0);
            self.0[idx] = self.0[idx].wrapping_sub(carry as u128);
            carry = temp_carry;
            idx += 1;
        }
        if carry {
            //propogate carry through rest of self
            loop {
                if idx >= self.0.len() {
                    // subtracting more than in number, return 0
                    self.0 = vec![0];
                    break;
                } else if self.0[idx] == 0 {
                    //carry
                    self.0[idx] = u128::MAX;
                } else {
                    //no carry
                    self.0[idx] -= 1;
                    break;
                }
                idx += 1;
            }
        }

        //remove trailing 0s
        while self.0.len() > 1 && *self.0.last().unwrap() == 0 {
            self.0.pop();
        }
    }

    pub fn multiply_destroy(&mut self, other: &InfInt) {
        if self.0.len() == 0 || other.0.len() == 0 {
            panic!("Empty InfInt object should never exist.");
        }
        if (other.0.len() == 1 && other.0[0] == 0) || (self.0.len() == 1 && self.0[0] == 0) {
            self.0 = vec![0];
            return; //if either is empty, or either is just 0, result is 0
        }
        //
        //create idxs vector to increment through other for correct number of multiplications
        let mut other_idxs: Vec<u128> = vec![];
        for i in 0..other.0.len() {
            if other.0[i] != 0 {
                other_idxs.push(0);
            }
        }
        //
        inc_list_idx(&mut other_idxs); //increment early because self already starts with 1x
        let self_adder = self.clone();
        while other_idxs != other.0 {
            self.add_destroy(&self_adder);
            //
            inc_list_idx(&mut other_idxs);
        }
    }

    pub fn to_base_10_array(&self) -> Vec<u8> {
        let mut array_out = vec![0];
        //
        //for every u128
        for i in 0..self.0.len() {
            //
            //convert each digit of the current item
            for j in 0..128 {
                //if bit is set
                if ((self.0[i] >> j) & 1) == 1 {
                    let mut new_value = vec![1];
                    //construct base 10 array from bit by multiply base 10 by 2 the appropriate amount of times
                    for _ in 0..((i * 128) + j) {
                        //double first digit
                        let (mut res, mut carry) =
                            base_10_add_and_carry(new_value[0], new_value[0]);
                        new_value[0] = res;
                        //
                        //double rest of digits
                        for k in 1..new_value.len() {
                            let temp_carry = carry;
                            (res, carry) = base_10_add_and_carry(new_value[k], new_value[k]);
                            //doubled value will always be even, so carry can be added without considering overflow
                            new_value[k] = res + temp_carry as u8;
                        }
                        //
                        if carry {
                            new_value.push(1);
                        }
                    }
                    //
                    //add base 10 array to array_out
                    let mut carry = false;
                    let mut k = 0;
                    while k < new_value.len() {
                        if k > array_out.len() - 1 {
                            array_out.push(0);
                        }
                        //add newly create base 10 digit value to out array
                        let (res, car_temp) = base_10_add_and_carry(array_out[k], new_value[k]);
                        //add carry from previous loop
                        (array_out[k], carry) = base_10_add_and_carry(res, carry as u8);
                        //set carry (only one carry can be true at once)
                        carry = car_temp || carry;
                        k += 1;
                    }
                    //propagate carry throughout array_out
                    while carry {
                        if k > array_out.len() - 1 {
                            array_out.push(0);
                        }
                        (array_out[k], carry) = base_10_add_and_carry(array_out[k], 1);
                        k += 1;
                    }
                }
            }
        }
        //
        array_out
    }
}

fn inc_list_idx(list_idx: &mut Vec<u128>) {
    let mut idx = 0;
    let mut carry = true;
    while idx < list_idx.len() {
        (list_idx[idx], carry) = u128::add_and_carry(list_idx[idx], carry as u128);
        if !carry {
            break;
        }
        //
        idx += 1;
    }
}

pub trait AddAndCarry<T, Output = (T, bool)> {
    fn add_and_carry(a: T, b: T) -> Output;
}

impl AddAndCarry<u128> for u128 {
    fn add_and_carry(a: u128, b: u128) -> (u128, bool) {
        let result = a.wrapping_add(b);
        let carry = result < a || result < b;
        (result, carry)
    }
}

impl AddAndCarry<u8> for u8 {
    fn add_and_carry(a: u8, b: u8) -> (u8, bool) {
        let result = a.wrapping_add(b);
        let carry = result < a || result < b;
        (result, carry)
    }
}

fn base_10_add_and_carry(a: u8, b: u8) -> (u8, bool) {
    let result = a + b;
    let carry = result > 9;
    (result % 10, carry)
}

impl fmt::Debug for InfInt {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut result = String::new();
        let base_10_version = self.to_base_10_array();
        for number in base_10_version.iter().rev() {
            result.push_str(&number.to_string());
        }
        write!(f, "{}", result)
    }
}

impl fmt::Display for InfInt {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut result = String::new();
        let base_10_version = self.to_base_10_array();
        for number in base_10_version.iter().rev() {
            result.push_str(&number.to_string());
        }
        write!(f, "{}", result)
    }
}

impl ops::Add<InfInt> for InfInt {
    type Output = InfInt;

    fn add(self, other: InfInt) -> InfInt {
        let mut result = self.clone();
        result.add_destroy(&other);
        result
    }
}

impl ops::Add<u128> for InfInt {
    type Output = InfInt;

    fn add(self, other: u128) -> InfInt {
        let mut result = self.clone();
        result.add_destroy(&InfInt::new(other));
        result
    }
}

impl PartialEq for InfInt {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

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

    #[test]
    fn test_add_and_carry() {
        let (result, carry) = u128::add_and_carry(1, 2);
        assert_eq!(result, 3);
        assert!(!carry);

        let (result, carry) = u128::add_and_carry(u128::MAX, 1);
        assert_eq!(result, 0);
        assert!(carry);
    }

    #[test]
    fn test_add_destroy() {
        let mut a = InfInt::new(1);
        let b = InfInt::new(2);
        a.add_destroy(&b);
        assert_eq!(a, InfInt::new(3));
    }

    #[test]
    fn add_new_item() {
        let mut a = InfInt::new(1);
        a.add_destroy(&InfInt::new(u128::MAX));
        //
        let mut answer = InfInt::new(0);
        answer.0.push(1);
        //
        println!("a: {:?}", a);
        println!("answer: {:?}", answer);
        //
        assert_eq!(a, answer);
    }

    #[test]
    fn add_two_items() {
        let mut a = InfInt::new(5);
        a.add_destroy(&InfInt::new(u128::MAX));
        a.add_destroy(&InfInt::new(u128::MAX));
        let mut b = InfInt::new(3);
        b.0.push(2);
        assert_eq!(a, b);
    }

    #[test]
    fn add_with_long_carry() {
        let mut a = InfInt::new(u128::MAX);
        a.0.push(u128::MAX);
        a.0.push(u128::MAX);
        a.add_destroy(&InfInt::new(1));
        //
        let mut answer = InfInt::new(0);
        answer.0.push(0);
        answer.0.push(0);
        answer.0.push(1);
        //
        assert_eq!(a, answer);
    }

    #[test]
    fn test_subtract_destroy() {
        let mut a = InfInt::new(5);
        let b = InfInt::new(2);
        a.subtract_destroy(&b);
        assert_eq!(a, InfInt::new(3));
    }

    #[test]
    fn test_subtract_bigger() {
        let mut a = InfInt::new(5);
        let b = InfInt::new(10);
        a.subtract_destroy(&b);
        assert_eq!(a, InfInt::new(0)); // should return 0
    }

    #[test]
    fn test_to_base_10_array() {
        let a = InfInt::new(123456789);
        let base_10_array = a.to_base_10_array();
        assert_eq!(base_10_array, vec![9, 8, 7, 6, 5, 4, 3, 2, 1]); // should match the digits in reverse order
    }

    #[test]
    fn test_small_to_base_10_array() {
        let a = InfInt::new(5);
        let base_10_array = a.to_base_10_array();
        assert_eq!(base_10_array, vec![5]);
    }

    #[test]
    fn test_carry_to_base_10_array() {
        let a = InfInt::new(10);
        let base_10_array = a.to_base_10_array();
        assert_eq!(base_10_array, vec![0, 1]);
    }

    #[test]
    fn test_subtract_carry() {
        let mut a = InfInt::new(0);
        a.0.push(1);
        let b = InfInt::new(1);
        a.subtract_destroy(&b);

        assert_eq!(a, InfInt::new(u128::MAX));
        assert_eq!(a.0.len(), InfInt::new(u128::MAX).0.len());
    }

    #[test]
    fn test_add_and_subtract() {
        let mut a = InfInt::new(10);
        a.add_destroy(&InfInt::new(5));
        assert_eq!(a, InfInt::new(15));

        a.subtract_destroy(&InfInt::new(12));
        assert_eq!(a, InfInt::new(3));
    }

    #[test]
    fn test_multiply_destroy() {
        let mut a = InfInt::new(3);
        let b = InfInt::new(4);
        a.multiply_destroy(&b);
        assert_eq!(a, InfInt::new(12));

        let mut c = InfInt::new(0);
        c.multiply_destroy(&b);
        assert_eq!(c, InfInt::new(0)); // multiplying by 0 should return 0
    }
}