手撸代码系列(八)

第八期:实现求三个数的最小公倍数

本题为2013年蓝桥杯真题之核桃的数量

题目分析:以2,4,5为例

第一步: 求出这三个数中的最大值。

第二步:利用最大值去除以这三个数,如果都能整除,说明该最大值即为三个数的最小公倍数。

第三步:如果存在不能整除的数,那么max+1操作,进行第二步操作,如果还是不能全部整除则继续 max+1操作,直到都能整除,即可。

Java代码:
import java.util.Scanner;
public class LCM {
    public static void main(String[] args) {
        input();
    }
    private static void input() {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = scanner.nextInt();
        f(a,b,c);
        scanner.close();
    }
    private static void f(int a, int b, int c) {
        int max = g(a,b,c);
        //System.out.println(max);
        while (true){
            if (max%a==0 && max%b==0 && max%c==0){
                System.out.println(max);
                return;
            }else {
                max++;
            }
        }
    }
    private static int g(int a, int b, int c) {
        int result = a;
        if (a<b){
            result = b;
        }
        if (result<c)
            result = c;
        return result;
    }
}

本人为算法渣渣,代码写得不够精炼,如有大神望指点。

发布了8 篇原创文章 · 获赞 0 · 访问量 45

猜你喜欢

转载自blog.csdn.net/qq_36565596/article/details/105030093
今日推荐