ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Exercism - Difference Of Squares(with.Kotlin)
    문제풀이/Exercism 2019. 8. 6. 12:31
    반응형

    [문제]

    Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.

    The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025.

    The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385.

    Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640.

    You are not expected to discover an efficient solution to this yourself from first principles; research is allowed, indeed, encouraged. Finding the best algorithm for the problem is a key skill in software engineering.

     

    [Solution1]

    import kotlin.math.pow
    
    class Squares(num: Int) {
    
        private val numList = (1..num)
    
        fun squareOfSum(): Int = numList.sum().toDouble().pow(2).toInt()
    
        fun sumOfSquares(): Int = numList.map { it.toDouble().pow(2) }.sum().toInt()
    
        fun difference(): Int = squareOfSum() - sumOfSquares()
    
    }

    처음 시도시에는 toDouble().pow(2)를 사용하여 제곱 처리를 함

     

     

    [Solution2]

    class Squares(num: Int) {
    
        private val numList = (1..num)
    
        fun squareOfSum(): Int = numList.sum().squareWithInt()
    
        fun sumOfSquares(): Int = numList.sumBy { it.squareWithInt() }
    
        fun difference(): Int = squareOfSum() - sumOfSquares()
    
    }
    
    private fun Int.squareWithInt(): Int = this * this

     

    Extention 을 사용해서 제곱을 처리하고 Map 과 Sum 을 sumBy 를 사용해서 처리하라는 조언에 따라 수정

    반응형

    댓글

Designed by Tistory.