<aside> π λͺ©μ°¨
</aside>
λ μμ μ΅μ곡배μ(Least Common Multiple)λ μ λ ₯λ λ μμ λ°°μ μ€ κ³΅ν΅μ΄ λλ κ°μ₯ μμ μ«μλ₯Ό μλ―Έν©λλ€. μλ₯Ό λ€μ΄ 2μ 7μ μ΅μ곡배μλ 14κ° λ©λλ€. μ μλ₯Ό νμ₯ν΄μ, nκ°μ μμ μ΅μ곡배μλ n κ°μ μλ€μ λ°°μ μ€ κ³΅ν΅μ΄ λλ κ°μ₯ μμ μ«μκ° λ©λλ€. nκ°μ μ«μλ₯Ό λ΄μ λ°°μ΄ arrμ΄ μ λ ₯λμμ λ μ΄ μλ€μ μ΅μ곡배μλ₯Ό λ°ννλ ν¨μ, solutionμ μμ±ν΄ μ£ΌμΈμ.
arr | result |
---|---|
[2,6,8,14] | 168 |
[1,2,3] | 6 |
public class Solution {
// νλ‘κ·Έλλ¨Έμ€ LEVEL2 Nκ°μ μ΅μ곡배μ
// λ¬Έμ URL : <https://programmers.co.kr/learn/courses/30/lessons/12953>
public int solution(int[] arr) {
// κ°μ₯ μμ κ°μΈ 1λ‘ μ΄κΈ°ν
int answer = 1;
for (int i = 0; i < arr.length; i++) {
answer = (answer * arr[i]) / this.gcd(answer, arr[i]);
}
return answer;
}
// μ΅λ곡μ½μ ꡬνλ λ©μλ
public int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
<aside> <img src="https://raw.githubusercontent.com/eirikmadland/notion-icons/master/v5/icon3/ul-github.svg" alt="https://raw.githubusercontent.com/eirikmadland/notion-icons/master/v5/icon3/ul-github.svg" width="40px" /> μ°Έμ‘° Github Code
</aside>
// μ΅λ곡μ½μ ꡬνλ λ©μλ
public int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public int gcd(int a, int b) {
int x = Math.min(a, b);
int y = Math.max(a, b);
int temp = 0;
while(x != 0) {
temp = y;
y = x;
x = temp % x;
}
return y;
}