r/ProgrammerHumor • • 2d ago

Meme dynamicProgramming

Post image
5.3k Upvotes

140 comments sorted by

View all comments

Show parent comment

3

u/anonymity_is_bliss 1d ago

Exactly. All you need for O(n) are 3 variables.

The Rust version to go through all u64 Fibonacci values is just

fn main() {
    let mut a: u64 = 0;
    println!("{}", a);
    let mut b: u64 = 1;
    println!("{}", b);

    while let Some(c) = a.checked_add(b) {
        println!("{}", c);
        a = std::mem::replace(&mut b, c);
    }
    println!("Overflowed!");
}

4

u/Dork_Knight_Rises 1d ago

You don't need mem::replace for this, you can just use (a, b) = (b, c);

3

u/anonymity_is_bliss 1d ago

Shit, TIL that works in rust