Rust program to calculate the GCD using recursion

Rust | Find GCD using Recursion: Given two numbers, we have to calculate the GCD using recursion.
Last Updated : October 11, 2021

Problem Statement

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

Program/Source Code

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

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

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

fn main() {
    let a:i32=45;
    let b:i32=75;
        
    let res = calculateGCD(a, b);
    println!("The GCD of {0} and {1} is {2}.", a, b, res);
}

Output

The GCD of 45 and 75 is 15.

Explanation

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

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

Rust Functions Programs »



Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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