878917. GCD

Basic

Here is a detailed Markdown blog post for the GCD problem:

GCD

Summary

The Greatest Common Divisor (GCD) problem involves finding the largest positive integer that divides two given numbers without leaving a remainder. This fundamental concept in number theory has numerous applications in various areas of computer science and mathematics.

Detailed Explanation

To solve this problem, we can use the Euclidean algorithm, which is an efficient method for calculating the GCD of two integers. The basic idea is to repeatedly apply the following steps:

  1. If one number is zero, return the other number as the GCD.
  2. Otherwise, replace the larger number with the difference between the two numbers.

Here's a step-by-step breakdown of the solution:

  • Initialize a and b as the input integers.
  • While b is not zero:
    • Calculate r as the remainder of a divided by b.
    • Update a to be b, and b to be r.
  • Return a as the GCD.

The time complexity of this algorithm is O(log(min(a, b))), where min(a, b) is the minimum of the two input integers. This is because each iteration reduces the magnitude of one of the numbers by a factor of at least 2. The space complexity is O(1), as we only need a few variables to store the intermediate results.

Optimized Solutions

Java

View on GeeksforGeeks
public class GCD {
    public static int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return a;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.