Open In App

TCS Coding Practice Question | HCF or GCD of 2 Numbers

Given two numbers, the task is to find the HCF of two numbers using Command Line Arguments. GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples:

Input: n1 = 10, n2 = 20
Output: 10

Input: n1 = 100, n2 = 101
Output: 1

Approach:



Program: 




// C program to compute the HCF of two numbers
// using command line arguments
 
#include <stdio.h>
#include <stdlib.h> /* atoi */
 
// Function to compute the HCF of two numbers
int HCF(int a, int b)
{
    if (b == 0)
        return a;
 
    return HCF(b, a % b);
}
 
// Driver code
int main(int argc, char* argv[])
{
 
    int num1, num2;
 
    // Check if the length of args array is 1
    if (argc == 1)
        printf("No command line arguments found.\n");
 
    else {
 
        // Get the command line argument and
        // Convert it from string type to integer type
        // using function "atoi( argument)"
        num1 = atoi(argv[1]);
        num2 = atoi(argv[2]);
 
        // Find the HCF and print it
        printf("%d\n", HCF(num1, num2));
    }
    return 0;
}




// Java program to compute the HCF of two numbers
// using command line arguments
 
class GFG {
 
    // Function to compute the HCF of two numbers
    static int HCF(int a, int b)
    {
        if (b == 0)
            return a;
 
        return HCF(b, a % b);
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Check if length of args array is
        // greater than 0
        if (args.length > 0) {
 
            // Get the command line argument and
            // Convert it from string type to integer type
            int num1 = Integer.parseInt(args[0]);
            int num2 = Integer.parseInt(args[1]);
 
            // Find the HCF
            int res = HCF(num1, num2);
 
            // Print the HCF
            System.out.println(res);
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}

Output:



Time Complexity: O(log(min(num1,num2)))
Auxiliary Space: O(1)


Article Tags :