I'm trying to learn Rust and for this reason I'm reading the Rust Book. It contains the following exercise:
Generate the nth Fibonacci number.
Here's my take. Note I'm only using material from chapters 1-3 of this book (since I've only read so far yet), with the exception of format!
which I learned by Googling it and unreachable!
, which I learned by asking other people. I think I needed both facilities to complete the task.
use std::io;
fn main() {
let n = loop {
println!("Enter n to get Fₙ:");
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.expect("Failed to read line");
break match n.trim().parse() {
Ok(n) => n,
Err(_) => continue,
}
};
let subscript_n = subscript(n);
let res = fib(n);
println!("F{subscript_n} = {res}");
}
fn fib(n: u32) -> u64 {
match n {
0 => 0,
n => {
let mut fib_i = 1u64;
let mut fib_i_minus_1 = 0u64;
for _ in 1..n {
(fib_i, fib_i_minus_1) = (fib_i.checked_add(fib_i_minus_1).expect("Result too large"), fib_i);
}
fib_i
}
}
}
fn subscript(n: u32) -> String {
match n {
0 => format!("0"),
mut n => {
let mut res = String::new();
while n != 0 {
let digit = match n % 10 {
0 => '₀',
1 => '₁',
2 => '₂',
3 => '₃',
4 => '₄',
5 => '₅',
6 => '₆',
7 => '₇',
8 => '₈',
9 => '₉',
10.. => unreachable!(),
};
n /= 10;
res = format!("{res}{digit}");
}
res
}
}
}
Comments?