java黑皮书课后习题7.14

import java.util.Scanner;

public class Exercise07_14 {
    public static void main(String[] args) {
        java.util.Scanner sc = new java.util.Scanner(System.in);
        System.out.println("Enter 5 integer:");//整数
        int[] numbers = new int[5];
        for(int i = 0; i < numbers.length; i++){
            numbers[i] = sc.nextInt();//用户输入5个数字并存入数组
        }
        System.out.println("Greatest common divisor is " + gcd(numbers));
    }

    public static int gcd(int... numbers) {
        java.util.Arrays.sort(numbers);//排序
        int d = numbers[0];//找到数组最小值,依次检验d,d-1,d-2···,2,1是否是5个整数的共同公约数,第一个满足条件的为最大公约数
        while (d > 1){
            if (numbers[0] % d == 0 && numbers[1] % d == 0 && numbers[2] % d == 0 && numbers[3] % d == 0 && numbers[4] % d == 0)
                return d;
            d--;
        }
        return 1;
    }
}
上一篇:两数之和


下一篇:Leetcode 2157 字符串分组