#fibonacci
18 messages · Page 1 of 1 (latest)
but I assume youre asking about code quality, not performance
js is definitely a real programming language, its just a lot more loose about everything
you can refactor this rs let n: u32 = match n.trim().parse() { Ok(num) => num, Err(_) => continue, };like thisrs let Ok(n) = n.trim().parse::<u32>() else { continue; }
let else was added just about one month ago
fn main() {
println!("Fibonacci generator");
println!("Type \"quit\" to end the program");
loop {
let mut n = String::new();
println!("\nEnter a positive integer:");
io::stdin().read_line(&mut n).expect("Failed to read line.");
let n = n.trim(); // you can use shadowing to your advantage here. we dont need the non-trimmed version anymore
if n == "quit" {
break;
}
let Ok(n) = n.parse::<u32>() else {
continue;
};
println!("{}", fibonacci(n));
}
}```
no, its just convenient here
the original n variable still exists, its just no longer accessible because there's another with the same name that's prioritized
its nice when you want to transform a value but dont need the original
in the book its here
I dont think I have anything more to say, except for the inefficient algorithm for fibonacci
I could write how I would do it if you want
fn fibonacci(n: u32) -> u32 {
let (mut a, mut b) = (0, 1);
for _ in 0..n {
(a, b) = (b, a + b);
}
b
}```
result will be the same, but this isnt recursive
imagine we call fib(4). lets expand that out.
it will expand into:
fib(3) + fib(2) which expands into
fib(2) + fib(1) + fib(1) + fib(0) which expands into
fib(1) + fib(0) + fib(1) + fib(1) + fib(0) see how different steps of the computation are done multiple times? its duplicated effort that slows it down
with an iterative method like this, you do each necessary step of the calculation only once
I'm pretty sure that recursive method actually gets optimized by the compiler to be just as fast, but thats not guaranteed. it probably wont happen for cases more complex than this.