-
Exercism - Perfect Numbers(with.Kotlin)문제풀이/Exercism 2019. 8. 17. 00:03반응형
[문제]
Determine if a number is perfect, abundant, or deficient based on Nicomachus' (60 - 120 CE) classification scheme for natural numbers.
The Greek mathematician Nicomachus devised a classification scheme for natural numbers, identifying each as belonging uniquely to the categories of perfect, abundant, or deficient based on their aliquot sum. The aliquot sum is defined as the sum of the factors of a number not including the number itself. For example, the aliquot sum of 15 is (1 + 3 + 5) = 9
- Perfect: aliquot sum = number
- 6 is a perfect number because (1 + 2 + 3) = 6
- 28 is a perfect number because (1 + 2 + 4 + 7 + 14) = 28
- Abundant: aliquot sum > number
- 12 is an abundant number because (1 + 2 + 3 + 4 + 6) = 16
- 24 is an abundant number because (1 + 2 + 3 + 4 + 6 + 8 + 12) = 36
- Deficient: aliquot sum < number
- 8 is a deficient number because (1 + 2 + 4) = 7
- Prime numbers are deficient
Implement a way to determine whether a given number is perfect. Depending on your language track, you may also need to implement a way to determine whether a given number is abundant or deficient.
[Solution1]
enum class Classification { DEFICIENT, PERFECT, ABUNDANT } fun classify(naturalNumber: Int): Classification { if(naturalNumber < 1) throw RuntimeException() val listNum = mutableListOf<Int>() for (i in 1 until naturalNumber){ if(naturalNumber % i == 0){ listNum.add(i) } } return when{ naturalNumber == listNum.sum() -> Classification.PERFECT naturalNumber > listNum.sum() -> Classification.DEFICIENT naturalNumber < listNum.sum() -> Classification.ABUNDANT else -> throw RuntimeException() } }
for 문을 사용해서 처리
[Solution2]
enum class Classification { DEFICIENT, PERFECT, ABUNDANT } fun classify(naturalNumber: Int): Classification { if(naturalNumber < 1) throw RuntimeException() val aliquotSum = (1 until naturalNumber).filter { naturalNumber % it == 0 }.sum() return when{ naturalNumber == aliquotSum -> Classification.PERFECT naturalNumber > aliquotSum -> Classification.DEFICIENT naturalNumber < aliquotSum -> Classification.ABUNDANT else -> throw RuntimeException() } }
배열로 나타낸 다음 filter을 사용하여 구분된 값들을 sum()으로 모아서 처리하도록 변경
반응형'문제풀이 > Exercism' 카테고리의 다른 글
Exercism - Diamond(with.Kotlin) (0) 2019.08.27 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 - Difference Of Squares(with.Kotlin) (0) 2019.08.06 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 - Perfect: aliquot sum = number