All of the answers ignore the fact, that the OP wants to sum i32
, not u32
from 0 to n. This implies that there may also be negative sums involved (0 + -1 + -2 + ... + n). Hence, I propose:
fn summation(n: i32) -> i32 {
if n < 0 {
(n..0).sum()
} else {
(0..=n).sum()
}
}