辗转相除法 求最大公因数 Java

2023-07-30 10:44:35 浏览数 (1)

原版

代码语言:javascript复制
import java.util.Scanner;
public class studying {
    private static int euclid(int a,int b){
        while(b!=0){
            int r=a%b;
            a=b;
            b=r;
        }
        return a;
    }
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int a=input.nextInt(),b=input.nextInt();
        System.out.println(euclid(a,b));
    }
}

函数递归调用版本

代码语言:javascript复制
import java.util.Scanner;
public class studying {
    private static int euclid(int a,int b){
        if(a%b==0)
            return b;
        return euclid(b,a%b);
    }
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int a=input.nextInt(),b=input.nextInt();
        System.out.println(euclid(a,b));
    }
}

0 人点赞