Swift Data Structure And Algorithm/Basic Number Theory

μ—λΌν† μŠ€ν…Œλ„€μŠ€μ˜ 체

youngjaeLee1026 2022. 4. 18. 11:43

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