malachite_nz/integer_vector/arithmetic/element_sum.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::integer::Integer;
10use crate::integer_vector::IntegerVector;
11use malachite_base::num::arithmetic::traits::ElementSum;
12
13impl ElementSum for IntegerVector {
14 type Output = Integer;
15
16 /// Returns the sum of the elements of an [`IntegerVector`], taking the vector by reference.
17 ///
18 /// The 0-dimensional vector has no elements, and their sum is 0.
19 ///
20 /// $$
21 /// f(v) = \sum_i v_i.
22 /// $$
23 ///
24 /// # Worst-case complexity
25 /// $T(n) = O(n)$
26 ///
27 /// $M(n) = O(n)$
28 ///
29 /// where $T$ is time, $M$ is additional memory, and $n$ is the total number of bits of the
30 /// elements.
31 ///
32 /// # Examples
33 /// ```
34 /// use core::str::FromStr;
35 /// use malachite_base::num::arithmetic::traits::ElementSum;
36 /// use malachite_nz::integer_vector::IntegerVector;
37 ///
38 /// assert_eq!(
39 /// IntegerVector::from_str("(1, -5, 2)")
40 /// .unwrap()
41 /// .to_element_sum(),
42 /// -2
43 /// );
44 /// assert_eq!(IntegerVector::from_str("()").unwrap().to_element_sum(), 0);
45 /// ```
46 ///
47 /// This is equivalent to `_fmpz_vec_sum` from `fmpz_vec/sum.c`, FLINT 3.6.0.
48 #[inline]
49 fn to_element_sum(&self) -> Integer {
50 self.elements.iter().sum()
51 }
52
53 /// Returns the sum of the elements of an [`IntegerVector`], taking the vector by value.
54 ///
55 /// The 0-dimensional vector has no elements, and their sum is 0.
56 ///
57 /// $$
58 /// f(v) = \sum_i v_i.
59 /// $$
60 ///
61 /// # Worst-case complexity
62 /// $T(n) = O(n)$
63 ///
64 /// $M(n) = O(n)$
65 ///
66 /// where $T$ is time, $M$ is additional memory, and $n$ is the total number of bits of the
67 /// elements.
68 ///
69 /// # Examples
70 /// ```
71 /// use core::str::FromStr;
72 /// use malachite_base::num::arithmetic::traits::ElementSum;
73 /// use malachite_nz::integer_vector::IntegerVector;
74 ///
75 /// assert_eq!(
76 /// IntegerVector::from_str("(1, -5, 2)")
77 /// .unwrap()
78 /// .into_element_sum(),
79 /// -2
80 /// );
81 /// assert_eq!(IntegerVector::from_str("()").unwrap().into_element_sum(), 0);
82 /// ```
83 ///
84 /// This is equivalent to `_fmpz_vec_sum` from `fmpz_vec/sum.c`, FLINT 3.6.0.
85 #[inline]
86 fn into_element_sum(self) -> Integer {
87 self.elements.into_iter().sum()
88 }
89}