#while loops question

24 messages · Page 1 of 1 (latest)

rancid bay
#

you can use low for the current number, and the condition would be low <= high

#

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

chrome sleet
#

why dont you just ((hi-lo)+1)*(hi+lo)/2

rancid bay
#

because they're learning

chrome sleet
#

¯_(ツ)_/¯

rancid bay
#

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 ferrisCat

chrome sleet
#

ferrisOwO my sum may be wrong

rancid bay
#

the optimizer can figure this particular optimization sometimes itself

chrome sleet
#

not here it cant

rancid bay
#

sometimes

chrome sleet
#

but the simple case it does

#

?godbolt ```rs
#[no_mangle]
pub fn gaussian_sum(to: usize) -> usize {
(0..to).sum()
}

hybrid bladeBOT
#
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
chrome sleet
rancid bay
#

no loop

#

yay

#

but again, not that useful for a beginner

chrome sleet
#

?godbolt flags="-Copt-level=z" ```rs
#[no_mangle]
pub fn gaussian_sum(to: usize) -> usize {
(0..to).sum()
}

hybrid bladeBOT
#
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
chrome sleet
#

xd