Q:

Rust program to find the GCD (Greatest Common Divisor)

belongs to collection: Rust Basic Programs

0

Here, we will read two integer numbers from the user. Then we will find the Greatest Common Divisor and print the result.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to find the GCD (Greatest Common Divisor) is given below. The given program is compiled and executed successfully.

// Rust program to find the GCD 
// (Greatest Common Divisor)

use std::io;

fn main() 
{
    let mut n1:i32 = 0;
    let mut n2:i32 = 0;
    let mut rem:i32= 0;
    let mut x:i32  = 0;
    let mut y:i32  = 0;
    
    let mut input1 = String::new();
    let mut input2 = String::new();
    
    println!("Enter Number1: ");
    io::stdin().read_line(&mut input1).expect("Not a valid string");
    n1 = input1.trim().parse().expect("Not a valid number");

    println!("Enter Number2: ");
    io::stdin().read_line(&mut input2).expect("Not a valid string");
    n2 = input2.trim().parse().expect("Not a valid number");
    
    if (n1 > n2) 
    {
        x = n1;
        y = n2;
    }
    else 
    {
        x = n2;
        y = n1;
    }

    rem = x % y;

    while (rem != 0) {
        x = y;
        y = rem;
        rem = x % y;
    }

    println!("Greatest Common Divisor is: {}", y);
}

Output:

RUN 1:
Enter Number1: 
30
Enter Number2: 
5
Greatest Common Divisor is: 5

RUN 2:
Enter Number1: 
21
Enter Number2: 
27
Greatest Common Divisor is: 3

Explanation:

Here, we read the value of n1n2 from the user. Then we found the GCD (Greatest Common Divisor) of n1 and n2. After that, we printed the result.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to find the LCM (Lowest Common Multip... >>
<< Rust program to find the roots of a quadratic equa...