等差数列

    public class 等差数列 {

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner sc = new Scanner(System.in);
            int N = sc.nextInt();
            int[] num = new int[N];
            for (int i = 0; i < N; i++) {
                num[i] = sc.nextInt();
            }
            sc.close();
            Arrays.sort(num);	//排序
            int[] cha = new int[N - 1];		//创建一个数组存差
            int min = Integer.MAX_VALUE;	//存最小的
            for (int i = 0; i < N - 1; i++) {
                cha[i] = num[i + 1] - num[i];                                         
                if (min > cha[i]) {
                    min = cha[i];
                }
            }
            int gcd = gcd(cha[0], cha[1]);
            for (int i = 2; i < cha.length; i++) {
                gcd = gcd(gcd, cha[i]);
            }
            System.out.println((num[N - 1] - num[0]) / gcd + 1);
        }
        
        public static int gcd(int x, int y) {
            if (y == 0) {
                return x;
            } else {
                return gcd(y, x % y);
            }
        }

}

您可能还喜欢...