Rust program to calculate the HCF (Highest Common Factor)

Given two numbers, we have to find the Highest Common Factor (HCF) using Rust program.
Last Updated : September 28, 2021

Problem Statement

Here, we will read two integer numbers from the user and find the Highest Common Factor of given numbers.

Program/Source Code

The source code to calculate the HCF is given below. The given program is compiled and executed successfully.

// Rust program to calculate the HCF.

use std::io;

fn main() {
    let mut n1:u32 = 0;
    let mut n2:u32 = 0;
    let mut temp:u32 = 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");

    while(n2 != 0)
    {
        temp = n1 % n2;
        n1   = n2;
        n2   = temp;
    }
        
    println!("Highest Common Factor is: {}",n1);
}

Output

RUN 1:
Enter number1: 
5
Enter number2: 
36
Highest Common Factor is: 1

RUN 2:
Enter number1: 
30
Enter number2: 
75
Highest Common Factor is: 15

Explanation

Here, we read the value of n1, n2 from the user. Then we calculated the Highest Common Factor (HCF) of given numbers and printed the result.

Rust Basic Programs »



Related Programs

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.