-
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 를 사용해서 처리하라는 조언에 따라 수정
반응형'문제풀이 > Exercism' 카테고리의 다른 글
Exercism - Largest Series Product (With.Kotlin) (0) 2019.08.21 Exercism - Luhn(with.Kotlin) (0) 2019.08.19 Exercism - Acronym(with.Kotlin) (0) 2019.08.19 Exercism - Perfect Numbers(with.Kotlin) (0) 2019.08.17 Exercism - Scrabble Score (With.Kotlin) (0) 2019.07.30 Exercism - Space Age (With.Kotlin) (0) 2019.07.26 Exercism - Gigasecond(With.Kotlin) (0) 2019.07.23 Exercism - Leap(With.Kotlin) (0) 2019.07.22