最大公约数和最小公倍数问题(洛谷P1029题题解,Java语言描述)

题目要求

P1029题目链接

在这里插入图片描述

分析

伟大的结论先亮出来:
最大公约数和最小公倍数的乘积就是原两个数的积。

此时我们知道了数学的重要性,哈哈……
知道了这个事,写代码就容易了呢~~

需要用gcd(),我觉得用BigInteger的gcd()反而麻烦,就自己写一下好了:

private static int gcd(int x,int y) {
    if(y==0) {
        return x;
    }
    return gcd(y, x % y);
}

Note:
gcd()表示辗转相除法,就算你没算法基础,高中数学必修三也该学了,所以应该问题不大的,对了,该算法也称欧几里得算法

AC代码(Java语言描述)

import java.util.Scanner;

public class Main {

    private static int gcd(int x,int y) {
        if(y==0) {
            return x;
        }
        return gcd(y, x % y);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt(), y = scanner.nextInt();
        scanner.close();
        int counter = 0;
        for (int i = 1; i <= Math.sqrt(x*y); i++) {
            if ((x * y) % i == 0 && gcd(i, (x * y) / i) == x) {
                counter++;
            }
        }
        System.out.println(counter*2);
    }

}
发布了479 篇原创文章 · 获赞 972 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/104129681
今日推荐