编写方法,返回个数不确定的整数的最大公约数:
public static int gcd(int… numbers)
编写一个测试程序,提示用户输入5个数字,调用该方法找出这些数的最大公约数,并显示这个最大公约数。
package pack2;
import java.util.Scanner;
import java.util.Stack;
public class ComputeGCD {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter number: ");
int[] list = new int[input.nextInt()];
System.out.print("Enter "+list.length+" numbers: ");
for (int i = 0; i < list.length; i++)
list[i] = input.nextInt();
System.out.println("The gcd is "+gcd(list));
}
}
/**最大公约数*/
public static int gcd(int...numbers) {
Stack<Integer> stack = new Stack<>(); //创建栈
//数组元素入栈
for (int i : numbers)
stack.push(i);
//处理栈中元素
while(stack.size() > 1)
stack.push(gcd(stack.pop(), stack.pop()));
return stack.pop();
}
/**最大公约数(欧几里得法)*/
public static int gcd(int m, int n) {
return m % n == 0 ? n : gcd(n, m % n);
}
}