第五章第十四题(计算最大公约数)(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;publicclassCode_14{publicstaticvoidmain(String[] args){int number1,number2,greatestCommonDivisor;
System.out.print("Enter two integer numbers are sperate by space(e.g. 5 6): ");
Scanner inputScanner =newScanner(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.56):56
The greatest common divisor for number1 and number2 is 1
Process finished with exit code 0