Skip to content

Instantly share code, notes, and snippets.

@tuesd4y
Last active June 13, 2022 09:02
Show Gist options
  • Save tuesd4y/dd194c15ba75a9eb8d9f715eb7e727ca to your computer and use it in GitHub Desktop.
Save tuesd4y/dd194c15ba75a9eb8d9f715eb7e727ca to your computer and use it in GitHub Desktop.
Calculate all happy numbers from 0 to 100
/**
* 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