求俩数的最大公约数(一):
package test01; import java.util.Scanner; 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); } }
效果如下图所示:
求俩数的最大公约数(二)
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); } }
效果如下图所示:
接着最大公约数,我们再来求最小公倍数:
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); } }
效果如下图所示:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)