最小公倍数

问题描述

求两个正整数的最小公倍数。

实现

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        Scanner in=new Scanner(System.in);
        int firstNum = in.nextInt();
        int secondNum = in.nextInt();
        System.out.println(getLCM(firstNum,secondNum));
    }

    /**
     * 求firstNum和secondNum等于那些质数相乘;
     * 如firstNum=n1*n1*n1*n2; secondNum=n1*n1*n2*n3;
     * 那么最小公倍数=n1*n1*n1*n2*n3(n1,n2,n3全部为质数)
     * @param firstNum
     * @param secondNum
     * @return firstNum 和secondNum的最小公倍数
     */
    public static int getLCM(int firstNum,int secondNum){
        int LeastCommonMultiple = 1;
        int max = Math.max(firstNum, secondNum);
        for (int i = 2; i <= max; i++) {
            int firstCount = 1;
            while (firstNum % i == 0) {
                firstNum /= i;
                firstCount *= i;
            }
            int secondCount = 1;
            while (secondNum % i == 0) {
                secondNum /= i;
                secondCount *= i;
            }
            int maxCount = Math.max(firstCount, secondCount);
            if (maxCount != 1)
                LeastCommonMultiple *= maxCount;
            max = Math.max(firstNum, secondNum);
        }
        return LeastCommonMultiple;
    }
}

你可能感兴趣的:(最小公倍数,日常练习)