private static int GcdOfMany(int[] numbers, GcdSolverDelegate gcdSolver) { int gcd = numbers[0]; for (int i = 1; i < numbers.Length; i++) { gcd = gcdSolver(gcd, numbers[i]); if (gcd == 1) { return(1); } } return(gcd); }
/// <summary> /// Calculates the greatest common divisor of three numbers by Stein's algorithm, the non recursive implementation. /// </summary> /// <exception cref="ArgumentException">Thrown when gcd(0, int.MinValue) or gcd(int.MinValue,int.MinValue) is calculated, because the answer is -int.MinValue and -int.MinValue = int.MaxValue + 1.</exception> public static int GcdByStein(params int[] numbers) { var gcdSolver = new GcdSolverDelegate(GcdByStein); return(GcdOfMany(numbers, gcdSolver)); }