第七章第十四题(计算gcd)(Calculate GCD)

第七章第十四题(计算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
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值