第七章第十四题(计算gcd)(Calculate GCD)
-
7.14(计算gcd)编写一个方法,返回个数不确定的整数的最大公约数。给定方法头如下所示:
public static int gcd(int … numbers)
编写一个测试程序,题数用户输入5个数字,调用该方法找出这些书的最大公约数,并且显示这个最大公约数。
7.14(Calculate GCD)Calculate GCD write a method, return the number of uncertain integer of the greatest common divisor. The given method header is as follows:
public static int gcd(int … numbers)
Write a test program, the user input 5 numbers, call this method to find the greatest common divisor of these books, and display the maximum common divisor. -
参考代码:
package chapter07; import java.util.Scanner; public class Code_14 { public static void main(String[] args) { int[] numbers = new int[5]; Scanner input = new Scanner(System.in); System.out.print("Enter 5 numbers : "); for (int i = 0;i < 5;i++) numbers[i] = input.nextInt(); System.out.println("The largest gcd is " + gcd(numbers)); } public static int gcd(int ... numbers){ int min = numbers[0]; for (int i = 1;i < numbers.length;i++) if (min > numbers[i]) min = numbers[i]; for (;min > 0;min--) { int count = 0; for (int i = 0; i < numbers.length; i++) { if (numbers[i] % min == 0) count++; } if (count == numbers.length) break; } return min; } }
-
结果显示:
Enter 5 numbers : 10 20 30 40 50 The largest gcd is 10 Process finished with exit code 0