TopcoderArchiveVisit Topcoder
Archive
Algorithm problem

GCD

Problem statement, definition, constraints, and public examples.

Problem Statement

The greatest common divisor (GCD) of two numbers is the largest number that evenly divides both of those two numbers. For example, the GCD of 30 and 48 is 6 because both 30 and 48 are exactly divisible by 6, and there is no number greater than 6 that evenly divides both 30 and 48. To be more precise, a number, n, is evenly divisible by another number, m, if n divided by m is an integer.

Your task is to write a class GCD with a method gcd, which takes two ints, a and b, and returns their GCD. Note that the GCD of two numbers is always at least 1.

Definition

Class:
GCD
Method:
gcd
Parameters:
int, int
Returns:
int
Method signature:
int gcd(int a, int b)
(be sure your method is public)

Notes

  • The GCD of any number and 0 is the absolute value of that number. The GCD of 0 and 0 is undefined, so that input will not be allowed.

Constraints

  • Both a and b will be between -1,000,000 and 1,000,000, inclusive.
  • a and b will not both be 0.

Examples

  1. 30
    48
    Returns: 6
    This is the example from the problem statement.
  2. -30
    -48
    Returns: 6
    6 still divides both of these numbers evenly.
  3. -5
    0
    Returns: 5
  4. 94572
    156762
    Returns: 18
  5. -5
    7
    Returns: 1
  6. 1000000
    1000000
    Returns: 1000000
  7. 0
    -2
    Returns: 2
Back to all problems