Tutorialspoint
Problem
Solution
Submissions

GCD of Two Numbers

Certification: Basic Level Accuracy: 80% Submissions: 5 Points: 5

Write a C++ program that finds the Greatest Common Divisor (GCD) of two positive integers using the Euclidean algorithm.

Example 1
  • Input: a = 48, b = 18
  • Output: 6
  • Explanation:
    • Step 1: Apply the Euclidean algorithm: gcd(a, b) = gcd(b, a % b) until b becomes 0.
    • Step 2: gcd(48, 18) = gcd(18, 48 % 18) = gcd(18, 12).
    • Step 3: gcd(18, 12) = gcd(12, 18 % 12) = gcd(12, 6).
    • Step 4: gcd(12, 6) = gcd(6, 12 % 6) = gcd(6, 0).
    • Step 5: When b becomes 0, the GCD is the value of a, which is 6.
Example 2
  • Input: a = 13, b = 7
  • Output: 1
  • Explanation:
    • Step 1: Apply the Euclidean algorithm: gcd(a, b) = gcd(b, a % b) until b becomes 0.
    • Step 2: gcd(13, 7) = gcd(7, 13 % 7) = gcd(7, 6).
    • Step 3: gcd(7, 6) = gcd(6, 7 % 6) = gcd(6, 1).
    • Step 4: gcd(6, 1) = gcd(1, 6 % 1) = gcd(1, 0).
    • Step 5: When b becomes 0, the GCD is the value of a, which is 1.
Constraints
  • 1 ≤ a, b ≤ 10^9
  • Both inputs are positive integers
  • Time Complexity: O(log(min(a, b)))
  • Space Complexity: O(1)
RecursionAlgorithmsHCL TechnologiesSwiggy
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

  • The Euclidean algorithm states that gcd(a, b) = gcd(b, a % b)
  • Use recursion or iteration to implement the algorithm
  • The base case is when the second number becomes 0, then the GCD is the first number

Steps to solve by this approach:

 Step 1: Define a function find_gcd that takes two integers a and b.

 Step 2: Implement the Euclidean algorithm using a while loop that continues until b becomes 0.
 Step 3: In each iteration, set a temporary variable to b, update b to a % b, and update a to the temporary variable.
 Step 4: Return a, which will be the GCD when the loop terminates.

Submitted Code :