Calculates greatest common divisor (GCD) of two numbers. - Java java.lang

Java examples for java.lang:Math Number

Description

Calculates greatest common divisor (GCD) of two numbers.

Demo Code

// Copyright (C) GridGain Systems, Inc. Licensed under GPLv3, http://www.gnu.org/licenses/gpl.html
//package com.java2s;

public class Main {
    /**/*from   w  ww .jav a2 s. c  o  m*/
     * Calculates greatest common divisor (GCD) of two numbers.
     *
     * @param a First number.
     * @param b Second number.
     * @return Greatest common divisor.
     */
    static int getGCD(int a, int b) {
        int x;
        int y;

        if (a > b) {
            x = a;
            y = b;
        } else {
            x = b;
            y = a;
        }

        int z = x % y;

        return (z == 0) ? y : getGCD(z, y);
    }
}

Related Tutorials