Rust Program to Find LCM of two Numbers


Find LCM of two Numbers

Rust Programming Language


Find LCM of two Numbers


Problem


Rust program that calculates the LCM (Least Common Multiple) of two numbers.

Input


use std::io;

fn main() {
    println!("Please enter two numbers:");

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    let mut nums = input
        .split_whitespace()
        .map(|num| match num.trim().parse() {
            Ok(parsed_num) => parsed_num,
            Err(_) => {
                println!("Invalid input, please enter two valid numbers");
                return;
            }
        })
        .collect::<Vec<u32>>();

    let mut num1 = nums.pop().unwrap();
    let mut num2 = nums.pop().unwrap();

    let gcd = {
        let mut n1 = num1;
        let mut n2 = num2;
        while n2 != 0 {
            let temp = n2;
            n2 = n1 % n2;
            n1 = temp;
        }
        n1
    };

    let lcm = num1 * num2 / gcd;

    println!("The LCM of the two numbers is: {}", lcm);
}{codeBox}

Output


Please enter two numbers:
6 8
The LCM of the two numbers is: 24{codeBox}

Explanation


This program is very similar to the previous one that calculates the GCD, except that instead of calculating the GCD, we calculate the LCM.

We first prompt the user for input and read two numbers from the user using the io module from Rust's standard library.

We then parse the input numbers into unsigned 32-bit integers and store them in a Vec<u32>. We use a similar error handling approach as before to handle cases where the user enters invalid input.

We then pop the two numbers from the Vec<u32> and store them in num1 and num2, respectively.

We then calculate the GCD of num1 and num2 using the Euclidean algorithm. We use a nested block to keep the variables used for GCD calculation in a narrower scope. Finally, we store the calculated GCD in gcd.

We then calculate the LCM using the formula lcm = num1 * num2 / gcd, where gcd is the calculated GCD.

Finally, we print the calculated LCM to the console using println!("The LCM of the two numbers is: {}", lcm);.

This shows the program prompting the user for input, the user entering the numbers 6 and 8, and the program calculating and displaying the LCM of the two numbers, which is 24.



Post a Comment