Finds the greatest common factor (also known as the greatest common divisor) of two numbers. - Java java.lang

Java examples for java.lang:Math Number

Description

Finds the greatest common factor (also known as the greatest common divisor) of two numbers.

Demo Code


//package com.java2s;

public class Main {
    /**//from w w w . j a  v a 2s .c  om
     * Finds the greatest common factor (also known as the greatest common
     * divisor) of two numbers.
     *
     * @param a
     *            the first value
     * @param b
     *            the second value
     * @return the greatest common factor of a and b
     */
    public static int greatestCommonFactor(int a, int b) {
        int larger = a > b ? a : b;
        int smaller = a < b ? a : b;

        int remainder;

        while (smaller != 0) {
            remainder = larger % smaller;
            larger = smaller;
            smaller = remainder;
        }

        return larger;
    }
}

Related Tutorials