VOOZH about

URL: https://www.geeksforgeeks.org/interview-experiences/tcs-coding-practice-question-hcf-or-gcd-of-2-numbers/

⇱ TCS Coding Practice Question | HCF or GCD of 2 Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TCS Coding Practice Question | HCF or GCD of 2 Numbers

Last Updated : 11 Jul, 2025

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. πŸ‘ Image
Examples:

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

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

Approach:

  • Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line
  • Extract the input numbers from the command line argument
  • This extracted numbers will be in String type.
  • Convert these numbers into integer type and store it in variables, say num1 and num2
  • Find the HCF of the numbers. An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number.
  • Print or return the HCF

Program: 

Output:

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

Comment