第五章第十四题(计算最大公约数)(Compute the greatest common divisor)

第五章第十四题(计算最大公约数)(Compute the greatest common divisor)

  • *5.14(计算最大公约数)下面是求两个整数n1和n2的最大公约数的程序清单5-9的另一种解法:首先找出n1和n2的最小值d,然后依次检验d, d–1, d–2, …, 2,1是否是n1和n2的公约数。第一个满足条件的公约数就是n1和n2的最大公约数。编写程序,提示用户输入两个正整数,然后显示最大公约数。
    *5.14(Compute the greatest common divisor)(Compute the greatest common divisor) Another solution for Listing 5.9 to find the greatest common divisor of two integers n1 and n2 is as follows: First find d to be the minimum of n1 and n2, then check whether d, d–1, d–2, …, 2, or 1 is a divisor for both n1 and n2 in this order. The first such common divisor is the greatest common divisor for n1 and n2. Write a program that prompts the user to enter two positive integers and displays the gcd.
  • 参考代码:
package chapter05;

import java.util.Scanner;

public class Code_14 {
    public static void main(String[] args) {
        int number1,number2,greatestCommonDivisor;

        System.out.print("Enter two integer numbers are sperate by space(e.g. 5 6): ");
        Scanner inputScanner = new Scanner(System.in);
        number1 = inputScanner.nextInt();
        number2 = inputScanner.nextInt();

        greatestCommonDivisor = (number1 > number2)?number2:number1;
        while(number1 % greatestCommonDivisor != 0 || number2 % greatestCommonDivisor != 0)
            greatestCommonDivisor--;
        System.out.println("The greatest common divisor for number1 and number2 is "
                + greatestCommonDivisor);

        inputScanner.close();
    }
}

  • 结果显示:
Enter two integer numbers are sperate by space(e.g. 5 6): 5 6
The greatest common divisor for number1 and number2 is 1

Process finished with exit code 0

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值