java 公因数_Java程序(最大公因数与最小公倍数)
package 求兩個(gè)數(shù)的公約數(shù)和公倍數(shù);
import java.util.Scanner;
public class MN
{
public static void swap(int a,int b)//交換位置
{
int k;
if(a
{
k=a;
a=b;
b=k;
}
}
static int shu(int a,int b)//循環(huán)尋找最大公約數(shù)
{
int k,y;
swap(a,b);
while(a%b!=0)
{
y=a%b;
a=b;
b=y;
}
return b;
}
static int shu2(int a,int b)//運(yùn)用遞歸
{
int k,y;
swap(a,b);
y=a%b;
if(a%b==0)
return b;
else
{
a=b;
b=y;
return shu2(a,b);
}
}
static int beishu(int a,int b,int l)//求最小公倍數(shù)的公式為:a*b除以最大公約數(shù)
{
int k;
k=(a*b)/l;
return k;
}
public static void main(String[] args)
{
int a,b,j,l,l2;
Scanner s=new Scanner(System.in);
System.out.println("請(qǐng)輸入兩個(gè)數(shù):");
a=s.nextInt();
b=s.nextInt();
l=shu2(a,b);
System.out.println("循環(huán)求得最大公約數(shù)為:");
System.out.println(l);
System.out.println("遞歸求得最大公約數(shù)為:");
l2=shu2(a,b);
System.out.println(l2);
System.out.println("最小公倍數(shù)為:");
j=beishu(a,b,l);
System.out.println(j);
}
}
總結(jié)
以上是生活随笔為你收集整理的java 公因数_Java程序(最大公因数与最小公倍数)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “留得五湖明月在,不愁无处下金钩“太经典
- 下一篇: Java实现智能对话机器人自动聊天+语音