JAVA小实例(九)

 求俩数的最大公约数(一):

package test01;

import java.util.Scanner;

/*
 * 求a和b的最大公约数
 */
public class Gongyue {
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		System.out.println("请依次输入a和b:");
		int a = in.nextInt();
		int b =in.nextInt();
		int gcd = 1;
		for(int i=2;i<=a&&i<=b;i++)
		{
			if(a%i==0&&b%i==0)
			{
				gcd = i;
			}
		}
		System.out.println(a+"和"+b+"的最大公约数为:"+gcd);
				
	}
}

效果如下图所示:

JAVA小实例(九)

求俩数的最大公约数(二) 

package test01;

import java.util.Scanner;

/*
 * 用辗转相除法计算俩数的最大公约数
 */
public class Gongyue02 {
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		System.out.println("请输入a和b:");
		int a = in.nextInt();
		int b = in.nextInt();
		int oa = a;
		int ob = b;
		while(b!=0)
		{
			int r = a%b;
			System.out.println(a+","+b+","+r);
			a=b;
			b=r;
		}
		System.out.println(oa+"和"+ob+"的最大公约数是:"+a);
	}
}

 效果如下图所示:

JAVA小实例(九)

接着最大公约数,我们再来求最小公倍数:

package test01;
/*
 * 算俩个数的最小公倍数=俩数乘积除以最大公约数
 */

import java.util.Scanner;

public class Gongbei {
	public static void main(String[] args){
	Scanner in = new Scanner(System.in);
	System.out.println("请依次输入a和b:");
	int a = in.nextInt();
	int b = in.nextInt();
	int gcd = 1;
	int cj;
	int gbs;
	for(int i=2;i<=a&&i<=b;i++)
	{
		if(a%i==0&&b%i==0)
		{
			gcd = i;
		}
	}
	cj = a*b;
	gbs = cj / gcd;
	System.out.println(a+"和"+b+"的最小公倍数为:"+gbs);
}

}

 效果如下图所示:

JAVA小实例(九)

 

 

上一篇:Spark系列(六)Master注册机制和状态改变机制


下一篇:2041. 干草堆