解题思路: m和n的最大公约数一定在区间1到较小的那个数之间,最小公倍数一定在较小的那个数到m*n之间,所以找到较小的那个数是关键!
附图(主要部分):
注意事项: 能一次for循环的不要俩次!
参考代码:
import java.util.Scanner; public class Main { public static void greatestCommonDivisorAndLeastCommonMultiple(int m,int n){ int temVal = 0; int greatestCommonDivisor = 0; int leastCommonMultiple = 0; if(m <= 0||n<= 0)return; //找出较小的数m if(m>n){ temVal = m; m = n; n = temVal; } for(int i=1; i<=m*n; i++){ //最大公约数一定在[1,m] if(i <= m){ if(m%i==0&&n%i==0){ greatestCommonDivisor = i; } } //最小公倍数一定在[m,m*n] else { if(i%m==0&&i%n==0){ leastCommonMultiple = i; break; } } } System.out.print(greatestCommonDivisor+" "+leastCommonMultiple); } public static void main(String[] args) { int m,n; Scanner sc = new Scanner(System.in); m = sc.nextInt(); n = sc.nextInt(); greatestCommonDivisorAndLeastCommonMultiple(m,n); } }
ps:如果对您有帮助,别忘了点个赞再走,谢谢您的支持,祝您学习愉快^_^ !
0.0分
6 人评分