r/ProgrammerHumor • • 2d ago

Meme dynamicProgramming

Post image
5.3k Upvotes

140 comments sorted by

View all comments

Show parent comment

20

u/PickMaleficent4096 1d ago

Fib(n) being used for DP has always been funny example to me. The naive recursive method is worse than the DP method sure... but if you calculate it the way a *human would on paper* it's the non-recursive O(n) time O(1) space solution.

3

u/suddencactus 1d ago

It's even funnier for me because analytic solutions exist.  We expect people to have complete mastery of courses in in discrete math and algorithms but then pretend they don't know how to use a generating series for a linear recurrence.

3

u/PickMaleficent4096 1d ago

To be honest I wouldn't expect anybody who isn't a specialist to be able to do that off the top of their head. The last time I heard the words "a generating series for a linear recurrence" was in college 10 years ago, and it hasn't been relevant to my software eng career since, including in interviews. I've had to dust off other parts of the math toolkit occasionally, but it's hard to justify analytical solutions in an environment where requirements are expected to change after your solution is live.

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

1

u/suddencactus 1d ago

And with the prices of RAM these days we need all the O(1) space we can get.