×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby program to find the GCD of two given numbers using recursion

Last Updated : December 15, 2025

Problem Solution

In this program, we will read two integer numbers from the user and find the GCD of input numbers using recursion.

Program/Source Code

The source code to find the GCD of two given numbers using recursion is given below. The given program is compiled and executed successfully.

# Ruby program to find the GCD of 
# two given numbers using recursion

def calculateGCD(a, b)
    while (a != b)
        if a > b
            return calculateGCD(a - b, b);
        else
            return calculateGCD(a, b - a);
        end
    end
    
    return a;
end

print "Enter number1: ";
number1 = gets.chomp.to_i;  

print "Enter number2: ";
number2 = gets.chomp.to_i;  

result = calculateGCD(number1, number2);

print "GCD is: ",result;

Output

Enter number1: 45
Enter number2: 75
GCD is: 15

Explanation

In the above program, we read two integer numbers from the user. Then we found the GCD of input numbers using recursive function calculateGCD(). Then we printed the result.

Ruby User-defined Functions Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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