๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/Kotlin

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค • ์ฝ”ํ‹€๋ฆฐ] ๊ธฐ์‚ฌ๋‹จ์›์˜ ๋ฌด๊ธฐ #136798

by ํ‚ค์œค 2024. 1. 15.

#136798

๐ŸŽ„ Question ?

https://school.programmers.co.kr/learn/courses/30/lessons/136798#

๐Ÿงฉ Thought Process

  1. ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์…ˆํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“ค๊ณ 
  2. ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ œํ•œ ์ˆ˜ ๋ณด๋‹ค ํฌ๋ฉด ๊ณต๊ฒฉ ์ˆ˜๋ฅผ ๋ฌด๊ฒŒ๋กœ ๋”ํ•ด์ค€๋‹ค.
  3. ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์ฐพ์„ ๋•Œ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ณ ๋ คํ•ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค.
class Solution {
    fun solution(number: Int, limit: Int, power: Int): Int {
        var answer: Int = 0
        for (i in 1..number) {
            var nLCD = countLCD(i)
             when  {
                (nLCD > limit) -> answer += power
                else -> answer += nLCD
            }
        }
        
        return answer
    }
    
    fun countLCD(number: Int): Int {
        var count = 0
        for (i in 1..number) {
            when {
                (number % i == 0) -> count += 1
            }
         
        }
        println(count)
        return count  
    }
}

๐ŸŽ€ Answer

import kotlin.math.sqrt

class Solution {
    fun solution(number: Int, limit: Int, power: Int): Int {
        var answer: Int = 0
        for (i in 1..number) {
            var nLCD = countLCD(i)
             when  {
                (nLCD > limit) -> answer += power
                else -> answer += nLCD
            }
        }
        
        return answer 
    }
    
    fun countLCD(number: Int): Int {
        var count = 0
        if (number == 1) {
            count += 1
        } else {
            count += 2
            for (i in 2 .. sqrt(number.toDouble()).toInt()) {
                if (number%i == 0)  {
                    when {
                        (i*i == number) -> count += 1
                        else -> count += 2
                    }
                }
            }
        }
        return count 
    }
}

 

๐ŸŽ Result

๐Ÿ† Comment