java求两个数的最大公约数及最大公倍数


import java.util.Scanner;
public class Test01 {
    public static void main(String args[]) {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入两个正整数");
        int n1 =scanner.nextInt();
        int n2 =scanner.nextInt();
        int first=java.lang.Math.max(n1,n2);
        int second=java.lang.Math.min(n1,n2);
        System.out.println("请选择您要使用的方法:"+'\n'+"1.辗转相除法"+'\n'+"2.相减法"+'\n'+"3.穷举法");
        int method=scanner.nextInt();
        System.out.print(n1+","+n2+"的最大公约数是:"); 
        switch(method){
        case 1:
            System.out.println(method1(first,second));break;
        case 2:
            System.out.println(method2(first,second));break;
        case 3:
            System.out.println(method3(first,second));break;
        }
        System.out.println(n1+","+n2+"的最大公倍数是"+(n1*n2)/method1(first,second));
    }   
    //辗转相除法求最大公约数
    public static int method1(int first,int second){
        if(second==0)
            return first;
        return method1(second,first%second);

    }
    //相减法求最大公约数
    public static int method2(int first ,int second) {

        int i=first-second;
        while(i!=0) {
            first=second;
            second=i;
            i=first-second;
        }
        return second;
    }
    //穷举法求最大公约数
    public static int method3(int first ,int second) {
        int i= second;
        while(i>0) {
            if(first%i==0 && second%i==0) break;
            i--;
        }
        return i;
    }
}

你可能感兴趣的:(java求两个数的最大公约数及最大公倍数)