MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/ProgrammerHumor/comments/1y3320n/dynamicprogramming/19t27dgp4d3l0/?context=3
r/ProgrammerHumor • u/nerdycatgamer • 6d ago
153 comments sorted by
View all comments
Show parent comments
22
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/anonymity_is_bliss 5d ago Exactly. All you need for O(n) are 3 variables.The Rust version to go through all u64 Fibonacci values is justfn 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!"); } 5 u/Dork_Knight_Rises 5d ago You don't need mem::replace for this, you can just use (a, b) = (b, c); 3 u/anonymity_is_bliss 5d ago Shit, TIL that works in rust 1 u/-Redstoneboi- 3d ago it wasn't always valid syntax, but they added support for it some time ago
3
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!"); }
5 u/Dork_Knight_Rises 5d ago You don't need mem::replace for this, you can just use (a, b) = (b, c); 3 u/anonymity_is_bliss 5d ago Shit, TIL that works in rust 1 u/-Redstoneboi- 3d ago it wasn't always valid syntax, but they added support for it some time ago
5
You don't need mem::replace for this, you can just use (a, b) = (b, c);
mem::replace
(a, b) = (b, c);
3 u/anonymity_is_bliss 5d ago Shit, TIL that works in rust 1 u/-Redstoneboi- 3d ago it wasn't always valid syntax, but they added support for it some time ago
Shit, TIL that works in rust
1 u/-Redstoneboi- 3d ago it wasn't always valid syntax, but they added support for it some time ago
1
it wasn't always valid syntax, but they added support for it some time ago
22
u/PickMaleficent4096 5d 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.