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

51 篇文章 19 订阅

## 第五章第十四题（计算最大公约数）(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
评论
03-12 4232
11-11 2554
06-16 2273
10-29 660
03-16 241
06-27 1196
04-25 251

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