Skip to content

Instantly share code, notes, and snippets.

@doraiso
Last active March 21, 2022 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doraiso/38f45b3fe9031326aa35956dbb0a2cd7 to your computer and use it in GitHub Desktop.
Save doraiso/38f45b3fe9031326aa35956dbb0a2cd7 to your computer and use it in GitHub Desktop.
/**
LCM_Sum.java
複数の最小公倍数の積を求める
Java program to calculate the product of multiple least common multiples.
**/
import java.util.ArrayList;
public class LCM_Sum {
public static void main(String[] args) {
int valueLCM = 0;
ArrayList<Integer> list = new ArrayList<>();
// TODO さらに複数の値にも対応できそう
list.add(2022);
list.add(3);
list.add(22);
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);
}
// Thanks
// https://qiita.com/ffstarter/items/58a716bff5e5846fde96
// https://www.jdoodle.com/online-java-compiler/
}
@doraiso
Copy link
Author

doraiso commented Mar 21, 2022

a little edit

@doraiso
Copy link
Author

doraiso commented Mar 21, 2022

Webコンパイラのコメント追記

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment