How to find all happy numbers in a specific range with Kotlin

1 Answer

0 votes
// A happy number is a number that eventually reaches 1 
// when repeatedly replaced by the sum of the squares of its digits.
//
// 19 = 1^2 + 9^2 = 82
// 19 -> 82 -> 68 ->100 -> 1 eventually reaches 1 
// 19 = happy numbe

// Compute the sum of squares of digits of n
fun sumOfDigitSquares(n: Int): Int {
    var num = n
    var sum = 0
    while (num > 0) {
        val d = num % 10
        sum += d * d
        num /= 10
    }
    return sum
}

// Determine whether n is a happy number
fun isHappy(n: Int): Boolean {
    val seen = mutableSetOf<Int>()
    var num = n

    while (num != 1 && num !in seen) {
        seen.add(num)
        num = sumOfDigitSquares(num)
    }
    return num == 1
}

fun main() {
    var a = 1
    var b = 100

    if (a > b) {
        val temp = a
        a = b
        b = temp
    }

    val happyNumbers = mutableListOf<Int>()

    for (i in a..b) {
        if (isHappy(i)) {
            happyNumbers.add(i)
        }
    }

    println("Happy numbers in range [$a, $b]:")
    println(happyNumbers.joinToString(" "))
}



/*
run:

Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100

*/

 



answered Feb 25 by avibootz
...