#while loops question
24 messages · Page 1 of 1 (latest)
eg. ||```rs
fn sum2(mut low: i32, high: i32) -> i32 {
let mut total = 0;
while low <= high {
total += low;
low += 1;
}
total
}```||
or just a for 😛
or you can do .sum() on a range and have no for or while
why dont you just ((hi-lo)+1)*(hi+lo)/2
because they're learning
¯_(ツ)_/¯
it's an adaptation of gauss' sum
which is a fast way to find the sum of all natural numbers up to n
that's ok 
my sum may be wrong
the optimizer can figure this particular optimization sometimes itself
not here it cant
sometimes
but the simple case it does
?godbolt ```rs
#[no_mangle]
pub fn gaussian_sum(to: usize) -> usize {
(0..to).sum()
}
gaussian_sum:
test rdi, rdi
je .LBB0_1
lea rax, [rdi - 1]
lea rcx, [rdi - 2]
mul rcx
shld rdx, rax, 63
lea rax, [rdi + rdx]
dec rax
ret
.LBB0_1:
xor eax, eax
ret
```Note: only public functions (`pub fn`) are shown

?godbolt flags="-Copt-level=z" ```rs
#[no_mangle]
pub fn gaussian_sum(to: usize) -> usize {
(0..to).sum()
}
core::iter::traits::iterator::Iterator::sum:
jmp qword ptr [rip + <usize as core::iter::traits::accum::Sum>::sum@GOTPCREL]
<usize as core::iter::traits::accum::Sum>::sum:
cmp rsi, rdi
cmovbe rsi, rdi
mov rax, rdi
not rax
add rax, rsi
sub rsi, rdi
mul rsi
shrd rax, rdx, 1
imul rsi, rdi
add rax, rsi
ret
gaussian_sum:
lea rax, [rdi - 1]
mul rdi
shrd rax, rdx, 1
ret
```Note: only public functions (`pub fn`) are shown
xd