ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 프로그래머스 / 기사단원의 무기
    코딩 테스트/Level 1 2022. 11. 17. 19:14
    반응형

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

    파이썬

    약수는 제곱근(루트)를 이용해서 계산을 줄일 수 있다. 

    def solution(number, limit, power):
        answer = 0
        for i in range(1, number + 1):
            sqrt_i = i ** .5
            count = sum(1 for j in range(1, int(sqrt_i) + 1) if i % j == 0) * 2 - (0 if sqrt_i % 1 else 1)
            answer += power if limit < count else count
        return answer

    코틀린

    class Solution {
        fun solution(number: Int, limit: Int, power: Int): Int {
            var answer = 0
            for (each in 1..number) {
                var temp = 0
                for (num in 1..each)
                    if (each % num == 0)
                        temp++
                answer += if (temp > limit) power else temp
            }
            return answer
        }
    }
    import kotlin.math.sqrt
    
    class Solution {
        fun solution(number: Int, limit: Int, power: Int): Int {
            var answer = 0
            for (each in 1..number) {
                var temp = 0
                val sqrtEach = sqrt(each.toDouble())
                for (num in 1 until sqrtEach.toInt() + 1)
                    if (each % num == 0)
                        temp++
                temp = temp * 2 - if (sqrtEach % 1 > 0) 0 else 1
                answer += if (temp > limit) power else temp
            }
            return answer
        }
    }
    class Solution {
        fun solution(number: Int, limit: Int, power: Int) = (1..number)
            .map { (1..it).count { each -> it % each == 0 } }
            .sumOf { if (it > limit) power else it }
    }
    import kotlin.math.sqrt
    
    class Solution {
        fun solution(number: Int, limit: Int, power: Int) = (1..number)
            .sumOf {
                val sqrtEach = sqrt(it.toDouble())
                val temp = (
                        (1 until sqrtEach.toInt() + 1).count { each -> it % each == 0 }
                        ) * 2 - if (sqrtEach % 1 > 0) 0 else 1
                if (temp > limit) power else temp
            }
    }
    반응형
Designed by Tistory.