Here you can find the source of gcdPositive(int a, int b)
Parameter | Description |
---|---|
a | Positive number. |
b | Positive number. |
private static int gcdPositive(int a, int b)
//package com.java2s; /*//from w ww .jav a2 s. c om * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** * Computes the greatest common divisor of two <em>positive</em> numbers * (this precondition is <em>not</em> checked and the result is undefined * if not fulfilled) using the "binary gcd" method which avoids division * and modulo operations. * See Knuth 4.5.2 algorithm B. * The algorithm is due to Josef Stein (1961). * <br/> * Special cases: * <ul> * <li>The result of {@code gcd(x, x)}, {@code gcd(0, x)} and * {@code gcd(x, 0)} is the value of {@code x}.</li> * <li>The invocation {@code gcd(0, 0)} is the only one which returns * {@code 0}.</li> * </ul> * * @param a Positive number. * @param b Positive number. * @return the greatest common divisor. */ private static int gcdPositive(int a, int b) { if (a == 0) { return b; } else if (b == 0) { return a; } // Make "a" and "b" odd, keeping track of common power of 2. final int aTwos = Integer.numberOfTrailingZeros(a); a >>= aTwos; final int bTwos = Integer.numberOfTrailingZeros(b); b >>= bTwos; final int shift = Math.min(aTwos, bTwos); // "a" and "b" are positive. // If a > b then "gdc(a, b)" is equal to "gcd(a - b, b)". // If a < b then "gcd(a, b)" is equal to "gcd(b - a, a)". // Hence, in the successive iterations: // "a" becomes the absolute difference of the current values, // "b" becomes the minimum of the current values. while (a != b) { final int delta = a - b; b = Math.min(a, b); a = Math.abs(delta); // Remove any power of 2 in "a" ("b" is guaranteed to be odd). a >>= Integer.numberOfTrailingZeros(a); } // Recover the common power of 2. return a << shift; } }