Add fibonacci number generator
This commit is contained in:
parent
ba3d3a591e
commit
5d14e86f4a
2 changed files with 41 additions and 0 deletions
9
fibonacci/Cargo.toml
Normal file
9
fibonacci/Cargo.toml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "fibonacci"
|
||||
version = "0.1.0"
|
||||
authors = ["laurens <miers132@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
32
fibonacci/src/main.rs
Normal file
32
fibonacci/src/main.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
use std::io;
|
||||
|
||||
const FIB_0: u32 = 0;
|
||||
const FIB_1: u32 = 1;
|
||||
|
||||
fn generate_fib_number(n: u32) -> u32 {
|
||||
if n == 0 {
|
||||
FIB_0
|
||||
} else if n == 1 {
|
||||
FIB_1
|
||||
} else {
|
||||
generate_fib_number(n - 1) + generate_fib_number(n - 2)
|
||||
}
|
||||
}
|
||||
|
||||
fn print_fib_sequence(n: u32) {
|
||||
println!("Just for lullz, a sequence of {} fibonacci numbers", n);
|
||||
for n in 0..n {
|
||||
println!("{}: {}", n, generate_fib_number(n));
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut n = String::new();
|
||||
|
||||
println!("Input number of fibonacci numbers to generate:");
|
||||
io::stdin().read_line(&mut n).expect("Failed to read user input");
|
||||
|
||||
let n: u32 = n.trim().parse().expect("Not a number!");
|
||||
|
||||
print_fib_sequence(n);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue