Last active
March 21, 2022 19:26
-
-
Save doraiso/38f45b3fe9031326aa35956dbb0a2cd7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a little edit