最大公约数 欧几里得公式2022-04-05

最大公约数

求最大公约数,一般用欧几里得公式(也叫做辗转相除法)
公式:g(a,b)=g(b,a \% b)
java 代码

package basic.math04.divisor;

import java.util.Scanner;

/**
 * @author : ac_scl
 * @description :
 * @date : 2022/4/5  11:03 下午
 */
public class Gcd {
    static int gcd(int a, int b) {
        return b > 0 ? gcd(b, a % b) : a;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        while (n-- > 0) {
            int a = sc.nextInt();
            int b = sc.nextInt();

            System.out.println(gcd(a, b));
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。