Skip to content

Mathematics

Weight on Mars

fn main() {
    let mut input = String::new();
    println!("Enter weight in kilograms: ");

    std::io::stdin().read_line(&mut input);

    let input: f32 = match input.trim().parse() {
        Ok(num) => num,
        Err(_) => 0.0,
    };

    let mars_weight = calculate_weight_on_mars(input);
    println!("Weight on Mars: {} kg", &mars_weight);
}

fn calculate_weight_on_mars(weight: f32) -> f32 {
    (weight / 9.81) * 3.711
}

Fibonacci sequence

use std::collections::HashMap;

fn fib(n: u64) -> u64 {
    match n {
        0 | 1 => 1,
        n => fib(n - 1) + fib(n - 2)
    }
}

fn main() {
    let n: u64 = std::env::args().nth(1).unwrap().parse().unwrap();
    for i in 1..n {
        println!("{}: {}", i, fib(i));
    }
}
use std::collections::HashMap;

fn fib(n: u64, map: &mut HashMap<u64, u64>) -> u64 {
    match n {
        0 | 1 => 1,
        n => {
            if map.contains_key(&n) {
                *map.get(&n).unwrap()
            } else {
                let val = fib(n-1, map) + fib(n-2, map);
                map.insert(n, val);
                val
            }
        }
    }
}

fn main() {
    let n: u64 = std::env::args().nth(1).unwrap().parse().unwrap();
    let mut map = HashMap::new();
    for i in 1..n {
        println!("{}: {}", i, fib(i, &mut map));
    }
}