黑马程序员技术交流社区
标题:
公约数和公倍数的2中解法,提供分享
[打印本页]
作者:
knockout
时间:
2015-9-5 01:09
标题:
公约数和公倍数的2中解法,提供分享
/*
【程序6】
题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
程序分析:利用辗除法。
*/
// 方法一: 对m和n同时除一个数,如果能同时整除,则取这个数的最大值即为最大公约数。
import java.util.Scanner;
class GongYueAndGongBei
{
public static void main(String[] args)
{
getGongYueAndGongBei();
}
public static void getGongYueAndGongBei()
{
Scanner sc = new Scanner(System.in);
System.out.println("请输入正整数m:");
int m=sc.nextInt();
System.out.println("请输入正整数n:");
int n=sc.nextInt();
if(m<=0||n<=0)
{
System.out.println("数据输入有误,请重新输入!");
getGongYueAndGongBei();
}
else
{
int max=m>=n?m:n;
int min=m>n?n:m;
int maxGongYue=1;
for(int i=1;i<=min;i++)
{
if(m%i==0&&n%i==0)
{
maxGongYue=i;
}
}
int minGongBei=m*n/maxGongYue;
System.out.println(m+"和"+n+"的最大公约数为:"+maxGongYue);
System.out.println(m+"和"+n+"的最小公倍数为:"+minGongBei);
}
}
}
//方法二: 利用辗除法。
/*
import java.util.*;
class GongYueAndGongBei
{
public static void main(String[] args)
{
int a,b,m;
Scanner s=new Scanner(System.in);
System.out.println("请键入一个正整数:");
a=s.nextInt();
System.out.println("请再键入一个正整数:");
b=s.nextInt();
deff cd=new deff();
m=cd.deff(a,b);
int n=a*b/m;
System.out.println("最大公约数为:"+m);
System.out.println("最小公倍数为:"+n);
}
}
class deff
{
public int deff(int x,int y)
{
while(y!=0)
{
if(x==y)
return x;
else
{
int k=x%y;
x=y;
y=k;
}
}
return x;
}
}
*/
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2