题解 | #求最小公倍数#

求最小公倍数

https://www.nowcoder.com/practice/22948c2cad484e0291350abad86136c3

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String x = in.nextLine();
            String []arrs = x.split(" ");
            if(arrs.length > 2 || arrs.length < 2) {
                System.out.println("输入数据不合法");
            } else {
                try {
                    int a = Integer.parseInt(arrs[0]);
                    int b = Integer.parseInt(arrs[1]);
                    if(b > 100000 || a < 1) {
                        System.out.println("输入的数据超过规定范围");
                    } else {
                        int s = calculateMin(a, b);
                        System.out.println(s);
                    }

                } catch(Exception e) {
                    System.out.println("输入的数据是字符串,不合法");
                }

            }

        }
    }

    /***
     * 求最小公倍数
     */
    private static int calculateMin(int a, int b) {

        for (int i = 1; i < Long.MAX_VALUE; i++) {
            if (i % a == 0 && i % b == 0) {
                return i;
            }
        }
        return 0;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务