Rust Program to Find GCD of two Numbers


Find GCD of two Numbers

Rust Programming Language


Find GCD of two Numbers


Problem


Rust program that calculates the GCD (Greatest Common Divisor) 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();

    while num2 != 0 {
        let temp = num2;
        num2 = num1 % num2;
        num1 = temp;
    }

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

Output


Please enter two numbers:
24 36
The GCD of the two numbers is: 12{codeBox}

Explanation


In this example, we first use Rust's standard library's io module to read input from the user. We print a prompt to the console using println!("Please enter two numbers:");.

We then create a new String called input and use the stdin() function from the io module to read a line of input from the user into input.

We then use Rust's split_whitespace() method to split the input string into a vector of strings, each containing a single number. We then use Rust's map() method to parse each number string into an unsigned 32-bit integer. If the parsing is successful, we store the resulting integer in a Vec<u32> called nums. If the parsing fails, we print an error message and return early using return;.

We then use Rust's pop() method to remove the last two items from the nums vector and store them in num1 and num2, respectively.

We then use a while loop to calculate the GCD of num1 and num2 using the Euclidean algorithm. We keep updating num1 and num2 until num2 is equal to 0, at which point num1 will contain the GCD.

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

This shows the program prompting the user for input, the user entering the numbers 24 and 36, and the program calculating and displaying the GCD of the two numbers, which is 12.


Post a Comment