Here you can find the source of gcd(long[] array)
Parameter | Description |
---|---|
array | Input array |
public static long gcd(long[] array)
//package com.java2s; /******************************************************************************* * Copyright (c) 2016 Pablo Pavon-Marino. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors:/* w w w . j a va2 s . c o m*/ * Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1 * Pablo Pavon-Marino - from version 0.4.0 onwards ******************************************************************************/ import java.util.*; public class Main { /** * Computes the greatest absolute common divisor of an integer array. * * @param array Input array * @return The greatest absolute common divisor. By convention, {@code gcd(0, 0)} is equal to zero and {@code gcd([])} is equal to one * */ public static long gcd(long[] array) { if (array.length == 0) { return 1; } long[] maxMinValue = maxMinValues(array); long minAbsValue = Math.min(Math.abs(maxMinValue[0]), Math.abs(maxMinValue[1])); for (long i = minAbsValue; i >= 1; i--) { int j; for (j = 0; j < array.length; ++j) { if (Math.abs(array[j]) % i != 0) { break; } } if (j == array.length) { return i; } } return 1; } /** * Returns the maximum/minimum values of an input array. * * @param array Input array * @return Maximum/minimum values * */ public static long[] maxMinValues(long[] array) { if (array.length == 0) { throw new NoSuchElementException("Empty array"); } long maxValue = array[0]; long minValue = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > maxValue) { maxValue = array[i]; } if (array[i] < minValue) { minValue = array[i]; } } return arrayOf(maxValue, minValue); } /** * Generates a {@code long[]} from comma-separated values. * * @param values Comma-separated {@code long} values * @return {@code long[]} * */ public static long[] arrayOf(long... values) { return values; } }