Last active
June 13, 2022 09:02
-
-
Save tuesd4y/dd194c15ba75a9eb8d9f715eb7e727ca to your computer and use it in GitHub Desktop.
Calculate all happy numbers from 0 to 100
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* What's a happy number? https://en.wikipedia.org/wiki/Happy_number | |
* | |
* Simple brute force solution that just evaluates if the happy number sequence reaches one within [MAX_DEPTH] iterations. | |
*/ | |
object HappyNumbers { | |
const val MAX_DEPTH = 10_000 | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val numbers = (0..100).filter { checkNumber(it) } | |
println(numbers.mapIndexed { index, i -> "$index: $i" }.joinToString("\n")) | |
} | |
fun checkNumber(number: Int, depth: Int = 0): Boolean = | |
number == 1 || (depth < MAX_DEPTH && checkNumber(squareSumOfDigits(number), depth + 1)) | |
private fun squareSumOfDigits(number: Int): Int { | |
return number.toString().map { it.digitToInt() * it.digitToInt() }.sum() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment