LoginSignup
1
1

More than 3 years have passed since last update.

Javaで複数値の最小公倍数を求めるサンプルソースコード

Posted at

ソースコード

Main.java
package src;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        int valueLCM = 0;
        ArrayList<Integer> list = new ArrayList<>();
        list.add(4);
        list.add(6);
        list.add(9);

        for(int index=0; index<list.size()-1; index++) {
            if( index==0 ) {
                valueLCM = calcLCM( list.get(index), list.get(index+1) );
            } else {
                valueLCM = calcLCM( valueLCM,        list.get(index+1) );
            }
        }
        System.out.println(valueLCM);
    }

    private static int calcLCM(int val1, int val2) {
        int maxValue = Math.max(val1, val2);
        int minValue = Math.min(val1, val2);
        long val3    = maxValue * minValue;

        if(minValue==0) return maxValue;

        int temp;
        while( (temp=maxValue%minValue)!=0 ) {
            maxValue=minValue;
            minValue=temp;
        }

        return (int)(val3/minValue);
    }

}

補足

ユークリッドの互除法による最大公約数を求めてから、
最小公倍数を求める。

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1