Algorithm
[Algorithm] μλΌν μ€ν λ€μ€μ 체
kexon
2022. 7. 9. 13:14
π μλΌν μ€ν λ€μ€μ 체?
- κ³ λ κ·Έλ¦¬μ€ μνμ μλΌν μ€ν λ€μ€κ° λ°κ²¬ν μμ νλ³ μκ³ λ¦¬μ¦
π€ μ½μ(Divisor)?
- 1κ³Ό μκΈ° μμ μΈ μ½μλ₯Ό κ°μ§μ§ μλ 1λ³΄λ€ ν° μμ°μ
π€ μμ(Prime Number)?
- μ΄λ€ μλ₯Ό λλ λ¨μ΄μ§κ² νλ μ
π μκ³ λ¦¬μ¦
- 2λΆν° μμλ₯Ό ꡬνκ³ μ νλ ꡬκ°μ λͺ¨λ μ λμ΄ (맨 μ²μ νμ)
- 2 == μμ (λΉ¨κ°μ)
- Prime numbers: 2
- μκΈ° μμ μ μ μΈν 2μ λ°°μ μ κ±°
- λ¨μμλ μ μ€, 3 == μμ (μ΄λ‘μ)
- Prime numbers: 2 3
- μκΈ° μμ μ μ μΈν 3μ λ°°μ μ κ±°
- λ¨μμλ μ μ€, 5 == μμ (νλμ)
- Prime numbers: 2 3 5
- μκΈ° μμ μ μ μΈν 5μ λ°°μ μ κ±°
- λ¨μμλ μ , 7 == μμ (λ
Έλμ)
- Prime numbers: 2 3 5 7
- μκΈ° μμ μ μ μΈν 7μ λ°°μ μ κ±°
- μμ κ³Όμ μ λ°λ³΅νλ©΄ ꡬνλ ꡬκ°μ λͺ¨λ μμκ° λ¨κ² λ¨
π μ½λ ꡬν
π€ λ¬Έμ : μμ νλ³
- 1 μ΄μμ μμ°μλ₯Ό μ λ ₯λ°μ
- μμμ΄λ©΄ true, μλλ©΄ false 리ν΄
π€ λ°λ³΅λ¬Έ μ¬μ©
public class Eratosthenes1 {
public boolean isPrime(int num) {
if(num == 1)
return false;
for(int divisor = 2; divisor < num; divisor++) { // λλ λ¨μ΄μ§λ μκ° μλμ§ μλμ§ νμΈ
// μ΄κΈ°νλ₯Ό 2λΆν° νλ건 1μ΄λ μκΈ° μμ μΈ λλ μ§λκ² μμ΄μ
if(num % divisor == 0)
return false;
}
return true;
}
}
π€ Math ν΄λμ€ μ¬μ©
public class Eratosthenes2 {
public boolean isPrime(int num) {
// Math ν΄λμ€ μ¬μ©
int sqrt = (int)Math.sqrt(num);
if(num == 1)
return false;
for(int i = 2; sqrt >= i; i++) {
if(num % i == 0)
return false;
}
return true;
}
}
π Ref.
μλΌν μ€ν λ€μ€μ 체 - μν€λ°±κ³Ό, μ°λ¦¬ λͺ¨λμ λ°±κ³Όμ¬μ
ko.wikipedia.org