我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!
天气: 晴朗
心情: 高兴
/*P3Q15
* Wang Chaoran
15 (Computing the greatest common divisor)
Another solution for Listing 4.6 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.
*/
import java.util.Scanner;
public class P3Q15
{
public static void main(String[] args)
{
int d=0;
int greatestCommondivisor=0;
//Create a scanner
Scanner scan = new Scanner(System.in);
//Read in the two integers
System.out.println("Please enter the first integer: ");
int n1 = scan.nextInt();
System.out.println("Please enter the second integer: ");
int n2 = scan.nextInt();
//Compute the greatest common divisor of the two numbers
if(n1>n2)
{
d=n1-n2;
}
else
{
d=n2-n1;
}
for(int i=1;i<=d;i++)
{
if(n1%i==0&&n2%i==0)
{
greatestCommondivisor=i;
}
}
//Display the greatest common divisor
System.out.println("The greatest common divisor for n1 and n2 is: "+greatestCommondivisor);
}
}
导入论坛查看(44)回复(0)引用(0)好评(0) 差评(0)
加入收藏
编辑
审核
TAG:
computing