Tutorialspoint
Problem
Solution
Submissions

Find the GCD (Greatest Common Divisor) of Two Numbers

Certification: Basic Level Accuracy: 55.17% Submissions: 116 Points: 5

Write a Python program that finds the Greatest Common Divisor (GCD) of two positive integers.

Example 1
  • Input: a = 48, b = 18
  • Output: 6
  • Explanation:
    • Step 1: Take two numbers a = 48 and b = 18 as input.
    • Step 2: Find factors of 48: 1, 2, 3, 4, 6, 8, 12, 16, 24, 48.
    • Step 3: Find factors of 18: 1, 2, 3, 6, 9, 18.
    • Step 4: Find the largest common factor: 6.
    • Step 5: Return 6 as the GCD.
Example 2
  • Input: a = 17, b = 5
  • Output: 1
  • Explanation:
    • Step 1: Take two numbers a = 17 and b = 5 as input.
    • Step 2: Find factors of 17: 1, 17.
    • Step 3: Find factors of 5: 1, 5.
    • Step 4: Find the largest common factor: 1.
    • Step 5: Return 1 as the GCD.
Constraints
  • 1 ≤ a, b ≤ 10^9
  • Time Complexity: O(log(min(a, b)))
  • Space Complexity: O(1)
RecursionFacebookTCS (Tata Consultancy Services)
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Euclidean algorithm: gcd(a, b) = gcd(b, a % b)
  • Recursive implementation: if b == 0, return a; else return gcd(b, a % b)
  • Iterative implementation: while b != 0: a, b = b, a % b; return a

The following are the steps to find the GCD of two numbers:

  • Define the function gcd(a, b).
  • Use a while loop to apply the Euclidean algorithm: a, b = b, a % b.
  • Return a when b becomes 0.
  • Call the function and print the result.

Submitted Code :