기본 코드
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
System.out.println("== 합의 법칙 ==");
int[] dice1 = {1, 2, 3, 4, 5, 6};
int[] dice2 = {1, 2, 3, 4, 5, 6};
int nA = 0;
int nB = 0;
int nAandB = 0;
for (int item1 : dice1) {
for (int item2 : dice2) {
if ((item1 + item2) % 3 == 0) {
nA += 1;
}
if ((item1 + item2) % 4 == 0) {
nB += 1;
}
if ((item1 + item2) % 12 == 0) {
nAandB += 1;
}
}
}
System.out.println("결과: " + (nA + nB - nAandB));
HashSet<ArrayList> allCase = new HashSet<>();
for (int item1 : dice1) {
for (int item2 : dice2) {
if ((item1 + item2) % 3 == 0 || (item1 + item2) % 4 == 0) {
ArrayList list = new ArrayList(Arrays.asList(item1, item2));
allCase.add(list);
}
}
}
System.out.println("결과: " + allCase.size());
System.out.println("== 곱의 법칙 ==");
nA = 0;
nB = 0;
for (int item1 : dice1) {
if (item1 % 3 == 0) {
nA++;
}
}
for (int item2 : dice2) {
if (item2 % 4 == 0) {
nB++;
}
}
System.out.println("결과: " + (nA * nB));
}
}
약수구하기, 최대공약수&최소공배수 구하기
import java.util.ArrayList;
public class Practice1 {
public ArrayList getDivisor(int num) {
ArrayList result = new ArrayList();
for (int i = 1; i <= (int) num / 2; i++) {
if (num % i == 0) {
result.add(i);
}
}
result.add(num);
return result;
}
public int getGCD(int numA, int numB) {
int gcd = -1;
ArrayList divisorA = this.getDivisor(numA);
ArrayList divisorB = this.getDivisor(numB);
for (int itemA : (ArrayList<Integer>) divisorA) {
for (int itemB : (ArrayList<Integer>) divisorB) {
if (itemA == itemB) {
if (itemA > gcd) {
gcd = itemA;
}
}
}
}
return gcd;
}
public int getLCM(int numA, int numB) {
int lcm = -1;
int gcd = this.getGCD(numA, numB);
if (gcd != -1) {
lcm = numA * numB / gcd;
}
return lcm;
}
public static void main(String[] args) {
int number1 = 10;
int number2 = 6;
Practice1 p = new Practice1();
ArrayList l1 = p.getDivisor(number1);
ArrayList l2 = p.getDivisor(number2);
System.out.println("l1 = " + l1);
System.out.println("l2 = " + l2);
System.out.println("최대 공약수: " + p.getGCD(number1, number2));
System.out.println("최소 공배수: " + p.getLCM(number1, number2));
}
}