๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Swift ์นด์นด์˜ค 2022 k์ง„์ˆ˜์—์„œ ์†Œ์ˆ˜ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ implementation

by Jouureee 2022. 4. 15.

๋ฌธ์ œ :

https://programmers.co.kr/learn/courses/30/lessons/92335?language=swift 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - k์ง„์ˆ˜์—์„œ ์†Œ์ˆ˜ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ

๋ฌธ์ œ ์„ค๋ช… ์–‘์˜ ์ •์ˆ˜ n์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์ด ์ˆซ์ž๋ฅผ k์ง„์ˆ˜๋กœ ๋ฐ”๊ฟจ์„ ๋•Œ, ๋ณ€ํ™˜๋œ ์ˆ˜ ์•ˆ์— ์•„๋ž˜ ์กฐ๊ฑด์— ๋งž๋Š” ์†Œ์ˆ˜(Prime number)๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€ ์•Œ์•„๋ณด๋ ค ํ•ฉ๋‹ˆ๋‹ค. 0P0์ฒ˜๋Ÿผ ์†Œ์ˆ˜ ์–‘์ชฝ์— 0์ด ์žˆ๋Š” ๊ฒฝ์šฐ P0์ฒ˜๋Ÿผ ์†Œ

programmers.co.kr

๋ถ„์„ :

swift์—๋Š” ์ง„์ˆ˜ ๋ณ€ํ™˜์„ ์‰ฝ๊ฒŒ ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜๊ฐ€ ์žˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋‹ค๋ฅธ์–ธ์–ด๋ณด๋‹ค ๊ฐ„๊ฒฐํ•˜๊ฒŒ ํ‘ผ๊ฑฐ ๊ฐ™๋‹ค 

 

Swift ์ฝ”๋“œ :

//
//  main.swift
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2022/04/15.
//

import Foundation

func isPrime(_ number: Int) -> Bool {
    var bool = false
    if number == 2 || number == 3 { return true }
    let maxDivider = Int(sqrt(Double(number)))
    bool = number > 1 && !(2...maxDivider).contains { number % $0 == 0 }
    
    return bool
}

//์ง„์ˆ˜ ๋ณ€ํ™˜
func solution(_ n:Int, _ k:Int) -> Int {
    var answer = 0
    let kcimal = String(n, radix: k)
    let arr = kcimal.split(separator: "0")
    for (idx, i) in arr.enumerated() {
        if isPrime(Int(i)!) {
            answer += 1
        }
    }
    return answer
}

 

๊ฒฐ๊ณผ :

๋Œ“๊ธ€