Rust program to calculate the HCF using recursion

Rust | Find HCF using Recursion: Given two numbers, we have to calculate the HCF using recursion.
Submitted by Nidhi, on October 11, 2021

Problem Solution:

In this program, we will create a recursive function to calculate the HCF and return the result to the calling function.

Program/Source Code:

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

// Rust program to calculate the 
// HCF using recursion

fn calculateHCF(a:i32, b:i32)->i32
{
    while a != b
    {
        if a > b
        {
            return calculateHCF(a - b, b);
        }
        else
        {
            return calculateHCF(a, b - a);
        }
    }
    
    return a;
}

fn main() {
    let a:i32=36;
    let b:i32=48;
        
    let res = calculateHCF(a, b);
    println!("The HCF of {0} and {1} is {2}.", a, b, res);
}

Output:

The HCF of 36 and 48 is 12.

Explanation:

In the above program, we created two functions calculateHCF() and main(). The calculateHCF() function is a recursive function, which is used to calculate the HCF of two numbers and return the result to the calling function.

In the main() function, we called the calculateHCF() function and printed the result.

Rust Functions Programs »





Comments and Discussions!

Load comments ↻





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