使用 Java 计算数组中数字的 GCD
程序
以下示例演示如何计算数组中数字的 GCD。
public class GCDOfArrayofNumbers{ public static int gcd(int a,int b){ int res = 0; while (b > 0){ int temp = b; b = a % b; a = temp; res = a; } return res; } public static void main(String arg[]){ int[] myArray = {3, 6, 8}; int result = gcd(myArray[0],myArray[1]); for(int i = 2; i < myArray.length; i++){ result = gcd(result, myArray[i]); } System.out.println("Gcd of n numbers is: "+result); } }
输出
GCD of n numbers is: 1
广告