1 import java.util.Scanner; 2 3 public class lianxi06_1 { 4 public static void main(String[] args) { 5 Scanner s = new Scanner(System.in); 6 int m = s.nextInt(); 7 int n = s.nextInt(); 8 System.out.println("最大公约数:" + f(m, n)); 9 System.out.println("最小公倍数:" + m(m, n)); 10 } 11 12 public static int f(int m, int n) { 13 int c = m % n; 14 return c == 0 ? n : f(n, c); 15 } 16 17 public static int m(int m, int n) { 18 return (m * n / f(m, n)); 19 } 20 }
方法二:
/** *在循环中,只要除数不等于0,用较大数除以较小的数,将小的一个数作为下一轮循环的大数, * 取得的余数作为下一轮循环的较小的数,如此循环直到较小的数的值为0,返回较大的数,此数即为最大公约数, * 最小公倍数为两数之积除以最大公约数。 *在循环中,只要除数不等于0,用较大数除以较小的数, */ import java.util.*; public class lianxi06 { public static void main(String[] args) { int a ,b,m; Scanner s = new Scanner(System.in); System.out.print( "键入一个整数: "); a = s.nextInt(); System.out.print( "再键入一个整数: "); 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) { int t; if(x < y) { t = x; x = y; y = t; } while(y != 0) { if(x == y) return x; else { int k = x % y; x = y; y = k; } } return x; } }
原文:http://www.cnblogs.com/sosolili/p/4970528.html