: 어떤 사건에서 일어날 수 있는 경우의 가짓 수
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// 합의 법칙
// 두 개의 주사위를 던졌을 때, 합이 3 또는 4의 배수일 경우의 수
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) { // 주사위 두개로 이중 for 문
if ((item1 + item2) % 3 == 0) { // 3으로 나눈 나머지가 0 = 3의 배수
nA+=1;
}
if ((item1 + item2) % 4 == 0) { // 4으로 나눈 나머지가 0 = 4의 배수
nB +=1;
}
if ((item1 + item2) % 12 == 0) { // 12로 나눈 나머지가 0 = 3과 4의 공배수
nAandB += 1;
}
}
}
System.out.println("결과 : " + (nA + nB - nAandB));
// HashSet 이용한 풀이
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());
// 곱의 법칙
// 두 개의 주사위 a, b를 던졌을 때, a는 3의 배수, b는 4의 배수인 경우의 수
nA = 0;
nB = 0;
for (int item1: dice1) {
if (item1 % 3 == 0) {
nA++;
}
}
for (int item1: dice2) {
if (item1 % 4 == 0) {
nB++;
}
}
System.out.println("결과 : " + (nA * nB));
}
}
import java.util.ArrayList;
// 약수 구하기, 두 수의 최대공약수와 최소공배수 구하기
// -> 쉬운 문제에 해당하지만, 해당 개념을 응용해서 출제 빈도 높음
// 1. 1 - 10 의 수 중, A의 약수 또는 B의 약수인 경우의 수
// 2. 1 - 10 의 수 중, A의 약수이면서, B의 약수인 경우의 수
class Practice {
// 약수
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;
}
// 최대 공약수, GCD (the Greatest Common Denominator)
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보다 크면,
gcd = itemA; // gcd에 그 값이 할당
}
}
}
}
return gcd;
}
// 최소 공배수, LCM
// LCM : the Lowest Common Multiple
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 class Main {
public static void main(String[] args) {
// Test code
int num1 = 10;
int num2 = 6;
Practice p = new Practice();
ArrayList l1 = p.getDivisor(num1);
ArrayList l2 = p.getDivisor(num2);
System.out.println("l1 = " + l1);
System.out.println("l2 = " + l2);
System.out.println("최대 공약수 : " + p.getGCD(num1, num2));
System.out.println("최소 공배수 : " + p.getLCM(num1, num2));
}
}