Skip to content

Instantly share code, notes, and snippets.

@motss
Created June 10, 2019 04:13
Show Gist options
  • Select an option

  • Save motss/88147b342e2ec0314a13c7c003947c35 to your computer and use it in GitHub Desktop.

Select an option

Save motss/88147b342e2ec0314a13c7c003947c35 to your computer and use it in GitHub Desktop.
Fibonacci sequence in Rust and JavaScript
function fib(nth) {
const vec = [0, 1];
let i = 2;
while (i <= nth) {
const val = vec[0] + vec[1];
vec[0] = vec[1];
vec[1] = val;
i += 1;
}
return vec[1];
}
function fibSeq(nth) {
const vec = [0, 1, 1];
let i = 3;
while (i <= nth) {
vec.push(vec[i - 1] + vec[i - 2]);
i += 1;
}
return vec;
}
function main() {
console.log(`20th term: ${fib(20)}`);
console.log(`Fibonacci sequence: [${fibSeq(20).join()}]`);
}
main();
fn fib(nth: i32) -> u32 {
let mut vec = (0, 1);
for _ in 2..=nth {
let val = vec.0 + vec.1;
vec = (vec.1, val);
}
vec.1
}
fn fib_seq(nth: usize) -> Vec<i32> {
let mut vec = vec![0, 1, 1];
for n in 3..=nth {
vec.push(vec[n - 1] + vec[n - 2]);
}
vec
}
fn main() {
println!("20th term: {}", fib(20));
println!("Fibonacci sequence: {:?}", fib_seq(20));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment