1. λ¬Έμ
- νΉμ μ«μκ° μμμΈμ§ μλμ§ νλ³νλκ²μ΄ μλ,
- 2λΆν° μ£Όμ΄μ§ μκΉμ§ λ²μ λ΄μ λͺ¨λ μμλ₯Ό μ°Ύλ μκ³ λ¦¬μ¦μΈ μλΌν μ€ν λ€μ€μ 체λ₯Ό ꡬν
2. λ¬Έμ μ€κ³
- 1μΈ μμκ° μλλ―λ‘, λ°°μ΄μ 1λ²μ§Έ μμμλ 0μ μ μ₯νκ³ 2λΆν° μ£Όμ΄μ§ μκΉμ§ κ° μλ₯Ό λ°°μ΄μ κ·Έμ λμνλ μμΉμ μμλ₯Ό μ μ₯ν¨
- κ°μ₯ μμ μμμΈ 2λΆν° κ·Έμ λ°°μλ€μ λ°°μ΄μμ λͺ¨λ 0μΌλ‘ μ§μλκ°λ©΄ μμλ§ λ¨κ²λ¨
- λ°λΌμ, μ£Όμ΄μ§ μκ° Nμ΄λΌλ©΄ O(N log N)μ νΉμ λ²μλ΄μ λͺ¨λ μμλ₯Ό μ°Ύμ μ μμ
- νΉμ μκ° μμμΈμ§ μλμ§λ₯Ό νλ³νλ λ¬Έμ μμλ μ κ³±κ·Ό κΉμ§ λλμ΄λ³΄λ κ²μ΄ ν¨μ¨μ μ΄κ³ ,
- νΉμ λ²μ λ΄μ λͺ¨λ μμλ₯Ό μ°Ύμ λλ μλΌν μ€ν λ€μ€μ 체λ₯Ό νμ©νλ κ²μ΄ ν¨μ¨μ μ
3. μ 체 μ½λ
//MARK: - μλΌν μ€ν
λ€μ€μ 체
//MARK: - Framework
import Foundation
//MARK: - Variable
var candidates: [Int] = []
//MARK: - Function
func getEratos(_ number: Int) -> Void {
for i in stride(from: 2, through: number, by: 1) {
for j in stride(from: i * 2, through: number, by: i) {
if candidates[j] == 0 {
continue
}
candidates[j] = 0
}
}
}
func solution() -> Void {
//MARK: - Input
guard let N: Int = Int(readLine() ?? "0") else { return }
candidates = Array(repeating: 0, count: N + 10)
for i in stride(from: 2, through: N, by: 1) {
candidates[i] = i
}
//MARK: - Process
getEratos(N)
//MARK: - Output
for i in 1...N {
if candidates[i] == 0 {
continue
}
print("\(candidates[i]) ", terminator: "")
}
}
solution()
μ 체μ½λλ μ¬κΈ°μμ νμΈν μ μμ΅λλ€.
'Swift Data Structure And Algorithm > Basic Number Theory' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
Adv. μμ νλ³ (0) | 2022.04.18 |
---|---|
νμ€μΉΌ μΌκ°ν (0) | 2022.04.18 |
chebyshevtheo (0) | 2022.03.08 |
pfactorization (0) | 2022.03.08 |
fmttalpha (0) | 2022.03.08 |