Java gcd gcd(int num1, int num2)

Here you can find the source of gcd(int num1, int num2)

Description

Returns the greatest common divisor of two integers.

License

LGPL

Parameter

Parameter Description
num1 The first number
num2 The second number

Return

The greatest common divisor

Declaration

public static int gcd(int num1, int num2) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

public class Main {
    /**/* www.j  av a 2  s  .  c  o m*/
     * Returns the greatest common divisor of two integers.
     * 
     * @param num1 The first number
     * @param num2 The second number
     * @return The greatest common divisor
     */
    public static int gcd(int num1, int num2) {
        if (num1 < 0)
            num1 = -num1;
        if (num2 < 0)
            num2 = -num2;
        return privGCD(num1, num2);
    }

    /**
     * Returns the greatest common divisor of two non-negative integers.
     * 
     * @param num1 The first number; must be non-negative
     * @param num2 The second number; must be non-negative
     * @return The greatest common divisor
     */
    private static int privGCD(int num1, int num2) {
        if (num1 == 0 && num2 == 0)
            return 1;
        if (num1 == 0)
            return num2;
        if (num2 == 0)
            return num1;
        return num1 > num2 ? privGCD(num1 % num2, num2) : privGCD(num1, num2 % num1);
    }
}

Related

  1. gcd(int m, int n)
  2. GCD(int m, int n)
  3. gcd(int m, int n)
  4. gcd(int n, int m)
  5. gcd(int n1, int n2)
  6. gcd(int p, int q)
  7. gcd(int p, int q)
  8. gcd(int u, int v)
  9. gcd(int u, int v)